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
/*
 * PROJECT:     ReactOS Setup Library
 * LICENSE:     GPL-2.0+ (https://spdx.org/licenses/GPL-2.0+)
 * PURPOSE:     Boot Stores Management functionality, with support for
 *              NT 5.x family (MS Windows <= 2003, and ReactOS) bootloaders.
 * COPYRIGHT:   Copyright 2017-2018 Hermes Belusca-Maito
 */

// TODO: Add support for NT 6.x family! (detection + BCD manipulation).

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

#include "precomp.h"

#include "bldrsup.h"
#include "filesup.h"
#include "inicache.h"

#define NDEBUG
#include <debug.h>


/* GLOBALS ******************************************************************/

typedef NTSTATUS
(*POPEN_BOOT_STORE)(
    OUT PVOID* Handle,
    IN HANDLE PartitionDirectoryHandle, // OPTIONAL
    IN BOOT_STORE_TYPE Type,
    IN BOOLEAN CreateNew);

typedef NTSTATUS
(*PCLOSE_BOOT_STORE)(
    IN PVOID Handle);

typedef NTSTATUS
(*PENUM_BOOT_STORE_ENTRIES)(
    IN PVOID Handle,
//  IN ULONG Flags, // Determine which data to retrieve
    IN PENUM_BOOT_ENTRIES_ROUTINE EnumBootEntriesRoutine,
    IN PVOID Parameter OPTIONAL);

typedef struct _NTOS_BOOT_LOADER_FILES
{
    BOOT_STORE_TYPE Type;
    PCZZWSTR LoaderExecutables;
    PCWSTR LoaderConfigurationFile;
    POPEN_BOOT_STORE OpenBootStore;
    PCLOSE_BOOT_STORE CloseBootStore;
    PENUM_BOOT_STORE_ENTRIES EnumBootStoreEntries;
} NTOS_BOOT_LOADER_FILES, *PNTOS_BOOT_LOADER_FILES;


/*
 * Header for particular store contexts
 */
typedef struct _BOOT_STORE_CONTEXT
{
    BOOT_STORE_TYPE Type;
//  PNTOS_BOOT_LOADER_FILES ??
/*
    PVOID PrivateData;
*/
} BOOT_STORE_CONTEXT, *PBOOT_STORE_CONTEXT;

typedef struct _BOOT_STORE_INI_CONTEXT
{
    BOOT_STORE_CONTEXT Header;

    /*
     * If all these members are NULL, we know that the store is freshly created
     * and is cached in memory only. At file closure we will therefore need to
     * create the file proper and save its contents.
     */
    HANDLE FileHandle;
    HANDLE SectionHandle;
    // SIZE_T ViewSize;
    ULONG FileSize;
    PVOID ViewBase;

    PINICACHE IniCache;
    PINICACHESECTION OptionsIniSection;
    PINICACHESECTION OsIniSection;
} BOOT_STORE_INI_CONTEXT, *PBOOT_STORE_INI_CONTEXT;

// TODO!
typedef struct _BOOT_STORE_BCDREG_CONTEXT
{
    BOOT_STORE_CONTEXT Header;
    ULONG PlaceHolder;
} BOOT_STORE_BCDREG_CONTEXT, *PBOOT_STORE_BCDREG_CONTEXT;


static NTSTATUS
OpenIniBootLoaderStore(
    OUT PVOID* Handle,
    IN HANDLE PartitionDirectoryHandle, // OPTIONAL
    IN BOOT_STORE_TYPE Type,
    IN BOOLEAN CreateNew);

static NTSTATUS
CloseIniBootLoaderStore(
    IN PVOID Handle);

static NTSTATUS
FreeLdrEnumerateBootEntries(
    IN PBOOT_STORE_INI_CONTEXT BootStore,
//  IN ULONG Flags, // Determine which data to retrieve
    IN PENUM_BOOT_ENTRIES_ROUTINE EnumBootEntriesRoutine,
    IN PVOID Parameter OPTIONAL);

static NTSTATUS
NtLdrEnumerateBootEntries(
    IN PBOOT_STORE_INI_CONTEXT BootStore,
//  IN ULONG Flags, // Determine which data to retrieve
    IN PENUM_BOOT_ENTRIES_ROUTINE EnumBootEntriesRoutine,
    IN PVOID Parameter OPTIONAL);


// Question 1: What if config file is optional?
// Question 2: What if many config files are possible?
NTOS_BOOT_LOADER_FILES NtosBootLoaders[] =
{
    {FreeLdr, L"freeldr.sys\0", L"freeldr.ini",
        OpenIniBootLoaderStore, CloseIniBootLoaderStore, (PENUM_BOOT_STORE_ENTRIES)FreeLdrEnumerateBootEntries},
    {NtLdr  , L"ntldr\0" L"osloader.exe\0", L"boot.ini",
        OpenIniBootLoaderStore, CloseIniBootLoaderStore, (PENUM_BOOT_STORE_ENTRIES)NtLdrEnumerateBootEntries  },
//  {SetupLdr, L"setupldr\0" L"setupldr.bin\0" L"setupldr.exe\0", L"txtsetup.sif", UNIMPLEMENTED, UNIMPLEMENTED, UNIMPLEMENTED}
//  {BootMgr , L"bootmgr", L"BCD", UNIMPLEMENTED, UNIMPLEMENTED, UNIMPLEMENTED}
};
C_ASSERT(_countof(NtosBootLoaders) == BldrTypeMax);


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

NTSTATUS
FindBootStore( // By handle
    IN HANDLE PartitionDirectoryHandle, // OPTIONAL
    IN BOOT_STORE_TYPE Type,
    OUT PULONG VersionNumber OPTIONAL)
// OUT PHANDLE ConfigFileHande OPTIONAL ????
{
    PCWSTR LoaderExecutable;
    // UINT i;

    if (Type >= BldrTypeMax)
        return STATUS_INVALID_PARAMETER;

    if (VersionNumber)
        *VersionNumber = 0;

    /* Check whether any of the loader executables exist */
    LoaderExecutable = NtosBootLoaders[Type].LoaderExecutables;
    while (*LoaderExecutable)
    {
        if (DoesFileExist(PartitionDirectoryHandle, LoaderExecutable))
        {
            /* A loader was found, stop there */
            DPRINT("Found loader executable '%S'\n", LoaderExecutable);
            break;
        }

        /* The loader does not exist, continue with another one */
        DPRINT("Loader executable '%S' does not exist, continue with another one...\n", LoaderExecutable);
        LoaderExecutable += wcslen(LoaderExecutable) + 1;
    }
    if (!*LoaderExecutable)
    {
        /* No loader was found */
        DPRINT("No loader executable was found\n");
        return STATUS_NOT_FOUND;
    }

    /* Check for loader version if needed */
    if (VersionNumber)
    {
        *VersionNumber = 0;
        // TODO: Check for BLDR version!
    }

    /* Check whether the loader configuration file exists */
    if (!DoesFileExist(PartitionDirectoryHandle, NtosBootLoaders[Type].LoaderConfigurationFile))
    {
        /* The loader does not exist, continue with another one */
        // FIXME: Consider it might be optional??
        DPRINT1("Loader configuration file '%S' does not exist\n", NtosBootLoaders[Type].LoaderConfigurationFile);
        return STATUS_NOT_FOUND;
    }

#if 0
    /* Check whether the loader configuration file exists */
    Status = OpenAndMapFile(PartitionDirectoryHandle, NtosBootLoaders[Type].LoaderConfigurationFile,
                            &FileHandle, &SectionHandle, &ViewBase, &FileSize, FALSE);
    if (!NT_SUCCESS(Status))
    {
        /* The loader does not exist, continue with another one */
        // FIXME: Consider it might be optional??
        DPRINT1("Loader configuration file '%S' does not exist\n", NtosBootLoaders[Type].LoaderConfigurationFile);
        return STATUS_NOT_FOUND;
    }
#endif

    return STATUS_SUCCESS;
}


