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
/*
 * COPYRIGHT:       See COPYING.ARM in the top level directory
 * PROJECT:         ReactOS UEFI Boot Library
 * FILE:            boot/environ/lib/misc/image.c
 * PURPOSE:         Boot Library Image Routines
 * PROGRAMMER:      Alex Ionescu (alex.ionescu@reactos.org)
 */

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

#include "bl.h"
#include <bcd.h>

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

ULONG IapAllocatedTableEntries;
ULONG IapTableEntries;
PVOID* IapImageTable;

#ifndef _M_ARM
KDESCRIPTOR GdtRegister;
KDESCRIPTOR IdtRegister;
KDESCRIPTOR BootAppGdtRegister;
KDESCRIPTOR BootAppIdtRegister;
PVOID BootApp32EntryRoutine;
PBOOT_APPLICATION_PARAMETER_BLOCK BootApp32Parameters;
PVOID BootApp32Stack;
#endif

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

NTSTATUS
ImgpGetFileSize (
    _In_ PBL_IMG_FILE File,
    _Out_ PULONG FileSize
    )
{
    NTSTATUS Status;
    ULONG Size;
    BL_FILE_INFORMATION FileInformation;

    /* Check if the file was memory mapped */
    if (File->Flags & BL_IMG_MEMORY_FILE)
    {
        /* Just read the size of the mapping */
        Size = File->FileSize;
    }
    else
    {
        /* Do file I/O to get the file size */
        Status = BlFileGetInformation(File->FileId,
                                      &FileInformation);
        if (!NT_SUCCESS(Status))
        {
            return Status;
        }

        /* We only support files less than 4GB in the Image Mapped */
        Size = FileInformation.Size;
        if (FileInformation.Size > ULONG_MAX)
        {
            return STATUS_NOT_SUPPORTED;
        }
    }

    /* Return the size and success */
    *FileSize = Size;
    return STATUS_SUCCESS;
}

NTSTATUS
ImgpReadAtFileOffset (
    _In_ PBL_IMG_FILE File,
    _In_ ULONG Size,
    _In_ ULONGLONG ByteOffset,
    _In_ PVOID Buffer,
    _Out_ PULONG BytesReturned
    )
{
    NTSTATUS Status;

    /* Check what if this is a mapped file or not */
    if (File->Flags & BL_IMG_MEMORY_FILE)
    {
        /* Check if the boundaries are within the file size */
        if ((ByteOffset + Size) <= File->FileSize)
        {
            /* Yep, copy into the caller-supplied buffer */
            RtlCopyMemory(Buffer,
                          (PVOID)((ULONG_PTR)File->BaseAddress + (ULONG_PTR)ByteOffset),
                          Size);

            /* If caller wanted to know, return the size copied */
            if (BytesReturned)
            {
                *BytesReturned = Size;
            }

            /* All good */
            Status = STATUS_SUCCESS;
        }
        else
        {
            /* Doesn't fit */
            Status = STATUS_INVALID_PARAMETER;
        }
    }
    else
    {
        /* Issue the file I/O instead */
        Status = BlFileReadAtOffsetEx(File->FileId,
                                      Size,
                                      ByteOffset,
                                      Buffer,
                                      BytesReturned,
                                      0);
    }

    /* Return the final status */
    return Status;
}

NTSTATUS
ImgpOpenFile (
    _In_ ULONG DeviceId,
    _In_ PWCHAR FileName,
    _In_ ULONG Flags,
    _Out_ PBL_IMG_FILE NewFile
    )
{
    NTSTATUS Status;
    ULONG FileSize;
    ULONGLONG RemoteFileSize;
    PVOID RemoteFileAddress;
    ULONG FileId;

    /* First, try to see if BD has this file remotely */
    Status = BlBdPullRemoteFile(FileName,
                                &RemoteFileAddress,
                                &RemoteFileSize);
    if (NT_SUCCESS(Status))
    {
        /* Yep, get the file size and make sure it's < 4GB */
        FileSize = RemoteFileSize;
        if (RemoteFileSize <= ULONG_MAX)
        {
            /* Remember this is a memory mapped remote file */
            NewFile->Flags |= (BL_IMG_MEMORY_FILE | BL_IMG_REMOTE_FILE);
            NewFile->FileSize = FileSize;
            NewFile->BaseAddress = RemoteFileAddress;
            goto Quickie;
        }
    }

    /* Use File I/O instead */
    Status = BlFileOpen(DeviceId,
                        FileName,
                        BL_FILE_READ_ACCESS,
                        &FileId);
    if (!NT_SUCCESS(Status))
    {
        /* Bail out on failure */
        return Status;
    }

    /* Make sure nobody thinks this is a memory file */
    NewFile->Flags &= ~BL_IMG_MEMORY_FILE;
    NewFile->FileId = FileId;

Quickie:
    /* Set common data for both memory and I/O based file */
    NewFile->Flags |= BL_IMG_VALID_FILE;
    NewFile->FileName = FileName;
    return Status;
}

NTSTATUS
ImgpCloseFile (
    _In_ PBL_IMG_FILE File
    )
{
    NTSTATUS Status;

    /* Make sure this is a valid file, otherwise no-op */
    Status = STATUS_SUCCESS;
    if (File->Flags & BL_IMG_VALID_FILE)
    {
        /* Is this a memory mapped file? */
        if (!(File->Flags & BL_IMG_MEMORY_FILE))
        {
            /* Nope, close the file handle */
            return BlFileClose(File->FileId);
        }

        /* Is this a remote file? */
        if (File->Flags & BL_IMG_REMOTE_FILE)
        {
            /* Then only free the memory in that scenario */
            return MmPapFreePages(File->BaseAddress, BL_MM_INCLUDE_MAPPED_ALLOCATED);
        }
    }

    /* Return the final status */
    return Status;
}

NTSTATUS
BlImgUnallocateImageBuffer (
    _In_ PVOID ImageBase,
    _In_ ULONG ImageSize,
    _In_ ULONG ImageFlags
    )
{
    PHYSICAL_ADDRESS PhysicalAddress;
    NTSTATUS Status;

    /* Make sure required parameters are present */
    if (!(ImageBase) || !(ImageSize))
    {
        return STATUS_INVALID_PARAMETER;
    }

    /* Check if this was a physical allocation */
    if (!(ImageFlags & BL_LOAD_IMG_VIRTUAL_BUFFER))
    {
        return MmPapFreePages(ImageBase, BL_MM_INCLUDE_MAPPED_ALLOCATED);
    }

    /* It's virtual, so translate it first */
    if (!BlMmTranslateVirtualAddress(ImageBase, &PhysicalAddress))
    {
        return STATUS_INVALID_PARAMETER;
    }

    /* Unmap the virtual mapping */
    Status = BlMmUnmapVirtualAddressEx(ImageBase, ROUND_TO_PAGES(ImageSize));
    if (NT_SUCCESS(Status))
    {
        /* Now free the physical pages */
        Status = BlMmFreePhysicalPages(PhysicalAddress);
    }

    /* All done */
    return Status;
}