static VOID
CreateCommonFreeLdrSections(
    IN OUT PBOOT_STORE_INI_CONTEXT BootStore)
{
    PINICACHESECTION IniSection;

    /*
     * Cache the "FREELOADER" section for our future usage.
     */

    /* Get the "FREELOADER" section */
    IniSection = IniCacheGetSection(BootStore->IniCache, L"FREELOADER");
    if (!IniSection)
    {
        /* It does not exist yet, so create it */
        IniSection = IniCacheAppendSection(BootStore->IniCache, L"FREELOADER");
        if (!IniSection)
        {
            DPRINT1("CreateCommonFreeLdrSections: Failed to create 'FREELOADER' section!\n");
        }
    }

    BootStore->OptionsIniSection = IniSection;

    /* Timeout=0 */
    IniCacheInsertKey(BootStore->OptionsIniSection, NULL, INSERT_LAST,
                      L"TimeOut", L"0");

    /* Create "Display" section */
    IniSection = IniCacheAppendSection(BootStore->IniCache, L"Display");

    /* TitleText=ReactOS Boot Manager */
    IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                      L"TitleText", L"ReactOS Boot Manager");

    /* StatusBarColor=Cyan */
    IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                      L"StatusBarColor", L"Cyan");

    /* StatusBarTextColor=Black */
    IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                      L"StatusBarTextColor", L"Black");

    /* BackdropTextColor=White */
    IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                      L"BackdropTextColor", L"White");

    /* BackdropColor=Blue */
    IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                      L"BackdropColor", L"Blue");

    /* BackdropFillStyle=Medium */
    IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                      L"BackdropFillStyle", L"Medium");

    /* TitleBoxTextColor=White */
    IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                      L"TitleBoxTextColor", L"White");

    /* TitleBoxColor=Red */
    IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                      L"TitleBoxColor", L"Red");

    /* MessageBoxTextColor=White */
    IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                      L"MessageBoxTextColor", L"White");

    /* MessageBoxColor=Blue */
    IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                      L"MessageBoxColor", L"Blue");

    /* MenuTextColor=White */
    IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                      L"MenuTextColor", L"Gray");

    /* MenuColor=Blue */
    IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                      L"MenuColor", L"Black");

    /* TextColor=Yellow */
    IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                      L"TextColor", L"Gray");

    /* SelectedTextColor=Black */
    IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                      L"SelectedTextColor", L"Black");

    /* SelectedColor=Gray */
    IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                      L"SelectedColor", L"Gray");

    /* SelectedColor=Gray */
    IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                      L"ShowTime", L"No");

    /* SelectedColor=Gray */
    IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                      L"MenuBox", L"No");

    /* SelectedColor=Gray */
    IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                      L"CenterMenu", L"No");

    /* SelectedColor=Gray */
    IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                      L"MinimalUI", L"Yes");

    /* SelectedColor=Gray */
    IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                      L"TimeText",
                      L"Seconds until highlighted choice will be started automatically:   ");

    /*
     * Cache the "Operating Systems" section for our future usage.
     */

    /* Get the "Operating Systems" section */
    IniSection = IniCacheGetSection(BootStore->IniCache, L"Operating Systems");
    if (!IniSection)
    {
        /* It does not exist yet, so create it */
        IniSection = IniCacheAppendSection(BootStore->IniCache, L"Operating Systems");
        if (!IniSection)
        {
            DPRINT1("CreateCommonFreeLdrSections: Failed to create 'Operating Systems' section!\n");
        }
    }

    BootStore->OsIniSection = IniSection;
}

static NTSTATUS
OpenIniBootLoaderStore(
    OUT PVOID* Handle,
    IN HANDLE PartitionDirectoryHandle, // OPTIONAL
    IN BOOT_STORE_TYPE Type,
    IN BOOLEAN CreateNew)
{
    NTSTATUS Status;
    PBOOT_STORE_INI_CONTEXT BootStore;

    /* Create a boot store structure */
    BootStore = RtlAllocateHeap(ProcessHeap, HEAP_ZERO_MEMORY, sizeof(*BootStore));
    if (!BootStore)
        return STATUS_INSUFFICIENT_RESOURCES;

    BootStore->Header.Type = Type;

    if (CreateNew)
    {
        UNICODE_STRING Name;
        OBJECT_ATTRIBUTES ObjectAttributes;
        IO_STATUS_BLOCK IoStatusBlock;

        //
        // WARNING! We "support" the INI creation *ONLY* for FreeLdr, and not for NTLDR!!
        //
        if (Type == NtLdr)
        {
            DPRINT1("OpenIniBootLoaderStore() unsupported for NTLDR!\n");
            RtlFreeHeap(ProcessHeap, 0, BootStore);
            return STATUS_NOT_SUPPORTED;
        }

        /* Initialize the INI file */
        BootStore->IniCache = IniCacheCreate();
        if (!BootStore->IniCache)
        {
            DPRINT1("IniCacheCreate() failed.\n");
            RtlFreeHeap(ProcessHeap, 0, BootStore);
            return STATUS_INSUFFICIENT_RESOURCES;
        }

        /*
         * So far, we only use the INI cache. The file itself is not created
         * yet, therefore FileHandle, SectionHandle, ViewBase and FileSize
         * are all NULL. We will use this fact to know that the INI file was
         * indeed created, and not just opened as an existing file.
         */
        // BootStore->FileHandle = NULL;
        BootStore->SectionHandle = NULL;
        BootStore->ViewBase = NULL;
        BootStore->FileSize = 0;

        /*
         * The INI file is fresh new, we need to create it now.
         */

        RtlInitUnicodeString(&Name, NtosBootLoaders[Type].LoaderConfigurationFile);

        InitializeObjectAttributes(&ObjectAttributes,
                                   &Name,
                                   OBJ_CASE_INSENSITIVE,
                                   PartitionDirectoryHandle,
                                   NULL);

        Status = NtCreateFile(&BootStore->FileHandle,
                              FILE_GENERIC_READ | FILE_GENERIC_WRITE, // Contains SYNCHRONIZE
                              &ObjectAttributes,
                              &IoStatusBlock,
                              NULL,
                              FILE_ATTRIBUTE_NORMAL,
                              0,
                              FILE_SUPERSEDE,
                              FILE_SYNCHRONOUS_IO_NONALERT | FILE_SEQUENTIAL_ONLY | FILE_NON_DIRECTORY_FILE,
                              NULL,
                              0);
        if (!NT_SUCCESS(Status))
        {
            DPRINT1("NtCreateFile() failed (Status 0x%08lx)\n", Status);
            IniCacheDestroy(BootStore->IniCache);
            RtlFreeHeap(ProcessHeap, 0, BootStore);
            return Status;
        }

        /* Initialize the INI file contents */
        if (Type == FreeLdr)
            CreateCommonFreeLdrSections(BootStore);
    }
    else
    {
        PINICACHESECTION IniSection;

        /*
         * Check whether the loader configuration INI file exists,
         * and open it if so.
         * TODO: FIXME: What if it doesn't exist yet???
         */
        Status = OpenAndMapFile(PartitionDirectoryHandle,
                                NtosBootLoaders[Type].LoaderConfigurationFile,
                                &BootStore->FileHandle,
                                &BootStore->SectionHandle,
                                &BootStore->ViewBase,
                                &BootStore->FileSize,
                                TRUE);
        if (!NT_SUCCESS(Status))
        {
            /* The loader configuration file does not exist */
            // FIXME: Consider it might be optional??
            DPRINT1("Loader configuration file '%S' does not exist (Status 0x%08lx)\n",
                    NtosBootLoaders[Type].LoaderConfigurationFile, Status);
            RtlFreeHeap(ProcessHeap, 0, BootStore);
            return Status;
        }

        /* Open an *existing* INI configuration file */
        // Status = IniCacheLoad(&BootStore->IniCache, NtosBootLoaders[Type].LoaderConfigurationFile, FALSE);
        Status = IniCacheLoadFromMemory(&BootStore->IniCache,
                                        BootStore->ViewBase,
                                        BootStore->FileSize,
                                        FALSE);
        if (!NT_SUCCESS(Status))
        {
            DPRINT1("IniCacheLoadFromMemory() failed (Status 0x%08lx)\n", Status);

            /* Finally, unmap and close the file */
            UnMapAndCloseFile(BootStore->FileHandle,
                              BootStore->SectionHandle,
                              BootStore->ViewBase);

            RtlFreeHeap(ProcessHeap, 0, BootStore);
            return Status;
        }

        if (Type == FreeLdr)
        {
            /*
             * Cache the "FREELOADER" section for our future usage.
             */

            /* Get the "FREELOADER" section */
            IniSection = IniCacheGetSection(BootStore->IniCache, L"FREELOADER");
            if (!IniSection)
            {
                /* It does not exist yet, so create it */
                IniSection = IniCacheAppendSection(BootStore->IniCache, L"FREELOADER");
                if (!IniSection)
                {
                    DPRINT1("OpenIniBootLoaderStore: Failed to retrieve 'FREELOADER' section!\n");
                }
            }

            BootStore->OptionsIniSection = IniSection;

            /*
             * Cache the "Operating Systems" section for our future usage.
             */

            /* Get the "Operating Systems" section */
            IniSection = IniCacheGetSection(BootStore->IniCache, L"Operating Systems");
            if (!IniSection)
            {
                /* It does not exist yet, so create it */
                IniSection = IniCacheAppendSection(BootStore->IniCache, L"Operating Systems");
                if (!IniSection)
                {
                    DPRINT1("OpenIniBootLoaderStore: Failed to retrieve 'Operating Systems' section!\n");
                }
            }

            BootStore->OsIniSection = IniSection;
        }
        else
        if (Type == NtLdr)
        {
            /*
             * Cache the "boot loader" section for our future usage.
             */
            /*
             * HISTORICAL NOTE:
             *
             * While the "operating systems" section acquired its definitive
             * name already when Windows NT was at its very early beta stage
             * (NT 3.1 October 1991 Beta, 10-16-1991), this was not the case
             * for its general settings section "boot loader".
             *
             * The following section names were successively introduced:
             *
             * - In NT 3.1 October 1991 Beta, 10-16-1991, using OS Loader V1.5,
             *   the section was named "multiboot".
             *
             * - In the next public beta version NT 3.10.340 Beta, 10-12-1992,
             *   using OS Loader V2.10, a new name was introduced: "flexboot".
             *   This is around this time that the NT OS Loader was also
             *   introduced as the "Windows NT FlexBoot" loader, as shown by
             *   the Windows NT FAQs that circulated around this time:
             *   http://cd.textfiles.com/cica9308/CIS_LIBS/WINNT/1/NTFAQ.TXT
             *   http://cd.textfiles.com/cica/cica9308/UNZIPPED/NT/NTFAQ/FTP/NEWS/NTFAQ1.TXT
             *   I can only hypothesize that the "FlexBoot" name was chosen
             *   as a marketing coup, possibly to emphasise its "flexibility"
             *   as a simple multiboot-aware boot manager.
             *
             * - A bit later, with NT 3.10.404 Beta, 3-7-1993, using an updated
             *   version of OS Loader V2.10, the final section name "boot loader"
             *   was introduced, and was kept since then.
             *
             * Due to the necessity to be able to boot and / or upgrade any
             * Windows NT version at any time, including its NT Loader and the
             * associated boot.ini file, all versions of NTLDR and the NT installer
             * understand and parse these three section names, the default one
             * being "boot loader", and if not present, they successively fall
             * back to "flexboot" and then to "multiboot".
             */

            /* Get the "boot loader" section */
            IniSection = IniCacheGetSection(BootStore->IniCache, L"boot loader");
            if (!IniSection)
            {
                /* Fall back to "flexboot" */
                IniSection = IniCacheGetSection(BootStore->IniCache, L"flexboot");
                if (!IniSection)
                {
                    /* Fall back to "multiboot" */
                    IniSection = IniCacheGetSection(BootStore->IniCache, L"multiboot");
                }
            }
#if 0
            if (!IniSection)
            {
                /* It does not exist yet, so create it */
                IniSection = IniCacheAppendSection(BootStore->IniCache, L"boot loader");
                if (!IniSection)
                {
                    DPRINT1("OpenIniBootLoaderStore: Failed to retrieve 'boot loader' section!\n");
                }
            }
#endif

            BootStore->OptionsIniSection = IniSection;

            /*
             * Cache the "Operating Systems" section for our future usage.
             */

            /* Get the "Operating Systems" section */
            IniSection = IniCacheGetSection(BootStore->IniCache, L"operating systems");
            if (!IniSection)
            {
#if 0
                /* It does not exist yet, so create it */
                IniSection = IniCacheAppendSection(BootStore->IniCache, L"operating systems");
                if (!IniSection)
                {
                    DPRINT1("OpenIniBootLoaderStore: Failed to retrieve 'operating systems' section!\n");
                }
#endif
            }

            BootStore->OsIniSection = IniSection;
        }
    }

    *Handle = BootStore;
    return STATUS_SUCCESS;
}

static NTSTATUS
UnprotectBootIni(
    IN HANDLE FileHandle,
    OUT PULONG Attributes)
{
    NTSTATUS Status;
    IO_STATUS_BLOCK IoStatusBlock;
    FILE_BASIC_INFORMATION FileInfo;

    Status = NtQueryInformationFile(FileHandle,
                                    &IoStatusBlock,
                                    &FileInfo,
                                    sizeof(FILE_BASIC_INFORMATION),
                                    FileBasicInformation);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("NtQueryInformationFile() failed (Status 0x%08lx)\n", Status);
        return Status;
    }

    *Attributes = FileInfo.FileAttributes;

    /* Delete attributes SYSTEM, HIDDEN and READONLY */
    FileInfo.FileAttributes = FileInfo.FileAttributes &
                              ~(FILE_ATTRIBUTE_SYSTEM |
                                FILE_ATTRIBUTE_HIDDEN |
                                FILE_ATTRIBUTE_READONLY);

    Status = NtSetInformationFile(FileHandle,
                                  &IoStatusBlock,
                                  &FileInfo,
                                  sizeof(FILE_BASIC_INFORMATION),
                                  FileBasicInformation);
    if (!NT_SUCCESS(Status))
        DPRINT1("NtSetInformationFile() failed (Status 0x%08lx)\n", Status);

    return Status;
}