NTSTATUS
BlImgAllocateImageBuffer (
    _Inout_ PVOID* ImageBuffer,
    _In_ ULONG MemoryType,
    _In_ ULONGLONG ImageSize,
    _In_ ULONG Flags
    )
{
    ULONG Attributes;
    ULONGLONG Pages, Size;
    PVOID MappedBase, CurrentBuffer;
    NTSTATUS Status;
    PHYSICAL_ADDRESS PhysicalAddress;

    /* Read and reset the current buffer address */
    CurrentBuffer = *ImageBuffer;
    *ImageBuffer = NULL;

    /* Align the image size to page */
    Size = ROUND_TO_PAGES(ImageSize);

    /* Not sure what this attribute does yet */
    Attributes = 0;
    if (Flags & BL_LOAD_IMG_UNKNOWN_BUFFER_FLAG)
    {
        Attributes = 0x10000;
    }

    /* Check if the caller wants a virtual buffer */
    if (Flags & BL_LOAD_IMG_VIRTUAL_BUFFER)
    {
        /* Set the physical address to the current buffer */
        PhysicalAddress.QuadPart = (ULONG_PTR)CurrentBuffer;
        Pages = Size >> PAGE_SHIFT;

        /* Allocate the physical pages */
        Status = BlMmAllocatePhysicalPages(&PhysicalAddress,
                                           Pages,
                                           MemoryType,
                                           Attributes,
                                           0);
        if (!NT_SUCCESS(Status))
        {
            /* If that failed, remove allocation attributes */
            PhysicalAddress.QuadPart = 0;
            Attributes &= ~BlMemoryValidAllocationAttributeMask,
            Status = BlMmAllocatePhysicalPages(&PhysicalAddress,
                                               Pages,
                                               MemoryType,
                                               Attributes,
                                               0);
        }

        /* Check if either attempts succeeded */
        if (!NT_SUCCESS(Status))
        {
            return Status;
        }

        /* Now map the physical buffer at the address requested */
        MappedBase = PhysicalAddressToPtr(PhysicalAddress);
        Status = BlMmMapPhysicalAddressEx(&MappedBase,
                                          BlMemoryFixed,
                                          Size,
                                          PhysicalAddress);
        if (!NT_SUCCESS(Status))
        {
            /* Free on failure if needed */
            BlMmFreePhysicalPages(PhysicalAddress);
            return Status;
        }
    }
    else
    {
        /* Otherwise, allocate raw physical pages */
        MappedBase = CurrentBuffer;
        Pages = Size >> PAGE_SHIFT;
        Status = MmPapAllocatePagesInRange(&MappedBase,
                                           MemoryType,
                                           Pages,
                                           Attributes,
                                           0,
                                           NULL,
                                           0);
        if (!NT_SUCCESS(Status))
        {
            /* If that failed, try without allocation attributes */
            MappedBase = NULL;
            Attributes &= ~BlMemoryValidAllocationAttributeMask,
            Status = MmPapAllocatePagesInRange(&MappedBase,
                                               MemoryType,
                                               Pages,
                                               Attributes,
                                               0,
                                               NULL,
                                               0);
        }

        /* Check if either attempts succeeded */
        if (!NT_SUCCESS(Status))
        {
            return Status;
        }
    }

    /* Success path, returned allocated address */
    *ImageBuffer = MappedBase;
    return STATUS_SUCCESS;
}

NTSTATUS
BlImgLoadImageWithProgress2 (
    _In_ ULONG DeviceId,
    _In_ BL_MEMORY_TYPE MemoryType,
    _In_ PWCHAR FileName,
    _Inout_ PVOID* MappedBase,
    _Inout_ PULONG MappedSize,
    _In_ ULONG ImageFlags,
    _In_ BOOLEAN ShowProgress,
    _Out_opt_ PUCHAR* HashBuffer,
    _Out_opt_ PULONG HashSize
    )
{
    NTSTATUS Status;
    PVOID BaseAddress, Buffer;
    ULONG RemainingLength, CurrentSize, ImageSize, ReadSize;
    BOOLEAN ComputeSignature, ComputeHash, Completed;
    BL_IMG_FILE FileHandle;
    ULONGLONG ByteOffset;
    PHYSICAL_ADDRESS PhysicalAddress;

    /* Initialize variables */
    BaseAddress = 0;
    ImageSize = 0;
    Completed = FALSE;
    RtlZeroMemory(&FileHandle, sizeof(FileHandle));

    /* Check for missing parameters */
    if (!MappedBase)
    {
        Status = STATUS_INVALID_PARAMETER;
        goto Quickie;
    }
    if (!FileName)
    {
        Status = STATUS_INVALID_PARAMETER;
        goto Quickie;
    }
    if (!MappedSize)
    {
        Status = STATUS_INVALID_PARAMETER;
        goto Quickie;
    }

    /* Check if the image buffer is being provided */
    if (ImageFlags & BL_LOAD_IMG_EXISTING_BUFFER)
    {
        /* An existing base must already exist */
        if (!(*MappedBase))
        {
            Status = STATUS_INVALID_PARAMETER;
            goto Quickie;
        }
    }

    /* Check of a hash is being requested */
    if (ImageFlags & BL_LOAD_IMG_COMPUTE_HASH)
    {
        /* Make sure we can return the hash */
        if (!HashBuffer)
        {
            Status = STATUS_INVALID_PARAMETER;
            goto Quickie;
        }
        if (!HashSize)
        {
            Status = STATUS_INVALID_PARAMETER;
            goto Quickie;
        }
    }

    /* Check for invalid combination of parameters */
    if ((ImageFlags & BL_LOAD_IMG_COMPUTE_HASH) && (ImageFlags & 0x270))
    {
        Status = STATUS_INVALID_PARAMETER;
        goto Quickie;
    }

    /* Initialize hash if requested by caller */
    if (HashBuffer)
    {
        *HashBuffer = 0;
    }

    /* Do the same for the hash size */
    if (HashSize)
    {
        *HashSize = 0;
    }

    /* Open the image file */
    Status = ImgpOpenFile(DeviceId, FileName, DeviceId, &FileHandle);
    if (!NT_SUCCESS(Status))
    {
        EfiPrintf(L"Error opening file: %lx\r\n", Status);
        goto Quickie;
    }

    /* Get the size of the image */
    Status = ImgpGetFileSize(&FileHandle, &ImageSize);
    if (!NT_SUCCESS(Status))
    {
        EfiPrintf(L"Error getting file size: %lx\r\n", Status);
        goto Quickie;
    }

    /* Read the current base address */
    BaseAddress = *MappedBase;
    if (ImageFlags & BL_LOAD_IMG_EXISTING_BUFFER)
    {
        /* Check if the current buffer is too small */
        if (*MappedSize < ImageSize)
        {
            /* Return the required size of the buffer */
            *MappedSize = ImageSize;
            Status = STATUS_BUFFER_TOO_SMALL;
        }
    }
    else
    {
        /* A buffer was not provided, allocate one ourselves */
        Status = BlImgAllocateImageBuffer(&BaseAddress,
                                          MemoryType,
                                          ImageSize,
                                          ImageFlags);
    }

    /* Bail out if allocation failed */
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Set the initial byte offset and length to read */
    RemainingLength = ImageSize;
    ByteOffset = 0;
    Buffer = BaseAddress;

    /* Update the initial progress */
    Completed = FALSE;
    if (ShowProgress)
    {
        BlUtlUpdateProgress(0, &Completed);
        ShowProgress &= (Completed != 0) - 1;
    }

    /* Set the chunk size for each read */
    ReadSize = 0x100000;
    if (ReadSize > ImageSize)
    {
        ReadSize = ImageSize;
    }

    /* Check if we should compute hash and/or signatures */
    ComputeSignature = ImageFlags & BL_LOAD_IMG_COMPUTE_SIGNATURE;
    ComputeHash = FALSE;
    if ((ComputeSignature) || (ImageFlags & BL_LOAD_IMG_COMPUTE_HASH))
    {
        ComputeHash = TRUE;
        // todo: crypto is hard
    }

    /* Begin the read loop */
    while (RemainingLength)
    {
        /* Check if we've got more than a chunk left to read */
        if (RemainingLength > ReadSize)
        {
            /* Read a chunk*/
            CurrentSize = ReadSize;
        }
        else
        {
            /* Read only what's left */
            CurrentSize = RemainingLength;
        }

        /* Read the chunk */
        Status = ImgpReadAtFileOffset(&FileHandle,
                                      CurrentSize,
                                      ByteOffset,
                                      Buffer,
                                      0);
        if (!NT_SUCCESS(Status))
        {
            goto Quickie;
        }

        /* Check if we need to compute the hash of this chunk */
        if (ComputeHash)
        {
            // todo: crypto is hard
        }

        /* Update our position and read information */
        Buffer = (PVOID)((ULONG_PTR)Buffer + CurrentSize);
        RemainingLength -= CurrentSize;
        ByteOffset += CurrentSize;

        /* Check if we should update the progress bar */
        if (ShowProgress)
        {
            /* Compute new percentage completed, check if we're done */
            BlUtlUpdateProgress(100 - 100 * RemainingLength / ImageSize,
                                &Completed);
            ShowProgress &= (Completed != 0) - 1;
        }
    }

    /* Is the read fully complete? We need to finalize the hash if requested */
    if (ComputeHash)
    {
        // todo: CRYPTO IS HARD
    }

    /* Success path, return back the buffer and the size of the image */
    *MappedBase = BaseAddress;
    *MappedSize = ImageSize;

Quickie:
    /* Close the file handle */
    ImgpCloseFile(&FileHandle);

    /* Check if we failed and had allocated a buffer */
    if (!(NT_SUCCESS(Status)) &&
        (BaseAddress) &&
        !(ImageFlags & BL_LOAD_IMG_EXISTING_BUFFER))
    {
        /* Check what kind of buffer we had allocated */
        if (ImageFlags & BL_LOAD_IMG_VIRTUAL_BUFFER)
        {
            /* Unmap and free the virtual buffer */
            PhysicalAddress.QuadPart = (ULONG_PTR)BaseAddress;
            BlMmUnmapVirtualAddressEx(BaseAddress, ImageSize);
            BlMmFreePhysicalPages(PhysicalAddress);
        }
        else
        {
            /* Free the physical buffer */
            MmPapFreePages(BaseAddress, BL_MM_INCLUDE_MAPPED_ALLOCATED);
        }
    }

    /* If we hadn't gotten to 100% yet, do it now */
    if (ShowProgress)
    {
        BlUtlUpdateProgress(100, &Completed);
    }

    /* Return the final status */
    return Status;
}