static NTSTATUS
ProtectBootIni(
    IN HANDLE FileHandle,
    IN ULONG Attributes)
{
    NTSTATUS Status;
    IO_STATUS_BLOCK IoStatusBlock;
    FILE_BASIC_INFORMATION FileInfo;

    Status = NtQueryInformationFile(FileHandle,
                                    &IoStatusBlock,
                                    &FileInfo,
                                    sizeof(FILE_BASIC_INFORMATION),
                                    FileBasicInformation);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("NtQueryInformationFile() failed (Status 0x%08lx)\n", Status);
        return Status;
    }

    FileInfo.FileAttributes = FileInfo.FileAttributes | Attributes;

    Status = NtSetInformationFile(FileHandle,
                                  &IoStatusBlock,
                                  &FileInfo,
                                  sizeof(FILE_BASIC_INFORMATION),
                                  FileBasicInformation);
    if (!NT_SUCCESS(Status))
        DPRINT1("NtSetInformationFile() failed (Status 0x%08lx)\n", Status);

    return Status;
}

static NTSTATUS
CloseIniBootLoaderStore(
    IN PVOID Handle)
{
    NTSTATUS Status;
    PBOOT_STORE_INI_CONTEXT BootStore = (PBOOT_STORE_INI_CONTEXT)Handle;
    ULONG FileAttribute = 0;

    // if (!BootStore)
        // return STATUS_INVALID_PARAMETER;

    if (BootStore->SectionHandle)
    {
        /*
         * The INI file was already opened because it already existed,
         * thus (in the case of NTLDR's boot.ini), unprotect it.
         */
        if (BootStore->Header.Type == NtLdr)
        {
            Status = UnprotectBootIni(BootStore->FileHandle, &FileAttribute);
            if (!NT_SUCCESS(Status))
            {
                DPRINT1("Could not unprotect BOOT.INI ! (Status 0x%08lx)\n", Status);
                goto Quit;
            }
        }
    }

    IniCacheSaveByHandle(BootStore->IniCache, BootStore->FileHandle);

    /* In the case of NTLDR's boot.ini, re-protect the INI file */
    if (BootStore->Header.Type == NtLdr)
    {
        FileAttribute |= (FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_READONLY);
        Status = ProtectBootIni(BootStore->FileHandle, FileAttribute);
    }

Quit:
    IniCacheDestroy(BootStore->IniCache);

    if (BootStore->SectionHandle)
    {
        /* Finally, unmap and close the file */
        UnMapAndCloseFile(BootStore->FileHandle,
                          BootStore->SectionHandle,
                          BootStore->ViewBase);
    }
    else // if (BootStore->FileHandle)
    {
        /* Just close the file we have opened for creation */
        NtClose(BootStore->FileHandle);
    }

    /* Finally, free the boot store structure */
    RtlFreeHeap(ProcessHeap, 0, BootStore);

    // TODO: Use a correct Status based on the return values of the previous functions...
    return STATUS_SUCCESS;
}


NTSTATUS
OpenBootStoreByHandle(
    OUT PVOID* Handle,
    IN HANDLE PartitionDirectoryHandle, // OPTIONAL
    IN BOOT_STORE_TYPE Type,
    IN BOOLEAN CreateNew)
{
    /*
     * NOTE: Currently we open & map the loader configuration file without
     * further tests. It's OK as long as we only deal with FreeLdr's freeldr.ini
     * and NTLDR's boot.ini files. But as soon as we'll implement support for
     * BOOTMGR detection, the "configuration file" will be the BCD registry
     * hive and then, we'll have instead to mount the hive & open it.
     */

    if (Type >= BldrTypeMax || NtosBootLoaders[Type].Type >= BldrTypeMax)<--- Assuming that condition 'Type>=BldrTypeMax' is not redundant
    {
        DPRINT1("Loader type %d is currently unsupported!\n", NtosBootLoaders[Type].Type);<--- Array index out of bounds
        return STATUS_NOT_SUPPORTED;
    }

    return NtosBootLoaders[Type].OpenBootStore(Handle,
                                               PartitionDirectoryHandle,
                                               Type,
                                               CreateNew);
}

NTSTATUS
OpenBootStore_UStr(
    OUT PVOID* Handle,
    IN PUNICODE_STRING SystemPartitionPath,
    IN BOOT_STORE_TYPE Type,
    IN BOOLEAN CreateNew)
{
    NTSTATUS Status;
    OBJECT_ATTRIBUTES ObjectAttributes;
    IO_STATUS_BLOCK IoStatusBlock;
    HANDLE PartitionDirectoryHandle;

    /*
     * NOTE: Currently we open & map the loader configuration file without
     * further tests. It's OK as long as we only deal with FreeLdr's freeldr.ini
     * and NTLDR's boot.ini files. But as soon as we'll implement support for
     * BOOTMGR detection, the "configuration file" will be the BCD registry
     * hive and then, we'll have instead to mount the hive & open it.
     */

    if (Type >= BldrTypeMax || NtosBootLoaders[Type].Type >= BldrTypeMax)<--- Assuming that condition 'Type>=BldrTypeMax' is not redundant
    {
        DPRINT1("Loader type %d is currently unsupported!\n", NtosBootLoaders[Type].Type);<--- Array index out of bounds
        return STATUS_NOT_SUPPORTED;
    }

    /* Open SystemPartition */
    InitializeObjectAttributes(&ObjectAttributes,
                               SystemPartitionPath,
                               OBJ_CASE_INSENSITIVE,
                               NULL,
                               NULL);
    Status = NtOpenFile(&PartitionDirectoryHandle,
                        FILE_LIST_DIRECTORY | FILE_ADD_FILE /* | FILE_ADD_SUBDIRECTORY | FILE_TRAVERSE*/ | SYNCHRONIZE,
                        &ObjectAttributes,
                        &IoStatusBlock,
                        FILE_SHARE_READ | FILE_SHARE_WRITE,
                        FILE_SYNCHRONOUS_IO_NONALERT | FILE_DIRECTORY_FILE /* | FILE_OPEN_FOR_BACKUP_INTENT */);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Failed to open SystemPartition '%wZ', Status 0x%08lx\n", SystemPartitionPath, Status);
        return Status;
    }

    Status = OpenBootStoreByHandle(Handle, PartitionDirectoryHandle, Type, CreateNew);

    /* Done! */
    NtClose(PartitionDirectoryHandle);
    return Status;
}

NTSTATUS
OpenBootStore(
    OUT PVOID* Handle,
    IN PCWSTR SystemPartition,
    IN BOOT_STORE_TYPE Type,
    IN BOOLEAN CreateNew)
{
    UNICODE_STRING SystemPartitionPath;
    RtlInitUnicodeString(&SystemPartitionPath, SystemPartition);
    return OpenBootStore_UStr(Handle, &SystemPartitionPath, Type, CreateNew);
}

NTSTATUS
CloseBootStore(
    IN PVOID Handle)
{
    PBOOT_STORE_CONTEXT BootStore = (PBOOT_STORE_CONTEXT)Handle;

    if (!BootStore)
        return STATUS_INVALID_PARAMETER;

    /*
     * NOTE: Currently we open & map the loader configuration file without
     * further tests. It's OK as long as we only deal with FreeLdr's freeldr.ini
     * and NTLDR's boot.ini files. But as soon as we'll implement support for
     * BOOTMGR detection, the "configuration file" will be the BCD registry
     * hive and then, we'll have instead to mount the hive & open it.
     */

    if (BootStore->Type >= BldrTypeMax || NtosBootLoaders[BootStore->Type].Type >= BldrTypeMax)<--- Assuming that condition 'BootStore->Type>=BldrTypeMax' is not redundant
    {
        DPRINT1("Loader type %d is currently unsupported!\n", NtosBootLoaders[BootStore->Type].Type);<--- Array index out of bounds
        return STATUS_NOT_SUPPORTED;
    }

    return NtosBootLoaders[BootStore->Type].CloseBootStore(Handle /* BootStore */);
}