PIMAGE_SECTION_HEADER 
BlImgFindSection (
    _In_ PVOID ImageBase,
    _In_ ULONG ImageSize
    )
{
    PIMAGE_SECTION_HEADER FoundSection;
    ULONG i;
    PIMAGE_SECTION_HEADER SectionHeader;
    PIMAGE_NT_HEADERS NtHeader;
    NTSTATUS Status;

    /* Assume failure */
    FoundSection = NULL;

    /* Make sure the image is valid */
    Status = RtlImageNtHeaderEx(0, ImageBase, ImageSize, &NtHeader);
    if (NT_SUCCESS(Status))
    {
        /* Get the first section and loop through them all */
        SectionHeader = IMAGE_FIRST_SECTION(NtHeader);
        for (i = 0; i < NtHeader->FileHeader.NumberOfSections; i++)
        {
            /* Check if this is the resource section */
            if (!_stricmp((PCCH)SectionHeader->Name, ".rsrc"))
            {
                /* Yep, we're done */
                FoundSection = SectionHeader;
                break;
            }

            /* Nope, keep going */
            SectionHeader++;
        }
    }

    /* Return the matching section */
    return FoundSection;
}

VOID
BlImgQueryCodeIntegrityBootOptions (
    _In_ PBL_LOADED_APPLICATION_ENTRY ApplicationEntry,
    _Out_ PBOOLEAN IntegrityChecksDisabled, 
    _Out_ PBOOLEAN TestSigning
    )
{
    
    NTSTATUS Status;
    BOOLEAN Value;

    /* Check if /DISABLEINTEGRITYCHECKS is on */
    Status = BlGetBootOptionBoolean(ApplicationEntry->BcdData,
                                    BcdLibraryBoolean_DisableIntegrityChecks,
                                    &Value);
    *IntegrityChecksDisabled = NT_SUCCESS(Status) && (Value);

    /* Check if /TESTSIGNING is on */
    Status = BlGetBootOptionBoolean(ApplicationEntry->BcdData,
                                    BcdLibraryBoolean_AllowPrereleaseSignatures,
                                    &Value);
    *TestSigning = NT_SUCCESS(Status) && (Value);
}

NTSTATUS
BlImgUnLoadImage (
    _In_ PVOID ImageBase,
    _In_ ULONG ImageSize,
    _In_ ULONG ImageFlags
    )
{
    /* Check for missing parameters */
    if (!(ImageSize) || !(ImageBase))
    {
        /* Bail out */
        return STATUS_INVALID_PARAMETER;
    }

    /* Unallocate the image buffer */
    return BlImgUnallocateImageBuffer(ImageBase, ImageSize, ImageFlags);
}

NTSTATUS
ImgpLoadPEImage (
    _In_ PBL_IMG_FILE ImageFile,
    _In_ BL_MEMORY_TYPE MemoryType,
    _Inout_ PVOID* ImageBase,
    _Out_opt_ PULONG ImageSize,
    _Inout_opt_ PVOID Hash,
    _In_ ULONG Flags
    )
{
    NTSTATUS Status;
    ULONG FileSize, HeaderSize;
    BL_IMG_FILE LocalFileBuffer;
    PBL_IMG_FILE LocalFile;
    PVOID VirtualAddress, PreferredBase, ImageBuffer, CertBuffer, HashBuffer;
    ULONGLONG VirtualSize;
    PIMAGE_DATA_DIRECTORY CertDirectory;
    PHYSICAL_ADDRESS PhysicalAddress;
    PIMAGE_NT_HEADERS NtHeaders;
    USHORT SectionCount, CheckSum, PartialSum, FinalSum;
    PIMAGE_SECTION_HEADER Section;
    ULONG_PTR EndOfHeaders, SectionStart, Slack, SectionEnd;
    ULONG i, SectionSize, RawSize, BytesRead, RemainingLength, Offset, AlignSize;
    BOOLEAN First, ImageHashValid;
    UCHAR LocalBuffer[1024];
    UCHAR TrustedBootInformation[52];
    ULONG WorkaroundForBinutils;

    /* Initialize locals */
    WorkaroundForBinutils = 0;
    LocalFile = NULL;
    ImageBuffer = NULL;
    FileSize = 0;
    First = FALSE;
    VirtualAddress = NULL;
    CertBuffer = NULL;
    CertDirectory = NULL;
    HashBuffer = NULL;
    Offset = 0;
    VirtualSize = 0;
    ImageHashValid = FALSE;
    RtlZeroMemory(&TrustedBootInformation, sizeof(TrustedBootInformation));

    /* Get the size of the image */
    Status = ImgpGetFileSize(ImageFile, &FileSize);
    if (!NT_SUCCESS(Status))
    {
        return STATUS_FILE_INVALID;
    }

    /* Allocate a flat buffer for it */
    Status = BlImgAllocateImageBuffer(&ImageBuffer, BlLoaderData, FileSize, 0);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Read the whole file flat for now */
    Status = ImgpReadAtFileOffset(ImageFile, FileSize, 0, ImageBuffer, NULL);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Build a local file handle */
    LocalFile = &LocalFileBuffer;
    LocalFileBuffer.FileName = ImageFile->FileName;
    LocalFileBuffer.Flags = BL_IMG_MEMORY_FILE | BL_IMG_VALID_FILE;
    LocalFileBuffer.BaseAddress = ImageBuffer;
    LocalFileBuffer.FileSize = FileSize;

    /* Get the NT headers of the file */
    Status = RtlImageNtHeaderEx(0, ImageBuffer, FileSize, &NtHeaders);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Check if we should validate the machine type */
    if (Flags & BL_LOAD_PE_IMG_CHECK_MACHINE)
    {
        /* Is it different than our current machine type? */
#if _M_AMD64
        if (NtHeaders->FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64)
#else
        if (NtHeaders->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)<--- outer condition: NtHeaders->FileHeader.Machine!=IMAGE_FILE_MACHINE_I386
#endif
        {
            /* Is it x86 (implying we are x64) ? */
            if (NtHeaders->FileHeader.Machine == IMAGE_FILE_MACHINE_I386)<--- opposite inner condition: NtHeaders->FileHeader.Machine==IMAGE_FILE_MACHINE_I386
            {
                /* Return special error code */
                Status = STATUS_INVALID_IMAGE_WIN_32;
            }
            else if (NtHeaders->FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64)
            {
                /* Otherwise, it's x64 but we are x86 */
                Status = STATUS_INVALID_IMAGE_WIN_64;
            }
            else
            {
                /* Or it's ARM or something... */
                Status = STATUS_INVALID_IMAGE_FORMAT;
            }

            /* Return with the distinguished error code */
            goto Quickie;
        }
    }

    /* Check if we should validate the subsystem */
    if (Flags & BL_LOAD_PE_IMG_CHECK_SUBSYSTEM)
    {
        /* It must be a Windows boot Application */
        if (NtHeaders->OptionalHeader.Subsystem !=
            IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION)
        {
            Status = STATUS_INVALID_IMAGE_FORMAT;
            goto Quickie;
        }
    }

    /* Check if we should validate the /INTEGRITYCHECK flag */
    if (Flags & BL_LOAD_PE_IMG_CHECK_FORCED_INTEGRITY)
    {
        /* Check if it's there */
        if (!(NtHeaders->OptionalHeader.DllCharacteristics &
              IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY))
        {
            /* Nope, fail otherwise */
            Status = STATUS_INVALID_IMAGE_FORMAT;
            goto Quickie;
        }
    }

    /* Check if we should compute the image hash */
    if ((Flags & BL_LOAD_PE_IMG_COMPUTE_HASH) || (Hash))
    {
        EfiPrintf(L"No hash support\r\n");
    }

    /* Read the current base address, if any */
    VirtualAddress = *ImageBase;

    /* Get the virtual size of the image */
    VirtualSize = NtHeaders->OptionalHeader.SizeOfImage;

    /* Safely align the virtual size to a page */
    Status = RtlULongLongAdd(VirtualSize,
                             PAGE_SIZE - 1,
                             &VirtualSize);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }
    VirtualSize = ALIGN_DOWN_BY(VirtualSize, PAGE_SIZE);

    /* Make sure the image isn't larger than 4GB */
    if (VirtualSize > ULONG_MAX)
    {
        Status = STATUS_INVALID_IMAGE_FORMAT;
        goto Quickie;
    }

    /* Check if we have a buffer already */
    if (Flags & BL_LOAD_IMG_EXISTING_BUFFER)
    {
        /* Check if it's too small */
        if (*ImageSize < VirtualSize)
        {
            /* Fail, letting the caller know how big to make it */
            *ImageSize = VirtualSize;
            Status = STATUS_BUFFER_TOO_SMALL;
        }
    }
    else
    {
        /* Allocate the buffer with the flags and type the caller wants */
        Status = BlImgAllocateImageBuffer(&VirtualAddress,
                                          MemoryType,
                                          VirtualSize,
                                          Flags);
    }

    /* Bail out if allocation failed, or existing buffer is too small */
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Read the size of the headers */
    HeaderSize = NtHeaders->OptionalHeader.SizeOfHeaders;
    if (VirtualSize < HeaderSize)
    {
        /* Bail out if they're bigger than the image! */
        Status = STATUS_INVALID_IMAGE_FORMAT;
        goto Quickie;
    }

    /* Now read the header into the buffer */
    Status = ImgpReadAtFileOffset(LocalFile, HeaderSize, 0, VirtualAddress, NULL);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Get the NT headers of the file */
    Status = RtlImageNtHeaderEx(0, VirtualAddress, HeaderSize, &NtHeaders);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    First = FALSE;

    /* Record how many sections we have */
    SectionCount = NtHeaders->FileHeader.NumberOfSections;

    /* Capture the current checksum and reset it */
    CheckSum = NtHeaders->OptionalHeader.CheckSum;
    NtHeaders->OptionalHeader.CheckSum = 0;

    /* Calculate the checksum of the header, and restore the original one */
    PartialSum = BlUtlCheckSum(0,
                               VirtualAddress,
                               HeaderSize,
                               BL_UTL_CHECKSUM_COMPLEMENT |
                               BL_UTL_CHECKSUM_USHORT_BUFFER);
    NtHeaders->OptionalHeader.CheckSum = CheckSum;

    /* Record our current position (right after the headers) */
    EndOfHeaders = (ULONG_PTR)VirtualAddress + HeaderSize;

    /* Get the first section and iterate through each one */
    Section = IMAGE_FIRST_SECTION(NtHeaders);
    for (i = 0; i < SectionCount; i++)
    {
        /* Compute where this section starts */
        SectionStart = (ULONG_PTR)VirtualAddress + Section->VirtualAddress;

        /* Make sure that the section fits within the image */
        if ((VirtualSize < Section->VirtualAddress) ||
            ((PVOID)SectionStart < VirtualAddress))
        {
            EfiPrintf(L"fail 1\r\n");
            Status = STATUS_INVALID_IMAGE_FORMAT;
            goto Quickie;
        }

        /* Check if there's slack space between header end and the section */
        if (!(First) && (EndOfHeaders < SectionStart))
        {
            /* Zero it out */
            Slack = SectionStart - EndOfHeaders;
            RtlZeroMemory((PVOID)EndOfHeaders, Slack);
        }

        /* Get the section virtual size and the raw size */
        SectionSize = Section->Misc.VirtualSize;
        RawSize = Section->SizeOfRawData;

        /* Safely align the raw size by 2 */
        Status = RtlULongAdd(RawSize, 1, &AlignSize);
        if (!NT_SUCCESS(Status))
        {
            goto Quickie;
        }
        AlignSize = ALIGN_DOWN_BY(AlignSize, 2);

        /* IF we don't have a virtual size, use the raw size */
        if (!SectionSize)
        {
            SectionSize = RawSize;
        }

        /* If we don't have raw data, ignore the raw size */
        if (!Section->PointerToRawData)
        {
            RawSize = 0;
        }
        else if (SectionSize < RawSize)
        {
            /* And if the virtual size is smaller, use it as the final size */
            RawSize = SectionSize;
        }

        /* Make sure that the section doesn't overflow in memory */
        Status = RtlULongPtrAdd(Section->VirtualAddress,
                                SectionSize,
                                &SectionEnd);
        if (!NT_SUCCESS(Status))
        {
            EfiPrintf(L"fail 21\r\n");
            Status = STATUS_INVALID_IMAGE_FORMAT;
            goto Quickie;
        }

        /* Make sure that it fits within the image */
        if (VirtualSize < SectionEnd)
        {
            Status = STATUS_INVALID_IMAGE_FORMAT;
            goto Quickie;
        }

        /* Make sure it doesn't overflow on disk */
        Status = RtlULongPtrAdd(Section->VirtualAddress,
                                AlignSize,
                                &SectionEnd);
        if (!NT_SUCCESS(Status))
        {
            EfiPrintf(L"fail 31\r\n");
            Status = STATUS_INVALID_IMAGE_FORMAT;
            goto Quickie;
        }

        /* Make sure that it fits within the disk image as well */
        if (VirtualSize < SectionEnd)
        {
            Status = STATUS_INVALID_IMAGE_FORMAT;
            goto Quickie;
        }

        /* So does this section have a valid size after all? */
        if (RawSize)
        {
            /* Are we in the first iteration? */
            if (!First)
            {
                /* FUCK YOU BINUTILS */
                if (NtHeaders->OptionalHeader.MajorLinkerVersion < 7)
                {
                    if ((*(PULONG)&Section->Name == 'ler.') && (RawSize < AlignSize))
                    {
                        /* Piece of shit won't build relocations when you tell it to,
                         * either by using --emit-relocs or --dynamicbase. People online
                         * have found out that by using -pie-executable you can get this
                         * to happen, but then it turns out that the .reloc section is
                         * incorrectly sized, and results in a corrupt PE. However, they
                         * still compute the checksum using the correct value. What idiots.
                         */
                        WorkaroundForBinutils = AlignSize - RawSize;
                        AlignSize -= WorkaroundForBinutils;
                    }
                }

                /* Yes, read the section data */
                Status = ImgpReadAtFileOffset(LocalFile,
                                              AlignSize,
                                              Section->PointerToRawData,
                                              (PVOID)SectionStart,
                                              NULL);
                if (!NT_SUCCESS(Status))
                {
                    goto Quickie;
                }

                /* Update our current offset */
                Offset = AlignSize + Section->PointerToRawData;

                /* Update the checksum to include this section */
                PartialSum = BlUtlCheckSum(PartialSum,
                                           (PUCHAR)SectionStart,
                                           AlignSize,
                                           BL_UTL_CHECKSUM_COMPLEMENT |
                                           BL_UTL_CHECKSUM_USHORT_BUFFER);
                AlignSize += WorkaroundForBinutils;
            }
        }

        /* Are we in the first iteration? */
        if (!First)
        {
            /* Is there space at the end of the section? */
            if (RawSize < SectionSize)
            {
                /* Zero out the slack space that's there */
                Slack = SectionSize - RawSize;
                RtlZeroMemory((PVOID)(SectionStart + RawSize), Slack);
            }

            /* Update our tail offset */
            EndOfHeaders = SectionStart + SectionSize;
        }

        /* Move to the next section */
        Section++;
    }

    /* Are we in the first iteration? */
    if (!First)
    {
        /* Go to the end of the file */
        SectionStart = (ULONG_PTR)VirtualAddress + VirtualSize;

        /* Is there still some slack space left? */
        if (EndOfHeaders < SectionStart)
        {
            /* Zero it out */
            Slack = SectionStart - EndOfHeaders;
            RtlZeroMemory((PVOID)EndOfHeaders, Slack);
        }
    }

    /* Did the first iteration complete OK? */
    if ((NT_SUCCESS(Status)) && !(First))
    {
        /* Check how many non-image bytes are left in the file */
        RemainingLength = FileSize - Offset;
        while (RemainingLength)
        {
            /* See if the read will fit into our local buffer */
            if (RemainingLength >= sizeof(LocalBuffer))
            {
                /* Nope, cap it */
                BytesRead = sizeof(LocalBuffer);
            }
            else
            {
                /* Yes, but there's less to read */
                BytesRead = RemainingLength;
            }

            /* Read 1024 bytes into the local buffer */
            Status = ImgpReadAtFileOffset(LocalFile,
                                          BytesRead,
                                          Offset,
                                          LocalBuffer,
                                          &BytesRead);
            if (!(NT_SUCCESS(Status)) || !(BytesRead))
            {
                Status = STATUS_FILE_INVALID;
                goto Quickie;
            }

            /* Advance the offset and reduce the length */
            RemainingLength -= BytesRead;
            Offset += BytesRead;

            /* Compute the checksum of this leftover space */
            PartialSum = BlUtlCheckSum(PartialSum,
                                       LocalBuffer,
                                       BytesRead,
                                       BL_UTL_CHECKSUM_COMPLEMENT |
                                       BL_UTL_CHECKSUM_USHORT_BUFFER);
        }

        /* Finally, calculate the final checksum and compare it */
        FinalSum = FileSize + PartialSum + WorkaroundForBinutils;
        if ((FinalSum != CheckSum) && (PartialSum == 0xFFFF))
        {
            /* It hit overflow, so set it to the file size */
            FinalSum = FileSize;
        }

        /* If the checksum doesn't match, and caller is enforcing, bail out */
        if ((FinalSum != CheckSum) &&
            !(Flags & BL_LOAD_PE_IMG_IGNORE_CHECKSUM_MISMATCH))
        {
            Status = STATUS_IMAGE_CHECKSUM_MISMATCH;
            goto Quickie;
        }
    }

    /* Check if the .rsrc section should be checked with the filename */
    if (Flags & BL_LOAD_PE_IMG_VALIDATE_ORIGINAL_FILENAME)
    {
        EfiPrintf(L"Not yet supported\r\n");
        Status = 0xC0430007; // STATUS_SECUREBOOT_FILE_REPLACED
        goto Quickie;
    }

    /* Check if we should relocate */
    if (!(Flags & BL_LOAD_PE_IMG_SKIP_RELOCATIONS))
    {
        /* Check if we loaded at a different address */
        PreferredBase = (PVOID)NtHeaders->OptionalHeader.ImageBase;
        if (VirtualAddress != PreferredBase)
        {
            /* Yep -- do relocations */
            Status = LdrRelocateImage(VirtualAddress,
                                      "Boot Environment Library",
                                      STATUS_SUCCESS,
                                      STATUS_UNSUCCESSFUL,
                                      STATUS_INVALID_IMAGE_FORMAT);
            if (!NT_SUCCESS(Status))
            {
                /* That's bad */
                goto Quickie;
            }
        }
    }