static
NTSTATUS
CreateNTOSEntry(
    IN PBOOT_STORE_INI_CONTEXT BootStore,
    IN ULONG_PTR BootEntryKey,
    IN PBOOT_STORE_ENTRY BootEntry)
{
    PINICACHESECTION IniSection;
    PWCHAR Section = (PWCHAR)BootEntryKey;

    /* Insert the entry into the "Operating Systems" section */
    IniCacheInsertKey(BootStore->OsIniSection, NULL, INSERT_LAST,
                      Section, (PWSTR)BootEntry->FriendlyName);

    /* Create a new section */
    IniSection = IniCacheAppendSection(BootStore->IniCache, Section);

    if (BootEntry->OsOptionsLength >= sizeof(NTOS_OPTIONS) &&
        RtlCompareMemory(&BootEntry->OsOptions /* Signature */,
                         NTOS_OPTIONS_SIGNATURE,
                         RTL_FIELD_SIZE(NTOS_OPTIONS, Signature)) ==
                         RTL_FIELD_SIZE(NTOS_OPTIONS, Signature))
    {
        PNTOS_OPTIONS Options = (PNTOS_OPTIONS)&BootEntry->OsOptions;

        /* BootType= */
        IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                          L"BootType", L"Windows2003");

        /* SystemPath= */
        IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                          L"SystemPath", (PWSTR)Options->OsLoadPath);

        /* Options= */
        IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                          L"Options", (PWSTR)Options->OsLoadOptions);
    }
    else
    if (BootEntry->OsOptionsLength >= sizeof(BOOT_SECTOR_OPTIONS) &&
        RtlCompareMemory(&BootEntry->OsOptions /* Signature */,
                         BOOT_SECTOR_OPTIONS_SIGNATURE,
                         RTL_FIELD_SIZE(BOOT_SECTOR_OPTIONS, Signature)) ==
                         RTL_FIELD_SIZE(BOOT_SECTOR_OPTIONS, Signature))
    {
        PBOOT_SECTOR_OPTIONS Options = (PBOOT_SECTOR_OPTIONS)&BootEntry->OsOptions;

        /* BootType= */
        IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                          L"BootType", L"BootSector");

        /* BootDrive= */
        IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                          L"BootDrive", (PWSTR)Options->Drive);

        /* BootPartition= */
        IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                          L"BootPartition", (PWSTR)Options->Partition);

        /* BootSector= */
        IniCacheInsertKey(IniSection, NULL, INSERT_LAST,
                          L"BootSectorFile", (PWSTR)Options->BootSectorFileName);
    }
    else
    {
        // DPRINT1("Unsupported BootType %lu/'%*.s'\n",
                // BootEntry->OsOptionsLength, 8, &BootEntry->OsOptions);
        DPRINT1("Unsupported BootType %lu\n", BootEntry->OsOptionsLength);
    }

    return STATUS_SUCCESS;
}

NTSTATUS
AddBootStoreEntry(
    IN PVOID Handle,
    IN PBOOT_STORE_ENTRY BootEntry,
    IN ULONG_PTR BootEntryKey)
{
    PBOOT_STORE_CONTEXT BootStore = (PBOOT_STORE_CONTEXT)Handle;

    if (!BootStore || !BootEntry)
        return STATUS_INVALID_PARAMETER;

    /*
     * NOTE: Currently we open & map the loader configuration file without
     * further tests. It's OK as long as we only deal with FreeLdr's freeldr.ini
     * and NTLDR's boot.ini files. But as soon as we'll implement support for
     * BOOTMGR detection, the "configuration file" will be the BCD registry
     * hive and then, we'll have instead to mount the hive & open it.
     */

    //
    // FIXME!!
    //

    // if (BootStore->Type >= BldrTypeMax || NtosBootLoaders[BootStore->Type].Type >= BldrTypeMax)

    if (BootStore->Type == FreeLdr)
    {
        if (BootEntry->Version != FreeLdr)
            return STATUS_INVALID_PARAMETER;

        return CreateNTOSEntry((PBOOT_STORE_INI_CONTEXT)BootStore,
                               BootEntryKey, BootEntry);
    }
    else
    if (BootStore->Type == NtLdr)
    {
        PNTOS_OPTIONS Options = (PNTOS_OPTIONS)&BootEntry->OsOptions;
        PWCHAR Buffer;
        ULONG BufferLength;
        PCWSTR InstallName, OsOptions;
        // ULONG InstallNameLength, OsOptionsLength;
        BOOLEAN IsNameNotQuoted;

        if (BootEntry->Version != NtLdr)
            return STATUS_INVALID_PARAMETER;

        if (BootEntry->OsOptionsLength < sizeof(NTOS_OPTIONS) ||
            RtlCompareMemory(&BootEntry->OsOptions /* Signature */,
                             NTOS_OPTIONS_SIGNATURE,
                             RTL_FIELD_SIZE(NTOS_OPTIONS, Signature)) !=
                             RTL_FIELD_SIZE(NTOS_OPTIONS, Signature))
        {
            // DPRINT1("Unsupported BootType '%S'\n", BootEntry->Version);
            DPRINT1("Unsupported BootType %lu\n", BootEntry->OsOptionsLength);
            return STATUS_SUCCESS; // STATUS_NOT_SUPPORTED;
        }

        InstallName = BootEntry->FriendlyName;
        OsOptions = Options->OsLoadOptions;

        // if (InstallNameLength == 0) InstallName = NULL;
        // if (OsOptionsLength == 0) OsOptions = NULL;

        IsNameNotQuoted = (InstallName[0] != L'\"' || InstallName[wcslen(InstallName)-1] != L'\"');

        BufferLength = (IsNameNotQuoted ? 2 /* Quotes for FriendlyName*/ : 0) + wcslen(InstallName);
        if (OsOptions)
            BufferLength += 1 /* Space between FriendlyName and options */ + wcslen(OsOptions);
        BufferLength++; /* NULL-termination */

        Buffer = RtlAllocateHeap(ProcessHeap, HEAP_ZERO_MEMORY, BufferLength * sizeof(WCHAR));
        if (!Buffer)
            return STATUS_INSUFFICIENT_RESOURCES;

        *Buffer = UNICODE_NULL;
        if (IsNameNotQuoted) RtlStringCchCatW(Buffer, BufferLength, L"\"");
        RtlStringCchCatW(Buffer, BufferLength, InstallName);
        if (IsNameNotQuoted) RtlStringCchCatW(Buffer, BufferLength, L"\"");
        if (OsOptions)
        {
            RtlStringCchCatW(Buffer, BufferLength, L" ");
            RtlStringCchCatW(Buffer, BufferLength, OsOptions);
        }

        /* Insert the entry into the "Operating Systems" section */
        IniCacheInsertKey(((PBOOT_STORE_INI_CONTEXT)BootStore)->OsIniSection, NULL, INSERT_LAST,
                          (PWSTR)Options->OsLoadPath, Buffer);

        RtlFreeHeap(ProcessHeap, 0, Buffer);
        return STATUS_SUCCESS;
    }
    else
    {
        DPRINT1("Loader type %d is currently unsupported!\n", BootStore->Type);
        return STATUS_NOT_SUPPORTED;
    }
}