#if BL_TPM_SUPPORT
    /* Check if the image hash  was valid */
    if (!ImageHashValid)
    {
        /* Send a TPM/SI notification without a context */
        BlEnNotifyEvent(0x10000002, NULL);
    }

    /* Now send a TPM/SI notification with the hash of the loaded image */
    BlMmTranslateVirtualAddress(VirtualAddress, &Context.ImageBase);
    Context.HashAlgorithm = HashAlgorithm;
    Context.HashSize = HashSize;
    Context.FileName = ImageFile->FileName;
    Context.ImageSize = VirtualSize;
    Context.HashValid = ImageHashValid;
    Context.Hash = Hash;
    BlEnNotifyEvent(0x10000002, &Context);
#endif

    /* Return the loaded address to the caller */
    *ImageBase = VirtualAddress;

    /* If the caller wanted the image size, return it too */
    if (ImageSize)
    {
        *ImageSize = VirtualSize;
    }

Quickie:
    /* Check if we computed the image hash OK */
    if (ImageHashValid)
    {
        /* Then free the information that ImgpValidateImageHash set up */
        EfiPrintf(L"leadking trusted boot\r\n");
        //ImgpDestroyTrustedBootInformation(&TrustedBootInformation);
    }

    /* Check if we had a hash buffer */
    if (HashBuffer)
    {
        /* Free it */
        MmPapFreePages(HashBuffer, BL_MM_INCLUDE_MAPPED_ALLOCATED);
    }

    /* Check if we have a certificate directory */
    if ((CertBuffer) && (CertDirectory))
    {
        /* Free it */
        BlImgUnallocateImageBuffer(CertBuffer, CertDirectory->Size, 0);
    }

    /* Check if we had an image buffer allocated */
    if ((ImageBuffer) && (FileSize))
    {
        /* Free it */
        BlImgUnallocateImageBuffer(ImageBuffer, FileSize, 0);
    }

    /* Check if we had a local file handle */
    if (LocalFile)
    {
        /* Close it */
        ImgpCloseFile(LocalFile);
    }

    /* Check if this is the failure path */
    if (!NT_SUCCESS(Status))
    {
        /* Check if we had started mapping in the image already */
        if ((VirtualAddress) && !(Flags & BL_LOAD_PE_IMG_EXISTING_BUFFER))
        {
            /* Into a virtual buffer? */
            if (Flags & BL_LOAD_PE_IMG_VIRTUAL_BUFFER)
            {
                /* Unmap and free it */
                BlMmUnmapVirtualAddressEx(VirtualAddress, VirtualSize);
                PhysicalAddress.QuadPart = (ULONG_PTR)VirtualAddress;
                BlMmFreePhysicalPages(PhysicalAddress);
            }
            else
            {
                /* Into a physical buffer -- free it */
                MmPapFreePages(VirtualAddress, BL_MM_INCLUDE_MAPPED_ALLOCATED);
            }
        }
    }

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

NTSTATUS
BlImgLoadPEImageEx (
    _In_ ULONG DeviceId,
    _In_ BL_MEMORY_TYPE MemoryType,
    _In_ PWCHAR Path,
    _Out_ PVOID* ImageBase,
    _Out_ PULONG ImageSize,
    _Out_ PVOID Hash,
    _In_ ULONG Flags
    )
{
    BL_IMG_FILE ImageFile;
    NTSTATUS Status;

    /* Initialize the image file structure */
    ImageFile.Flags = 0;
    ImageFile.FileName = NULL;

    /* Check if the required parameter are missing */
    if (!(ImageBase) || !(Path))
    {
        return STATUS_INVALID_PARAMETER;
    }

    /* If we are loading a pre-allocated image, make sure we have it */
    if ((Flags & BL_LOAD_IMG_EXISTING_BUFFER) && (!(*ImageBase) || !(ImageSize)))
    {
        return STATUS_INVALID_PARAMETER;
    }

    /* Load the file from disk */
    Status = ImgpOpenFile(DeviceId, Path, 0, &ImageFile);
    if (NT_SUCCESS(Status))
    {
        /* If that worked, do the PE parsing */
        Status = ImgpLoadPEImage(&ImageFile,
                                 MemoryType,
                                 ImageBase,
                                 ImageSize,
                                 Hash,
                                 Flags);
    }

    /* Close the image file and return back to caller */
    ImgpCloseFile(&ImageFile);
    return Status;
}

NTSTATUS
BlImgLoadBootApplication (
    _In_ PBL_LOADED_APPLICATION_ENTRY BootEntry,
    _Out_ PULONG AppHandle
    )
{
    NTSTATUS Status;
    PULONGLONG AllowedList;
    ULONGLONG AllowedCount;
    ULONG i, DeviceId, ImageSize, Flags, ListSize;
    LARGE_INTEGER Frequency;
    PVOID UnlockCode, ImageBase;
    PBL_DEVICE_DESCRIPTOR Device, BitLockerDevice;
    PWCHAR Path;
    PBL_APPLICATION_ENTRY AppEntry;
    PBL_IMG_FILE ImageFile;
    BOOLEAN DisableIntegrity, TestSigning;
    UCHAR Hash[64];
    PBL_IMAGE_APPLICATION_ENTRY ImageAppEntry;

    /* Initialize all locals */
    BitLockerDevice = NULL;
    UnlockCode = NULL;
    ImageFile = NULL;
    DeviceId = -1;
    Device = NULL;
    ImageAppEntry = NULL;
    AppEntry = NULL;
    Path = NULL;
    ImageSize = 0;
    ImageBase = NULL;

    /* Check for "allowed in-memory settings" */
    Status = BlpGetBootOptionIntegerList(BootEntry->BcdData,
                                         BcdLibraryIntegerList_AllowedInMemorySettings,
                                         &AllowedList,
                                         &AllowedCount,
                                         TRUE);
    if (Status == STATUS_SUCCESS)
    {
        /* Loop through the list of allowed setting */
        for (i = 0; i < AllowedCount; i++)
        {
            /* Find the super undocumented one */
            if (AllowedList[i] == BcdLibraryInteger_UndocumentedMagic)
            {
                /* If it's present, append the current perf frequence to it */
                BlTimeQueryPerformanceCounter(&Frequency);
                BlAppendBootOptionInteger(BootEntry,
                                          BcdLibraryInteger_UndocumentedMagic,
                                          Frequency.QuadPart);
            }
        }
    }

#if BL_BITLOCKER_SUPPORT
    /* Do bitlocker stuff */
    Status = BlFveSecureBootUnlockBootDevice(BootEntry, &BitLockerDevice, &UnlockCode);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }
#endif

    /* Get the device on which this application is on*/
    Status = BlGetBootOptionDevice(BootEntry->BcdData,
                                   BcdLibraryDevice_ApplicationDevice,
                                   &Device,
                                   NULL);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Get the path of the application */
    Status = BlGetBootOptionString(BootEntry->BcdData,
                                   BcdLibraryString_ApplicationPath,
                                   &Path);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Open the device */
    Status = BlpDeviceOpen(Device,
                           BL_DEVICE_READ_ACCESS,
                           0,
                           &DeviceId);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Check for integrity BCD options */
    BlImgQueryCodeIntegrityBootOptions(BootEntry,
                                       &DisableIntegrity,
                                       &TestSigning);

#if BL_TPM_SUPPORT
    RtlZeroMemory(&Context, sizeof(Context);
    Context.BootEntry = BootEntry;
    BlEnNotifyEvent(0x10000003, &Context);
#endif

    /* Enable signing and hashing checks if integrity is enabled */
    Flags = 0;
    if (!DisableIntegrity)
    {
        Flags = 0x8070;
    }

    /* Now call the PE loader to load the image */
    Status = BlImgLoadPEImageEx(DeviceId,
                                BlLoaderMemory,
                                Path,
                                &ImageBase,
                                &ImageSize,
                                Hash,
                                Flags);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

#if BL_KD_SUPPORT
    /* Check if we should notify the debugger of load */
    if (BdDebugTransitions)
    {
        /* Initialize it */
        BdForceDebug = 1;
        Status = BlBdInitialize();
        if (NT_SUCCESS(Status))
        {
            /* Check if it's enabled */
            if (BlBdDebuggerEnabled())
            {
                /* Send it an image load notification */
                BdDebuggerNotPresent = FALSE;
                RtlInitUnicodeString(&PathString, Path);
                BlBdLoadImageSymbols(&PathString, ImageBase);
            }
        }
    }
#endif

#if BL_BITLOCKER_SUPPORT
    /* Do bitlocker stuff */
    Status = BlSecureBootCheckPolicyOnFveDevice(BitLockerDevice);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }
#endif

#if BL_BITLOCKER_SUPPORT
    /* Do bitlocker stuff */
    Status = BlFveSecureBootCheckpointBootApp(BootEntry, BitLockerDevice, Hash, UnlockCode);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }
#endif

    /* Get the BCD option size */
    ListSize = BlGetBootOptionListSize(BootEntry->BcdData);

    /* Allocate an entry with all the BCD options */
    AppEntry = BlMmAllocateHeap(ListSize + sizeof(*AppEntry));
    if (!AppEntry)
    {
        Status = STATUS_NO_MEMORY;
        goto Quickie;
    }

    /* Zero it out */
    RtlZeroMemory(AppEntry, sizeof(*AppEntry));

    /* Initialize it */
    strcpy(AppEntry->Signature, "BTAPENT");
    AppEntry->Guid = BootEntry->Guid;
    AppEntry->Flags = BootEntry->Flags;

    /* Copy the BCD options */
    RtlCopyMemory(&AppEntry->BcdData, BootEntry->BcdData, ListSize);

    /* Allocate the image entry */
    ImageAppEntry = BlMmAllocateHeap(sizeof(*ImageAppEntry));
    if (!ImageAppEntry)
    {
        Status = STATUS_NO_MEMORY;
        goto Quickie;
    }

    /* Initialize it */
    ImageAppEntry->ImageBase = ImageBase;
    ImageAppEntry->ImageSize = ImageSize;
    ImageAppEntry->AppEntry = AppEntry;

    /* Check if this is the first entry */
    if (!IapTableEntries)
    {
        /* Allocate two entries */
        IapAllocatedTableEntries = 0;
        IapTableEntries = 2;
        IapImageTable = BlMmAllocateHeap(IapTableEntries * sizeof(PVOID));
        if (!IapImageTable)
        {
            Status = STATUS_NO_MEMORY;
            goto Quickie;
        }

        /* Zero out the entries for now */
        RtlZeroMemory(IapImageTable, IapTableEntries * sizeof(PVOID));
    }

    /* Set this entry into the table */
    Status = BlTblSetEntry(&IapImageTable,
                           &IapTableEntries,
                           ImageAppEntry,
                           AppHandle,
                           TblDoNotPurgeEntry);

Quickie:
    /* Is the device open? Close it if so */
    if (DeviceId != 1)
    {
        BlDeviceClose(DeviceId);
    }

    /* Is there an allocated device? Free it */
    if (Device)
    {
        BlMmFreeHeap(Device);
    }

    /* Is there an allocated path? Free it */
    if (Path)
    {
        BlMmFreeHeap(Path);
    }

    /* Is there a bitlocker device? Free it */
    if (BitLockerDevice)
    {
        BlMmFreeHeap(BitLockerDevice);
    }

    /* Is there a bitlocker unlock code? Free it */
    if (UnlockCode)
    {
        BlMmFreeHeap(UnlockCode);
    }

    /* Did we succeed in creating an entry? */
    if (NT_SUCCESS(Status))
    {
        /* Remember there's one more in the table */
        IapAllocatedTableEntries++;

        /* Return success */
        return Status;
    }

    /* Did we load an image after all? */
    if (ImageBase)
    {
        /* Unload it */
        BlImgUnLoadImage(ImageBase, ImageSize, 0);
    }

    /* Did we allocate an app entry? Free it */
    if (AppEntry)
    {
        BlMmFreeHeap(AppEntry);
    }

    /* Do we have an image file entry?  Free it */
    if (ImageFile)
    {
        BlMmFreeHeap(ImageFile);
    }

    /* Do we no longer have a single entry in the table? */
    if (!(IapAllocatedTableEntries) && (IapImageTable))
    {
        /* Free and destroy the table */
        BlMmFreeHeap(IapImageTable);
        IapTableEntries = 0;
        IapImageTable = NULL;
    }

    /* Return the failure code */
    return Status;
}

NTSTATUS
BlpPdParseReturnArguments (
    _In_ PBL_RETURN_ARGUMENTS ReturnArguments
    )
{
    /* Check if any custom data was returned */
    if (ReturnArguments->DataPage == 0)
    {
        /* Nope, nothing to do */
        return STATUS_SUCCESS;
    }

    /* Yes, we have to parse it */
    EfiPrintf(L"Return arguments not supported\r\n");
    return STATUS_NOT_IMPLEMENTED;
}