NTSTATUS
DeleteBootStoreEntry(
    IN PVOID Handle,
    IN ULONG_PTR BootEntryKey)
{
    PBOOT_STORE_CONTEXT BootStore = (PBOOT_STORE_CONTEXT)Handle;

    if (!BootStore)
        return STATUS_INVALID_PARAMETER;

    /*
     * NOTE: Currently we open & map the loader configuration file without
     * further tests. It's OK as long as we only deal with FreeLdr's freeldr.ini
     * and NTLDR's boot.ini files. But as soon as we'll implement support for
     * BOOTMGR detection, the "configuration file" will be the BCD registry
     * hive and then, we'll have instead to mount the hive & open it.
     */

    //
    // FIXME!!
    //

    // if (BootStore->Type >= BldrTypeMax || NtosBootLoaders[BootStore->Type].Type >= BldrTypeMax)
    if (BootStore->Type != FreeLdr)
    {
        DPRINT1("Loader type %d is currently unsupported!\n", NtosBootLoaders[BootStore->Type].Type);
        return STATUS_NOT_SUPPORTED;
    }

    // FIXME! This function needs my INI library rewrite to be implemented!!
    UNIMPLEMENTED;
    return STATUS_NOT_IMPLEMENTED;
}

NTSTATUS
ModifyBootStoreEntry(
    IN PVOID Handle,
    IN PBOOT_STORE_ENTRY BootEntry)
{
    PBOOT_STORE_CONTEXT BootStore = (PBOOT_STORE_CONTEXT)Handle;

    if (!BootStore || !BootEntry)
        return STATUS_INVALID_PARAMETER;

    /*
     * NOTE: Currently we open & map the loader configuration file without
     * further tests. It's OK as long as we only deal with FreeLdr's freeldr.ini
     * and NTLDR's boot.ini files. But as soon as we'll implement support for
     * BOOTMGR detection, the "configuration file" will be the BCD registry
     * hive and then, we'll have instead to mount the hive & open it.
     */

    //
    // FIXME!!
    //

    // if (BootStore->Type >= BldrTypeMax || NtosBootLoaders[BootStore->Type].Type >= BldrTypeMax)
    if (BootStore->Type != FreeLdr)
    {
        DPRINT1("Loader type %d is currently unsupported!\n", NtosBootLoaders[BootStore->Type].Type);
        return STATUS_NOT_SUPPORTED;
    }

    // FIXME! This function needs my INI library rewrite to operate properly!!
    UNIMPLEMENTED;
    return STATUS_NOT_IMPLEMENTED;
}

NTSTATUS
QueryBootStoreEntry(
    IN PVOID Handle,
    IN ULONG_PTR BootEntryKey,
    OUT PBOOT_STORE_ENTRY BootEntry) // Technically this should be PBOOT_STORE_ENTRY*
{
    PBOOT_STORE_CONTEXT BootStore = (PBOOT_STORE_CONTEXT)Handle;

    if (!BootStore)
        return STATUS_INVALID_PARAMETER;

    /*
     * NOTE: Currently we open & map the loader configuration file without
     * further tests. It's OK as long as we only deal with FreeLdr's freeldr.ini
     * and NTLDR's boot.ini files. But as soon as we'll implement support for
     * BOOTMGR detection, the "configuration file" will be the BCD registry
     * hive and then, we'll have instead to mount the hive & open it.
     */

    //
    // FIXME!!
    //

    // if (BootStore->Type >= BldrTypeMax || NtosBootLoaders[BootStore->Type].Type >= BldrTypeMax)
    if (BootStore->Type != FreeLdr)
    {
        DPRINT1("Loader type %d is currently unsupported!\n", NtosBootLoaders[BootStore->Type].Type);
        return STATUS_NOT_SUPPORTED;
    }

    // FIXME! This function needs my INI library rewrite to be implemented!!
    UNIMPLEMENTED;
    return STATUS_NOT_IMPLEMENTED;
}

NTSTATUS
QueryBootStoreOptions(
    IN PVOID Handle,
    IN OUT PBOOT_STORE_OPTIONS BootOptions
/* , IN PULONG BootOptionsLength */ )
{
    NTSTATUS Status = STATUS_SUCCESS;
    PBOOT_STORE_CONTEXT BootStore = (PBOOT_STORE_CONTEXT)Handle;
    PWCHAR TimeoutStr;

    if (!BootStore || !BootOptions)
        return STATUS_INVALID_PARAMETER;

    /*
     * NOTE: Currently we open & map the loader configuration file without
     * further tests. It's OK as long as we only deal with FreeLdr's freeldr.ini
     * and NTLDR's boot.ini files. But as soon as we'll implement support for
     * BOOTMGR detection, the "configuration file" will be the BCD registry
     * hive and then, we'll have instead to mount the hive & open it.
     */

    //
    // FIXME!!
    //

    // if (BootStore->Type >= BldrTypeMax || NtosBootLoaders[BootStore->Type].Type >= BldrTypeMax)
    if (BootStore->Type != FreeLdr && BootStore->Type != NtLdr)
    {
        DPRINT1("Loader type %d is currently unsupported!\n", BootStore->Type);
        return STATUS_NOT_SUPPORTED;
    }

    if (BootStore->Type == FreeLdr)
    {
        BootOptions->Version = FreeLdr;

        Status = IniCacheGetKey(((PBOOT_STORE_INI_CONTEXT)BootStore)->OptionsIniSection,
                                L"DefaultOS", (PWCHAR*)&BootOptions->CurrentBootEntryKey);
        if (!NT_SUCCESS(Status))
            BootOptions->CurrentBootEntryKey = 0;

        Status = IniCacheGetKey(((PBOOT_STORE_INI_CONTEXT)BootStore)->OptionsIniSection,
                                L"TimeOut", &TimeoutStr);
        if (NT_SUCCESS(Status) && TimeoutStr)
            BootOptions->Timeout = _wtoi(TimeoutStr);
        else
            BootOptions->Timeout = 0;
    }
    else if (BootStore->Type == NtLdr)
    {
        BootOptions->Version = NtLdr;

        Status = IniCacheGetKey(((PBOOT_STORE_INI_CONTEXT)BootStore)->OptionsIniSection,
                                L"default", (PWCHAR*)&BootOptions->CurrentBootEntryKey);
        if (!NT_SUCCESS(Status))
            BootOptions->CurrentBootEntryKey = 0;

        Status = IniCacheGetKey(((PBOOT_STORE_INI_CONTEXT)BootStore)->OptionsIniSection,
                                L"timeout", &TimeoutStr);
        if (NT_SUCCESS(Status) && TimeoutStr)
            BootOptions->Timeout = _wtoi(TimeoutStr);
        else
            BootOptions->Timeout = 0;
    }

    return STATUS_SUCCESS; // FIXME: use Status; instead?
}

NTSTATUS
SetBootStoreOptions(
    IN PVOID Handle,
    IN PBOOT_STORE_OPTIONS BootOptions,
    IN ULONG FieldsToChange)
{
    PBOOT_STORE_CONTEXT BootStore = (PBOOT_STORE_CONTEXT)Handle;
    WCHAR TimeoutStr[15];

    if (!BootStore || !BootOptions)
        return STATUS_INVALID_PARAMETER;

    /*
     * NOTE: Currently we open & map the loader configuration file without
     * further tests. It's OK as long as we only deal with FreeLdr's freeldr.ini
     * and NTLDR's boot.ini files. But as soon as we'll implement support for
     * BOOTMGR detection, the "configuration file" will be the BCD registry
     * hive and then, we'll have instead to mount the hive & open it.
     */

    //
    // FIXME!!
    //

    // if (BootStore->Type >= BldrTypeMax || NtosBootLoaders[BootStore->Type].Type >= BldrTypeMax)
    if (BootStore->Type != FreeLdr)
    {
        DPRINT1("Loader type %d is currently unsupported!\n", NtosBootLoaders[BootStore->Type].Type);
        return STATUS_NOT_SUPPORTED;
    }

    if (BootOptions->Version != FreeLdr)
        return STATUS_INVALID_PARAMETER;

    //
    // TODO: Depending on the flags set in 'FieldsToChange',
    // change either one or both these bootloader options.
    //
    IniCacheInsertKey(((PBOOT_STORE_INI_CONTEXT)BootStore)->OptionsIniSection,
                      NULL, INSERT_LAST,
                      L"DefaultOS", (PWCHAR)BootOptions->CurrentBootEntryKey);

    RtlStringCchPrintfW(TimeoutStr, ARRAYSIZE(TimeoutStr), L"%d", BootOptions->Timeout);
    IniCacheInsertKey(((PBOOT_STORE_INI_CONTEXT)BootStore)->OptionsIniSection,
                      NULL, INSERT_FIRST, // INSERT_LAST, // FIXME!! There is a bug in the INI parser where a given key can be inserted twice in the same section...
                      L"TimeOut", TimeoutStr);

    return STATUS_SUCCESS;
}



static NTSTATUS
FreeLdrEnumerateBootEntries(
    IN PBOOT_STORE_INI_CONTEXT BootStore,
//  IN ULONG Flags, // Determine which data to retrieve
    IN PENUM_BOOT_ENTRIES_ROUTINE EnumBootEntriesRoutine,
    IN PVOID Parameter OPTIONAL)
{
    NTSTATUS Status = STATUS_SUCCESS;
    PINICACHEITERATOR Iterator;
    PINICACHESECTION OsIniSection;
    PWCHAR SectionName, KeyData;
    UCHAR xxBootEntry[FIELD_OFFSET(BOOT_STORE_ENTRY, OsOptions) +
                      max(sizeof(NTOS_OPTIONS), sizeof(BOOT_SECTOR_OPTIONS))];
    PBOOT_STORE_ENTRY BootEntry = (PBOOT_STORE_ENTRY)&xxBootEntry;
    PWCHAR Buffer;

    /* Enumerate all the valid installations listed in the "Operating Systems" section */
    Iterator = IniCacheFindFirstValue(BootStore->OsIniSection, &SectionName, &KeyData);
    if (!Iterator) return STATUS_SUCCESS;
    do
    {
        PWCHAR InstallName;
        ULONG InstallNameLength;

        /* Poor-man quotes removal (improvement over bootsup.c:UpdateFreeLoaderIni) */
        if (*KeyData == L'"')
        {
            /* Quoted name, copy up to the closing quote */
            PWCHAR End = wcschr(KeyData + 1, L'"');

            if (End)
            {
                /* Skip the first quote */
                InstallName = KeyData + 1;
                InstallNameLength = End - InstallName;
            }
            else // if (!End)
            {
                /* No corresponding closing quote, so we include the first one in the InstallName */
                InstallName = KeyData;
                InstallNameLength = wcslen(InstallName);
            }
            if (InstallNameLength == 0) InstallName = NULL;
        }
        else
        {
            /* Non-quoted name, copy everything */
            InstallName = KeyData;
            InstallNameLength = wcslen(InstallName);
            if (InstallNameLength == 0) InstallName = NULL;
        }

        /* Allocate the temporary buffer */
        Buffer = NULL;
        if (InstallNameLength)
            Buffer = RtlAllocateHeap(ProcessHeap, HEAP_ZERO_MEMORY, (InstallNameLength + 1) * sizeof(WCHAR));
        if (Buffer)
        {
            RtlCopyMemory(Buffer, InstallName, InstallNameLength * sizeof(WCHAR));
            Buffer[InstallNameLength] = UNICODE_NULL;
            InstallName = Buffer;
        }

        DPRINT("Boot entry '%S' in OS section '%S'\n", InstallName, SectionName);

        BootEntry->Version = FreeLdr;
        BootEntry->BootEntryKey = MAKESTRKEY(SectionName);
        BootEntry->FriendlyName = InstallName;
        BootEntry->BootFilePath = NULL;
        BootEntry->OsOptionsLength = 0;

        /* Search for an existing boot entry section */
        OsIniSection = IniCacheGetSection(BootStore->IniCache, SectionName);
        if (!OsIniSection)
            goto DoEnum;

        /* Check for supported boot type "Windows2003" */
        Status = IniCacheGetKey(OsIniSection, L"BootType", &KeyData);
        if (!NT_SUCCESS(Status) || (KeyData == NULL))
        {
            /* Certainly not a ReactOS installation */
            DPRINT1("No BootType value present!\n");
            goto DoEnum;
        }

        // TODO: What to do with "Windows" ; "WindowsNT40" ; "ReactOSSetup" ?
        if ((_wcsicmp(KeyData, L"Windows2003")     == 0) ||
            (_wcsicmp(KeyData, L"\"Windows2003\"") == 0))
        {
            /* BootType is Windows2003 */
            PNTOS_OPTIONS Options = (PNTOS_OPTIONS)&BootEntry->OsOptions;

            DPRINT("This is a '%S' boot entry\n", KeyData);

            BootEntry->OsOptionsLength = sizeof(NTOS_OPTIONS);
            RtlCopyMemory(Options->Signature,
                          NTOS_OPTIONS_SIGNATURE,
                          RTL_FIELD_SIZE(NTOS_OPTIONS, Signature));

            // BootEntry->BootFilePath = NULL;

            /* Check its SystemPath */
            Status = IniCacheGetKey(OsIniSection, L"SystemPath", &KeyData);
            if (!NT_SUCCESS(Status))
                Options->OsLoadPath = NULL;
            else
                Options->OsLoadPath = KeyData;
            // KeyData == SystemRoot;

            /* Check the optional Options */
            Status = IniCacheGetKey(OsIniSection, L"Options", &KeyData);
            if (!NT_SUCCESS(Status))
                Options->OsLoadOptions = NULL;
            else
                Options->OsLoadOptions = KeyData;
        }
        else
        if ((_wcsicmp(KeyData, L"BootSector")     == 0) ||
            (_wcsicmp(KeyData, L"\"BootSector\"") == 0))
        {
            /* BootType is BootSector */
            PBOOT_SECTOR_OPTIONS Options = (PBOOT_SECTOR_OPTIONS)&BootEntry->OsOptions;

            DPRINT("This is a '%S' boot entry\n", KeyData);

            BootEntry->OsOptionsLength = sizeof(BOOT_SECTOR_OPTIONS);
            RtlCopyMemory(Options->Signature,
                          BOOT_SECTOR_OPTIONS_SIGNATURE,
                          RTL_FIELD_SIZE(BOOT_SECTOR_OPTIONS, Signature));

            // BootEntry->BootFilePath = NULL;

            /* Check its BootDrive */
            Status = IniCacheGetKey(OsIniSection, L"BootDrive", &KeyData);
            if (!NT_SUCCESS(Status))
                Options->Drive = NULL;
            else
                Options->Drive = KeyData;

            /* Check its BootPartition */
            Status = IniCacheGetKey(OsIniSection, L"BootPartition", &KeyData);
            if (!NT_SUCCESS(Status))
                Options->Partition = NULL;
            else
                Options->Partition = KeyData;

            /* Check its BootSector */
            Status = IniCacheGetKey(OsIniSection, L"BootSectorFile", &KeyData);
            if (!NT_SUCCESS(Status))
                Options->BootSectorFileName = NULL;
            else
                Options->BootSectorFileName = KeyData;
        }
        else
        {
            DPRINT1("Unrecognized BootType value '%S'\n", KeyData);
            // goto DoEnum;
        }

DoEnum:
        /* Call the user enumeration routine callback */
        Status = EnumBootEntriesRoutine(FreeLdr, BootEntry, Parameter);

        /* Free temporary buffers */
        if (Buffer)
            RtlFreeHeap(ProcessHeap, 0, Buffer);

        /* Stop the enumeration if needed */
        if (!NT_SUCCESS(Status))
            break;
    }
    while (IniCacheFindNextValue(Iterator, &SectionName, &KeyData));

    IniCacheFindClose(Iterator);
    return Status;
}