NTSTATUS
ImgpCopyApplicationBootDevice (
    __in PBL_DEVICE_DESCRIPTOR DestinationDevice,
    __in PBL_DEVICE_DESCRIPTOR SourceDevice
    )
{
    /* Is this a partition device? */
    if (SourceDevice->DeviceType != PartitionDevice)
    {
        /* It's not -- a simple copy will do */
        RtlCopyMemory(DestinationDevice, SourceDevice, SourceDevice->Size);
        return STATUS_SUCCESS;
    }

    /* TODO */
    EfiPrintf(L"Partition copy not supported\r\n");
    return STATUS_NOT_IMPLEMENTED;

}

NTSTATUS
ImgpInitializeBootApplicationParameters (
    _In_ PBL_BUFFER_DESCRIPTOR ImageParameters,
    _In_ PBL_APPLICATION_ENTRY AppEntry,
    _In_ PVOID ImageBase, 
    _In_ ULONG ImageSize
    )
{
    NTSTATUS Status;
    PIMAGE_NT_HEADERS NtHeaders;
    BL_BUFFER_DESCRIPTOR MemoryParameters;
    LIST_ENTRY MemoryList;
    PBL_FIRMWARE_DESCRIPTOR FirmwareParameters;
    PBL_DEVICE_DESCRIPTOR BootDevice;
    PBL_MEMORY_DATA MemoryData;
    PBL_APPLICATION_ENTRY BootAppEntry;
    PBL_RETURN_ARGUMENTS ReturnArguments;
    PBOOT_APPLICATION_PARAMETER_BLOCK ParameterBlock;
    ULONG EntrySize, BufferSize;

    /* Get the image headers and validate it */
    Status = RtlImageNtHeaderEx(0, ImageBase, ImageSize, &NtHeaders);
    if (!NT_SUCCESS(Status))
    {
        return Status;
    }

    /* Get the size of the entire non-firmware, allocated, memory map */
    MemoryParameters.BufferSize = 0;
    Status = BlMmGetMemoryMap(&MemoryList,
                              &MemoryParameters,
                              BL_MM_INCLUDE_PERSISTENT_MEMORY |
                              BL_MM_INCLUDE_MAPPED_ALLOCATED |
                              BL_MM_INCLUDE_MAPPED_UNALLOCATED |
                              BL_MM_INCLUDE_UNMAPPED_ALLOCATED |
                              BL_MM_INCLUDE_RESERVED_ALLOCATED,
                              0);
    if ((Status != STATUS_BUFFER_TOO_SMALL) && (Status != STATUS_SUCCESS))
    {
        /* We failed due to an unknown reason -- bail out */
        return Status;
    }

    /* Compute the list of the BCD plus the application entry */
    EntrySize = BlGetBootOptionListSize(&AppEntry->BcdData) +
                FIELD_OFFSET(BL_APPLICATION_ENTRY, BcdData);

    /* Compute the total size required for the entire structure */
    BufferSize = EntrySize +
                 BlpBootDevice->Size +
                 MemoryParameters.BufferSize +
                 sizeof(*ReturnArguments) +
                 sizeof(*MemoryData) + 
                 sizeof(*FirmwareParameters) + 
                 sizeof(*ParameterBlock);

    /* Check if this gives us enough space */
    if (ImageParameters->BufferSize < BufferSize)
    {
        /* It does not -- free the existing buffer */
        if (ImageParameters->BufferSize)
        {
            BlMmFreeHeap(ImageParameters->Buffer);
        }

        /* Allocate a new buffer of sufficient size */
        ImageParameters->BufferSize = BufferSize;
        ImageParameters->Buffer = BlMmAllocateHeap(BufferSize);
        if (!ImageParameters->Buffer)
        {
            /* Bail out if we couldn't allocate it */
            return STATUS_NO_MEMORY;
        }
    }

    /* Zero out the parameter block */
    ParameterBlock = (PBOOT_APPLICATION_PARAMETER_BLOCK)ImageParameters->Buffer;
    RtlZeroMemory(ParameterBlock, BufferSize);

    /* Initialize it */
    ParameterBlock->Version = BOOT_APPLICATION_VERSION;
    ParameterBlock->Size = BufferSize;
    ParameterBlock->Signature[0] = BOOT_APPLICATION_SIGNATURE_1;
    ParameterBlock->Signature[1] = BOOT_APPLICATION_SIGNATURE_2;
    ParameterBlock->MemoryTranslationType = MmTranslationType;
    ParameterBlock->ImageType = IMAGE_FILE_MACHINE_I386;
    ParameterBlock->ImageBase = (ULONG_PTR)ImageBase;
    ParameterBlock->ImageSize = NtHeaders->OptionalHeader.SizeOfImage;

    /* Get the offset to the memory data */
    ParameterBlock->MemoryDataOffset = sizeof(*ParameterBlock);

    /* Fill it out */
    MemoryData = (PBL_MEMORY_DATA)((ULONG_PTR)ParameterBlock +
                                   ParameterBlock->MemoryDataOffset);
    MemoryData->Version = BL_MEMORY_DATA_VERSION;
    MemoryData->MdListOffset = sizeof(*MemoryData);
    MemoryData->DescriptorSize = sizeof(BL_MEMORY_DESCRIPTOR);
    MemoryData->DescriptorOffset = FIELD_OFFSET(BL_MEMORY_DESCRIPTOR, BasePage);

    /* And populate the memory map */
    MemoryParameters.Buffer = MemoryData + 1;
    Status = BlMmGetMemoryMap(&MemoryList,
                              &MemoryParameters,
                              BL_MM_INCLUDE_PERSISTENT_MEMORY |
                              BL_MM_INCLUDE_MAPPED_ALLOCATED |
                              BL_MM_INCLUDE_MAPPED_UNALLOCATED |
                              BL_MM_INCLUDE_UNMAPPED_ALLOCATED |
                              BL_MM_INCLUDE_RESERVED_ALLOCATED,
                              0);
    if (!NT_SUCCESS(Status))
    {
        return Status;
    }

    /* Now that we have the map, indicate the number of descriptors */
    MemoryData->DescriptorCount = MemoryParameters.ActualSize /
                                  MemoryData->DescriptorSize;

    /* Get the offset to the application entry */
    ParameterBlock->AppEntryOffset = ParameterBlock->MemoryDataOffset +
                                     MemoryData->MdListOffset +
                                     MemoryParameters.BufferSize;

    /* Fill it out */
    BootAppEntry = (PBL_APPLICATION_ENTRY)((ULONG_PTR)ParameterBlock +
                                           ParameterBlock->AppEntryOffset);
    RtlCopyMemory(BootAppEntry, AppEntry, EntrySize);

    /* Get the offset to the boot device */
    ParameterBlock->BootDeviceOffset = ParameterBlock->AppEntryOffset +
                                       EntrySize;

    /* Fill it out */
    BootDevice = (PBL_DEVICE_DESCRIPTOR)((ULONG_PTR)ParameterBlock +
                                         ParameterBlock->BootDeviceOffset);
    Status = ImgpCopyApplicationBootDevice(BootDevice, BlpBootDevice);
    if (!NT_SUCCESS(Status))
    {
        return Status;
    }

    /* Get the offset to the firmware data */
    ParameterBlock->FirmwareParametersOffset = ParameterBlock->BootDeviceOffset +
                                               BootDevice->Size;

    /* Fill it out */
    FirmwareParameters = (PBL_FIRMWARE_DESCRIPTOR)((ULONG_PTR)ParameterBlock +
                                                   ParameterBlock->
                                                   FirmwareParametersOffset);
    Status = BlFwGetParameters(FirmwareParameters);
    if (!NT_SUCCESS(Status))
    {
        return Status;
    }

    /* Get the offset to the return arguments */
    ParameterBlock->ReturnArgumentsOffset = ParameterBlock->FirmwareParametersOffset +
                                            sizeof(BL_FIRMWARE_DESCRIPTOR);

    /* Fill them out */
    ReturnArguments = (PBL_RETURN_ARGUMENTS)((ULONG_PTR)ParameterBlock +
                                             ParameterBlock->
                                             ReturnArgumentsOffset);
    ReturnArguments->Version = BL_RETURN_ARGUMENTS_VERSION;
    ReturnArguments->DataPage = 0;
    ReturnArguments->DataSize = 0;

    /* Structure complete */
    ImageParameters->ActualSize = ParameterBlock->ReturnArgumentsOffset +
                                  sizeof(*ReturnArguments);
    return STATUS_SUCCESS;
}