static NTSTATUS
NtLdrEnumerateBootEntries(
    IN PBOOT_STORE_INI_CONTEXT BootStore,
//  IN ULONG Flags, // Determine which data to retrieve
    IN PENUM_BOOT_ENTRIES_ROUTINE EnumBootEntriesRoutine,
    IN PVOID Parameter OPTIONAL)
{
    NTSTATUS Status = STATUS_SUCCESS;
    PINICACHEITERATOR Iterator;
    PWCHAR SectionName, KeyData;
    UCHAR xxBootEntry[FIELD_OFFSET(BOOT_STORE_ENTRY, OsOptions) + sizeof(NTOS_OPTIONS)];
    PBOOT_STORE_ENTRY BootEntry = (PBOOT_STORE_ENTRY)&xxBootEntry;
    PNTOS_OPTIONS Options = (PNTOS_OPTIONS)&BootEntry->OsOptions;
    PWCHAR Buffer;
    ULONG BufferLength;

    /* Enumerate all the valid installations */
    Iterator = IniCacheFindFirstValue(BootStore->OsIniSection, &SectionName, &KeyData);
    if (!Iterator) return STATUS_SUCCESS;
    do
    {
        PWCHAR InstallName, OsOptions;
        ULONG InstallNameLength, OsOptionsLength;

        /* Poor-man quotes removal (improvement over bootsup.c:UpdateFreeLoaderIni) */
        if (*KeyData == L'"')
        {
            /* Quoted name, copy up to the closing quote */
            OsOptions = wcschr(KeyData + 1, L'"');

            /* Retrieve the starting point of the installation name and the OS options */
            if (OsOptions)
            {
                /* Skip the first quote */
                InstallName = KeyData + 1;
                InstallNameLength = OsOptions - InstallName;
                if (InstallNameLength == 0) InstallName = NULL;

                /* Skip the ending quote (if found) */
                ++OsOptions;

                /* Skip any whitespace */
                while (iswspace(*OsOptions)) ++OsOptions;
                /* Get its final length */
                OsOptionsLength = wcslen(OsOptions);
                if (OsOptionsLength == 0) OsOptions = NULL;
            }
            else
            {
                /* No corresponding closing quote, so we include the first one in the InstallName */
                InstallName = KeyData;
                InstallNameLength = wcslen(InstallName);
                if (InstallNameLength == 0) InstallName = NULL;

                /* There are no OS options */
                // OsOptions = NULL;
                OsOptionsLength = 0;
            }
        }
        else
        {
            /* Non-quoted name, copy everything */

            /* Retrieve the starting point of the installation name */
            InstallName = KeyData;
            InstallNameLength = wcslen(InstallName);
            if (InstallNameLength == 0) InstallName = NULL;

            /* There are no OS options */
            OsOptions = NULL;
            OsOptionsLength = 0;
        }

        /* Allocate the temporary buffer */
        Buffer = NULL;
        BufferLength = (InstallNameLength + OsOptionsLength) * sizeof(WCHAR);
        if (BufferLength)
            Buffer = RtlAllocateHeap(ProcessHeap, HEAP_ZERO_MEMORY, BufferLength + 2*sizeof(UNICODE_NULL));
        if (Buffer)
        {
            PWCHAR ptr;

            /* Copy the installation name, and make InstallName point into the buffer */
            if (InstallName && InstallNameLength)
            {
                ptr = Buffer;
                RtlCopyMemory(ptr, InstallName, InstallNameLength * sizeof(WCHAR));
                ptr[InstallNameLength] = UNICODE_NULL;
                InstallName = ptr;
            }

            /* Copy the OS options, and make OsOptions point into the buffer */
            if (OsOptions && OsOptionsLength)
            {
                ptr = Buffer + InstallNameLength + 1;
                RtlCopyMemory(ptr, OsOptions, OsOptionsLength * sizeof(WCHAR));
                ptr[OsOptionsLength] = UNICODE_NULL;
                OsOptions = ptr;
            }
        }

        DPRINT1("Boot entry '%S' in OS section (path) '%S'\n", InstallName, SectionName);
        // SectionName == SystemRoot;

        BootEntry->Version = NtLdr;
        BootEntry->BootEntryKey = 0; // FIXME??
        BootEntry->FriendlyName = InstallName;
        BootEntry->BootFilePath = NULL;

        BootEntry->OsOptionsLength = sizeof(NTOS_OPTIONS);
        RtlCopyMemory(Options->Signature,
                      NTOS_OPTIONS_SIGNATURE,
                      RTL_FIELD_SIZE(NTOS_OPTIONS, Signature));

        Options->OsLoadPath    = SectionName;
        Options->OsLoadOptions = OsOptions;

        /* Call the user enumeration routine callback */
        Status = EnumBootEntriesRoutine(NtLdr, BootEntry, Parameter);

        /* Free temporary buffers */
        if (Buffer)
            RtlFreeHeap(ProcessHeap, 0, Buffer);

        /* Stop the enumeration if needed */
        if (!NT_SUCCESS(Status))
            break;
    }
    while (IniCacheFindNextValue(Iterator, &SectionName, &KeyData));

    IniCacheFindClose(Iterator);
    return Status;
}

NTSTATUS
EnumerateBootStoreEntries(
    IN PVOID Handle,
//  IN ULONG Flags, // Determine which data to retrieve
    IN PENUM_BOOT_ENTRIES_ROUTINE EnumBootEntriesRoutine,
    IN PVOID Parameter OPTIONAL)
{
    PBOOT_STORE_CONTEXT BootStore = (PBOOT_STORE_CONTEXT)Handle;

    if (!BootStore)
        return STATUS_INVALID_PARAMETER;

    if (BootStore->Type >= BldrTypeMax || NtosBootLoaders[BootStore->Type].Type >= BldrTypeMax)<--- Assuming that condition 'BootStore->Type>=BldrTypeMax' is not redundant
    {
        DPRINT1("Loader type %d is currently unsupported!\n", NtosBootLoaders[BootStore->Type].Type);<--- Array index out of bounds
        /**/return STATUS_SUCCESS;/**/
        // return STATUS_INVALID_PARAMETER;
    }

    return NtosBootLoaders[BootStore->Type].EnumBootStoreEntries(
                (PBOOT_STORE_INI_CONTEXT)BootStore, // Flags,
                EnumBootEntriesRoutine, Parameter);
}

/* EOF */