NTSTATUS
ImgArchEfiStartBootApplication (
    _In_ PBL_APPLICATION_ENTRY AppEntry,
    _In_ PVOID ImageBase,
    _In_ ULONG ImageSize,
    _In_ PBL_RETURN_ARGUMENTS ReturnArguments
    )
{
#ifndef _M_ARM
    KDESCRIPTOR Gdt, Idt;
    ULONG BootSizeNeeded;
    NTSTATUS Status;
    PVOID BootData;
    PIMAGE_NT_HEADERS NtHeaders;
    PVOID NewStack, NewGdt, NewIdt;
    BL_BUFFER_DESCRIPTOR Parameters;

    /* Read the current IDT and GDT */
    _sgdt(&Gdt.Limit);
    __sidt(&Idt.Limit);

    /* Allocate space for the IDT, GDT, and 24 pages of stack */
    BootSizeNeeded = (ULONG_PTR)PAGE_ALIGN(Idt.Limit + Gdt.Limit + 1 + 25 * PAGE_SIZE);
    Status = MmPapAllocatePagesInRange(&BootData,
                                       BlLoaderArchData,
                                       BootSizeNeeded >> PAGE_SHIFT,
                                       0,
                                       0,
                                       NULL,
                                       0);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Zero the boot data */
    RtlZeroMemory(BootData, BootSizeNeeded);

    /* Set the new stack, GDT and IDT */
    NewStack = (PVOID)((ULONG_PTR)BootData + (24 * PAGE_SIZE) - 8);
    NewGdt = (PVOID)((ULONG_PTR)BootData + (24 * PAGE_SIZE));
    NewIdt = (PVOID)((ULONG_PTR)BootData + (24 * PAGE_SIZE) + Gdt.Limit + 1);

    /* Copy the current (firmware) GDT and IDT */
    RtlCopyMemory(NewGdt, (PVOID)Gdt.Base, Gdt.Limit + 1);
    RtlCopyMemory(NewIdt, (PVOID)Idt.Base, Idt.Limit + 1);

    /* Read the NT headers so that we can get the entrypoint later on */
    RtlImageNtHeaderEx(0, ImageBase, ImageSize, &NtHeaders);

    /* Prepare the application parameters */
    RtlZeroMemory(&Parameters, sizeof(Parameters));
    Status = ImgpInitializeBootApplicationParameters(&Parameters,
                                                     AppEntry,
                                                     ImageBase,
                                                     ImageSize);
    if (NT_SUCCESS(Status))
    {
        /* Set the firmware GDT/IDT as the one the application will use */
        BootAppGdtRegister = Gdt;
        BootAppIdtRegister = Idt;

        /* Set the entrypoint, parameters, and stack */
        BootApp32EntryRoutine = (PVOID)((ULONG_PTR)ImageBase +
                                        NtHeaders->OptionalHeader.
                                        AddressOfEntryPoint);
        BootApp32Parameters = Parameters.Buffer;
        BootApp32Stack = NewStack;

#if BL_KD_SUPPORT
        /* Disable the kernel debugger */
        BlBdStop();
#endif
        /* Make it so */
        Archx86TransferTo32BitApplicationAsm();

        /* Not yet implemented. This is the last step! */
        EfiPrintf(L"EFI APPLICATION RETURNED!!!\r\n");
        EfiStall(100000000);

#if BL_KD_SUPPORT
        /* Re-enable the kernel debugger */
        BlBdStart();
#endif
    }

Quickie:
    /* Check if we had boot data allocated */
    if (BootData)
    {
        /* Free it */
        MmPapFreePages(BootData, BL_MM_INCLUDE_MAPPED_ALLOCATED);
    }
#else
    EfiPrintf(L"ImgArchEfiStartBootApplication not implemented for this platform.\r\n");
#endif

    /* All done */
    return STATUS_NOT_IMPLEMENTED;
}

NTSTATUS
BlImgStartBootApplication (
    _In_ ULONG AppHandle,
    _Inout_opt_ PBL_RETURN_ARGUMENTS ReturnArguments
    )
{
    PBL_IMAGE_APPLICATION_ENTRY ImageAppEntry;
    BL_RETURN_ARGUMENTS LocalReturnArgs;
    PBL_FILE_SYSTEM_ENTRY FileSystem;
    PLIST_ENTRY NextEntry, ListHead;
    NTSTATUS Status;

    /* Check if we don't have an argument structure */
    if (!ReturnArguments)
    {
        /* Initialize a local copy and use it instead */
        LocalReturnArgs.Version = BL_RETURN_ARGUMENTS_VERSION;
        LocalReturnArgs.Status = STATUS_SUCCESS;
        LocalReturnArgs.Flags = 0;
        LocalReturnArgs.DataPage = 0;
        LocalReturnArgs.DataSize = 0;
        ReturnArguments = &LocalReturnArgs;
    }

    /* Make sure the handle index is valid */
    if (IapTableEntries <= AppHandle)
    {
        return STATUS_INVALID_PARAMETER;
    }

    /* Get the entry for this handle, making sure it exists */
    ImageAppEntry = IapImageTable[AppHandle];
    if (!ImageAppEntry)
    {
        return STATUS_INVALID_PARAMETER;
    }

    /* Loop the registered file systems */
    ListHead = &RegisteredFileSystems;
    NextEntry = RegisteredFileSystems.Flink;
    while (NextEntry != ListHead)
    {
        /* Get the filesystem entry */
        FileSystem = CONTAINING_RECORD(NextEntry,
                                       BL_FILE_SYSTEM_ENTRY,
                                       ListEntry);

        /* See if it has a purge callback */
        if (FileSystem->PurgeCallback)
        {
            /* Call it */
            FileSystem->PurgeCallback();
        }

        /* Move to the next entry */
        NextEntry = NextEntry->Flink;
    }

    /* TODO  -- flush the block I/O cache too */
    //BlockIoPurgeCache();

    /* Call into EFI land to start the boot application */
    Status = ImgArchEfiStartBootApplication(ImageAppEntry->AppEntry,
                                            ImageAppEntry->ImageBase,
                                            ImageAppEntry->ImageSize,
                                            ReturnArguments);

    /* Parse any arguments we got on the way back */
    BlpPdParseReturnArguments(ReturnArguments);

#if BL_BITLOCKER_SUPPORT
    /* Bitlocker stuff */
    FvebpCheckAllPartitions(TRUE);
#endif

#if BL_TPM_SUPPORT
    /* Notify a TPM/SI event */
    BlEnNotifyEvent(0x10000005, NULL);
#endif

    /* Reset the display */
    BlpDisplayReinitialize();

    /* TODO -- reset ETW */
    //BlpLogInitialize();

    /* All done */
    return Status;
}

NTSTATUS
BlImgUnloadBootApplication (
    _In_ ULONG AppHandle
    )
{
    PBL_IMAGE_APPLICATION_ENTRY ImageAppEntry;
    NTSTATUS Status;

    /* Make sure the handle index is valid */
    if (IapTableEntries <= AppHandle)
    {
        return STATUS_INVALID_PARAMETER;
    }

    /* Get the entry for this handle, making sure it exists */
    ImageAppEntry = IapImageTable[AppHandle];
    if (!ImageAppEntry)
    {
        return STATUS_INVALID_PARAMETER;
    }

    /* Unload the image */
    Status = BlImgUnLoadImage(ImageAppEntry->ImageBase,
                              ImageAppEntry->ImageSize,
                              0);
    if (NT_SUCCESS(Status))
    {
        /* Normalize the success code */
        Status = STATUS_SUCCESS;
    }
    else
    {
        /* Normalize the failure code */
        Status = STATUS_MEMORY_NOT_ALLOCATED;
    }

    /* Free the entry and the image entry as well */
    BlMmFreeHeap(ImageAppEntry->AppEntry);
    BlMmFreeHeap(ImageAppEntry);

    /* Clear the handle */
    IapImageTable[AppHandle] = NULL;

    /* Free one entry */
    if (!(--IapAllocatedTableEntries))
    {
        /* There are no more, so get rid of the table itself */
        BlMmFreeHeap(IapImageTable);
        IapImageTable = NULL;
        IapTableEntries = 0;
    }

    /* All good */
    return Status;
}