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
/*
 * COPYRIGHT:       See COPYING in the top level directory
 * PROJECT:         ReactOS system libraries
 * FILE:            lib/advapi32/reg/hkcr.c
 * PURPOSE:         Registry functions - HKEY_CLASSES_ROOT abstraction
 * PROGRAMMER:      Jerôme Gardou (jerome.gardou@reactos.org)
 */

#include <advapi32.h>

#include <ndk/cmfuncs.h>
#include <pseh/pseh2.h>

#include "reg.h"

WINE_DEFAULT_DEBUG_CHANNEL(reg);

static const UNICODE_STRING HKLM_ClassesPath = RTL_CONSTANT_STRING(L"\\Registry\\Machine\\Software\\Classes");

static
LONG
GetKeyName(HKEY hKey, PUNICODE_STRING KeyName)
{
    UNICODE_STRING InfoName;
    PKEY_NAME_INFORMATION NameInformation;
    ULONG InfoLength;
    NTSTATUS Status;

    /* Get info length */
    InfoLength = 0;
    Status = NtQueryKey(hKey, KeyNameInformation, NULL, 0, &InfoLength);
    if (Status != STATUS_BUFFER_TOO_SMALL)
    {
        ERR("NtQueryKey returned unexpected Status: 0x%08x\n", Status);
        return RtlNtStatusToDosError(Status);
    }

    /* Get it for real */
    NameInformation = RtlAllocateHeap(RtlGetProcessHeap(), 0, InfoLength);
    if (NameInformation == NULL)
    {
        ERR("Failed to allocate %lu bytes", InfoLength);
        return ERROR_NOT_ENOUGH_MEMORY;
    }

    Status = NtQueryKey(hKey, KeyNameInformation, NameInformation, InfoLength, &InfoLength);
    if (!NT_SUCCESS(Status))
    {
        RtlFreeHeap(RtlGetProcessHeap(), 0, NameInformation);
        ERR("NtQueryKey failed: 0x%08x\n", Status);
        return RtlNtStatusToDosError(Status);
    }

    /* Make it a proper UNICODE_STRING */
    InfoName.Length = NameInformation->NameLength;
    InfoName.MaximumLength = NameInformation->NameLength;
    InfoName.Buffer = NameInformation->Name;

    Status = RtlDuplicateUnicodeString(RTL_DUPLICATE_UNICODE_STRING_NULL_TERMINATE, &InfoName, KeyName);
    if (!NT_SUCCESS(Status))
    {
        RtlFreeHeap(RtlGetProcessHeap(), 0, NameInformation);
        ERR("RtlDuplicateUnicodeString failed: 0x%08x\n", Status);
        return RtlNtStatusToDosError(Status);
    }

    RtlFreeHeap(RtlGetProcessHeap(), 0, NameInformation);

    return ERROR_SUCCESS;
}

static
LONG
GetKeySam(
    _In_ HKEY hKey,
    _Out_ REGSAM* RegSam)
{
    NTSTATUS Status;
    OBJECT_BASIC_INFORMATION ObjectInfo;

    Status = NtQueryObject(hKey, ObjectBasicInformation, &ObjectInfo, sizeof(ObjectInfo), NULL);
    if (!NT_SUCCESS(Status))
    {
        ERR("NtQueryObject failed, Status %x08x\n", Status);
        return RtlNtStatusToDosError(Status);
    }

    *RegSam = ObjectInfo.GrantedAccess;
    return ERROR_SUCCESS;
}

/*
 * Gets a HKLM key from an HKCU key.
 */
static
LONG
GetFallbackHKCRKey(
    _In_ HKEY hKey,
    _Out_ HKEY* MachineKey,
    _In_ BOOL MustCreate)
{
    UNICODE_STRING KeyName;
    LPWSTR SubKeyName;
    LONG ErrorCode;
    REGSAM SamDesired;

    /* Get the key name */
    ErrorCode = GetKeyName(hKey, &KeyName);
    if (ErrorCode != ERROR_SUCCESS)
        return ErrorCode;

    /* See if we really need a conversion */
    if (RtlPrefixUnicodeString(&HKLM_ClassesPath, &KeyName, TRUE))
    {
        RtlFreeUnicodeString(&KeyName);
        *MachineKey = hKey;
        return ERROR_SUCCESS;
    }

    SubKeyName = KeyName.Buffer + 15; /* 15 == wcslen(L"\\Registry\\User\\") */
    /* Skip the user token */
    while (*SubKeyName++ != L'\\')
    {
        if (!*SubKeyName)
        {
            ERR("Key name %S is invalid!\n", KeyName.Buffer);
            return ERROR_INTERNAL_ERROR;
        }
    }

    /* Use the same access mask than the original key */
    ErrorCode = GetKeySam(hKey, &SamDesired);
    if (ErrorCode != ERROR_SUCCESS)
    {
        RtlFreeUnicodeString(&KeyName);
        return ErrorCode;
    }

    if (MustCreate)
    {
        ErrorCode = RegCreateKeyExW(
            HKEY_LOCAL_MACHINE,
            SubKeyName,
            0,
            NULL,
            0,
            SamDesired,
            NULL,
            MachineKey,
            NULL);
    }
    else
    {
        /* Open the key. */
        ErrorCode = RegOpenKeyExW(
            HKEY_LOCAL_MACHINE,
            SubKeyName,
            0,
            SamDesired,
            MachineKey);
    }

    RtlFreeUnicodeString(&KeyName);

    return ErrorCode;
}

/* Get the HKCU key (if it exists) from an HKCR key */
static
LONG
GetPreferredHKCRKey(
    _In_ HKEY hKey,
    _Out_ HKEY* PreferredKey)
{
    UNICODE_STRING KeyName;
    LPWSTR SubKeyName;
    LONG ErrorCode;
    REGSAM SamDesired;

    /* Get the key name */
    ErrorCode = GetKeyName(hKey, &KeyName);
    if (ErrorCode != ERROR_SUCCESS)
        return ErrorCode;

    /* See if we really need a conversion */
    if (!RtlPrefixUnicodeString(&HKLM_ClassesPath, &KeyName, TRUE))
    {
        RtlFreeUnicodeString(&KeyName);
        *PreferredKey = hKey;
        return ERROR_SUCCESS;
    }

    /* 18 == wcslen(L"\\Registry\\Machine\\") */
    SubKeyName = KeyName.Buffer + 18;

    /* Use the same access mask than the original key */
    ErrorCode = GetKeySam(hKey, &SamDesired);
    if (ErrorCode != ERROR_SUCCESS)
    {
        RtlFreeUnicodeString(&KeyName);
        return ErrorCode;
    }

    /* Open the key. */
    ErrorCode = RegOpenKeyExW(
        HKEY_CURRENT_USER,
        SubKeyName,
        0,
        SamDesired,
        PreferredKey);

    RtlFreeUnicodeString(&KeyName);

    return ErrorCode;
}

/* HKCR version of RegCreateKeyExW. */
LONG
WINAPI
CreateHKCRKey(
    _In_ HKEY hKey,
    _In_ LPCWSTR lpSubKey,
    _In_ DWORD Reserved,
    _In_opt_ LPWSTR lpClass,
    _In_ DWORD dwOptions,
    _In_ REGSAM samDesired,
    _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
    _Out_ PHKEY phkResult,
    _Out_opt_ LPDWORD lpdwDisposition)
{
    LONG ErrorCode;
    HKEY QueriedKey, TestKey;

    ASSERT(IsHKCRKey(hKey));

    /* Remove the HKCR flag while we're working */
    hKey = (HKEY)(((ULONG_PTR)hKey) & ~0x2);

    ErrorCode = GetPreferredHKCRKey(hKey, &QueriedKey);

    if (ErrorCode == ERROR_FILE_NOT_FOUND)
    {
        /* The current key doesn't exist on HKCU side, so we can only create it in HKLM */
        ErrorCode = RegCreateKeyExW(
            hKey,
            lpSubKey,
            Reserved,
            lpClass,
            dwOptions,
            samDesired,
            lpSecurityAttributes,
            phkResult,
            lpdwDisposition);
        if (ErrorCode == ERROR_SUCCESS)
            MakeHKCRKey(phkResult);
        return ErrorCode;
    }

    if (ErrorCode != ERROR_SUCCESS)
    {
        /* Somehow we failed for another reason (maybe deleted key or whatever) */
        return ErrorCode;
    }

    /* See if the subkey already exists in HKCU. */
    ErrorCode = RegOpenKeyExW(QueriedKey, lpSubKey, 0, READ_CONTROL, &TestKey);
    if (ErrorCode != ERROR_FILE_NOT_FOUND)
    {
        if (ErrorCode == ERROR_SUCCESS)
        {
            /* Great. Close the test one and do the real create operation */
            RegCloseKey(TestKey);
            ErrorCode = RegCreateKeyExW(
                QueriedKey,
                lpSubKey,
                Reserved,
                lpClass,
                dwOptions,
                samDesired,
                lpSecurityAttributes,
                phkResult,
                lpdwDisposition);
            if (ErrorCode == ERROR_SUCCESS)
                MakeHKCRKey(phkResult);
        }
        if (QueriedKey != hKey)
            RegCloseKey(QueriedKey);

        return ERROR_SUCCESS;
    }

    if (QueriedKey != hKey)
        RegCloseKey(QueriedKey);

    /* So we must do the create operation in HKLM, creating the missing parent keys if needed. */
    ErrorCode = GetFallbackHKCRKey(hKey, &QueriedKey, TRUE);
    if (ErrorCode != ERROR_SUCCESS)
        return ErrorCode;

    /* Do the key creation */
    ErrorCode = RegCreateKeyEx(
        QueriedKey,
        lpSubKey,
        Reserved,
        lpClass,
        dwOptions,
        samDesired,
        lpSecurityAttributes,
        phkResult,
        lpdwDisposition);

    if (QueriedKey != hKey)
        RegCloseKey(QueriedKey);

    if (ErrorCode == ERROR_SUCCESS)
        MakeHKCRKey(phkResult);

    return ErrorCode;
}

/* Same as RegOpenKeyExW, but for HKEY_CLASSES_ROOT subkeys */
LONG
WINAPI
OpenHKCRKey(
    _In_ HKEY hKey,
    _In_ LPCWSTR lpSubKey,
    _In_ DWORD ulOptions,
    _In_ REGSAM samDesired,
    _In_ PHKEY phkResult)
{
    HKEY QueriedKey;
    LONG ErrorCode;

    ASSERT(IsHKCRKey(hKey));

    /* Remove the HKCR flag while we're working */
    hKey = (HKEY)(((ULONG_PTR)hKey) & ~0x2);

    ErrorCode = GetPreferredHKCRKey(hKey, &QueriedKey);

    if (ErrorCode == ERROR_FILE_NOT_FOUND)
    {
        /* The key doesn't exist on HKCU side, no chance for a subkey */
        ErrorCode = RegOpenKeyExW(hKey, lpSubKey, ulOptions, samDesired, phkResult);
        if (ErrorCode == ERROR_SUCCESS)
            MakeHKCRKey(phkResult);
        return ErrorCode;
    }

    if (ErrorCode != ERROR_SUCCESS)
    {
        /* Somehow we failed for another reason (maybe deleted key or whatever) */
        return ErrorCode;
    }

    /* Try on the HKCU side */
    ErrorCode = RegOpenKeyExW(QueriedKey, lpSubKey, ulOptions, samDesired, phkResult);
    if (ErrorCode == ERROR_SUCCESS)
        MakeHKCRKey(phkResult);

    /* Close it if we must */
    if (QueriedKey != hKey)
    {
        RegCloseKey(QueriedKey);
    }

    /* Anything else than ERROR_FILE_NOT_FOUND means that we found it, even if it is with failures. */
    if (ErrorCode != ERROR_FILE_NOT_FOUND)
        return ErrorCode;

    /* If we're here, we must open from HKLM key. */
    ErrorCode = GetFallbackHKCRKey(hKey, &QueriedKey, FALSE);
    if (ErrorCode != ERROR_SUCCESS)
    {
        /* Maybe the key doesn't exist in the HKLM view */
        return ErrorCode;
    }

    ErrorCode = RegOpenKeyExW(QueriedKey, lpSubKey, ulOptions, samDesired, phkResult);
    if (ErrorCode == ERROR_SUCCESS)
        MakeHKCRKey(phkResult);

    /* Close it if we must */
    if (QueriedKey != hKey)
    {
        RegCloseKey(QueriedKey);
    }

    return ErrorCode;
}

/* HKCR version of RegDeleteKeyExW */
LONG
WINAPI
DeleteHKCRKey(
    _In_ HKEY hKey,
    _In_ LPCWSTR lpSubKey,
    _In_ REGSAM RegSam,
    _In_ DWORD Reserved)
{
    HKEY QueriedKey;
    LONG ErrorCode;

    ASSERT(IsHKCRKey(hKey));

    /* Remove the HKCR flag while we're working */
    hKey = (HKEY)(((ULONG_PTR)hKey) & ~0x2);

    ErrorCode = GetPreferredHKCRKey(hKey, &QueriedKey);

    if (ErrorCode == ERROR_FILE_NOT_FOUND)
    {
        /* The key doesn't exist on HKCU side, no chance for a subkey */
        return RegDeleteKeyExW(hKey, lpSubKey, RegSam, Reserved);
    }

    if (ErrorCode != ERROR_SUCCESS)
    {
        /* Somehow we failed for another reason (maybe deleted key or whatever) */
        return ErrorCode;
    }

    ErrorCode = RegDeleteKeyExW(QueriedKey, lpSubKey, RegSam, Reserved);

    /* Close it if we must */
    if (QueriedKey != hKey)
    {
        /* The original key is on the machine view */
        RegCloseKey(QueriedKey);
    }

    /* Anything else than ERROR_FILE_NOT_FOUND means that we found it, even if it is with failures. */
    if (ErrorCode != ERROR_FILE_NOT_FOUND)
        return ErrorCode;

    /* If we're here, we must open from HKLM key. */
    ErrorCode = GetFallbackHKCRKey(hKey, &QueriedKey, FALSE);
    if (ErrorCode != ERROR_SUCCESS)
    {
        /* Maybe the key doesn't exist in the HKLM view */
        return ErrorCode;
    }

    ErrorCode = RegDeleteKeyExW(QueriedKey, lpSubKey, RegSam, Reserved);

    /* Close it if we must */
    if (QueriedKey != hKey)
    {
        RegCloseKey(QueriedKey);
    }

    return ErrorCode;
}

/* HKCR version of RegQueryValueExW */
LONG
WINAPI
QueryHKCRValue(
    _In_ HKEY hKey,
    _In_ LPCWSTR Name,
    _In_ LPDWORD Reserved,
    _In_ LPDWORD Type,
    _In_ LPBYTE Data,
    _In_ LPDWORD Count)
{
    HKEY QueriedKey;
    LONG ErrorCode;

    ASSERT(IsHKCRKey(hKey));

    /* Remove the HKCR flag while we're working */
    hKey = (HKEY)(((ULONG_PTR)hKey) & ~0x2);

    ErrorCode = GetPreferredHKCRKey(hKey, &QueriedKey);

    if (ErrorCode == ERROR_FILE_NOT_FOUND)
    {
        /* The key doesn't exist on HKCU side, no chance for a value in it */
        return RegQueryValueExW(hKey, Name, Reserved, Type, Data, Count);
    }

    if (ErrorCode != ERROR_SUCCESS)
    {
        /* Somehow we failed for another reason (maybe deleted key or whatever) */
        return ErrorCode;
    }

    ErrorCode = RegQueryValueExW(QueriedKey, Name, Reserved, Type, Data, Count);

    /* Close it if we must */
    if (QueriedKey != hKey)
    {
        /* The original key is on the machine view */
        RegCloseKey(QueriedKey);
    }

    /* Anything else than ERROR_FILE_NOT_FOUND means that we found it, even if it is with failures. */
    if (ErrorCode != ERROR_FILE_NOT_FOUND)
        return ErrorCode;

    /* If we're here, we must open from HKLM key. */
    ErrorCode = GetFallbackHKCRKey(hKey, &QueriedKey, FALSE);
    if (ErrorCode != ERROR_SUCCESS)
    {
        /* Maybe the key doesn't exist in the HKLM view */
        return ErrorCode;
    }

    ErrorCode = RegQueryValueExW(QueriedKey, Name, Reserved, Type, Data, Count);

    /* Close it if we must */
    if (QueriedKey != hKey)
    {
        RegCloseKey(QueriedKey);
    }

    return ErrorCode;
}

/* HKCR version of RegSetValueExW */
LONG
WINAPI
SetHKCRValue(
    _In_ HKEY hKey,
    _In_ LPCWSTR Name,
    _In_ DWORD Reserved,
    _In_ DWORD Type,
    _In_ CONST BYTE* Data,
    _In_ DWORD DataSize)
{
    HKEY QueriedKey;
    LONG ErrorCode;

    ASSERT(IsHKCRKey(hKey));

    /* Remove the HKCR flag while we're working */
    hKey = (HKEY)(((ULONG_PTR)hKey) & ~0x2);

    ErrorCode = GetPreferredHKCRKey(hKey, &QueriedKey);

    if (ErrorCode == ERROR_FILE_NOT_FOUND)
    {
        /* The key doesn't exist on HKCU side, no chance to put a value in it */
        return RegSetValueExW(hKey, Name, Reserved, Type, Data, DataSize);
    }

    if (ErrorCode != ERROR_SUCCESS)
    {
        /* Somehow we failed for another reason (maybe deleted key or whatever) */
        return ErrorCode;
    }

    /* Check if the value already exists in the preferred key */
    ErrorCode = RegQueryValueExW(QueriedKey, Name, NULL, NULL, NULL, NULL);
    if (ErrorCode != ERROR_FILE_NOT_FOUND)
    {
        if (ErrorCode == ERROR_SUCCESS)
        {
            /* Yes, so we have the right to modify it */
            ErrorCode = RegSetValueExW(QueriedKey, Name, Reserved, Type, Data, DataSize);
        }
        if (QueriedKey != hKey)
            RegCloseKey(QueriedKey);
        return ErrorCode;
    }
    if (QueriedKey != hKey)
        RegCloseKey(QueriedKey);

    /* So we must set the value in the HKLM version */
    ErrorCode = GetPreferredHKCRKey(hKey, &QueriedKey);
    if (ErrorCode == ERROR_FILE_NOT_FOUND)
    {
        /* No choice: put this in HKCU */
        return RegSetValueExW(hKey, Name, Reserved, Type, Data, DataSize);
    }
    else if (ErrorCode != ERROR_SUCCESS)
    {
        return ErrorCode;
    }

    ErrorCode = RegSetValueExW(QueriedKey, Name, Reserved, Type, Data, DataSize);

    if (QueriedKey != hKey)
        RegCloseKey(QueriedKey);

    return ErrorCode;
}

/* HKCR version of RegEnumKeyExW */
LONG
WINAPI
EnumHKCRKey(
    _In_ HKEY hKey,
    _In_ DWORD dwIndex,
    _Out_ LPWSTR lpName,
    _Inout_ LPDWORD lpcbName,
    _Reserved_ LPDWORD lpReserved,
    _Out_opt_ LPWSTR lpClass,
    _Inout_opt_ LPDWORD lpcbClass,
    _Out_opt_ PFILETIME lpftLastWriteTime)
{
    HKEY PreferredKey, FallbackKey;
    DWORD NumPreferredSubKeys;
    DWORD MaxFallbackSubKeyLen;
    DWORD FallbackIndex;
    WCHAR* FallbackSubKeyName = NULL;
    LONG ErrorCode;

    ASSERT(IsHKCRKey(hKey));

    /* Remove the HKCR flag while we're working */
    hKey = (HKEY)(((ULONG_PTR)hKey) & ~0x2);

    /* Get the preferred key */
    ErrorCode = GetPreferredHKCRKey(hKey, &PreferredKey);
    if (ErrorCode != ERROR_SUCCESS)
    {
        if (ErrorCode == ERROR_FILE_NOT_FOUND)
        {
            /* Only the HKLM key exists */
            return RegEnumKeyExW(
                hKey,
                dwIndex,
                lpName,
                lpcbName,
                lpReserved,
                lpClass,
                lpcbClass,
                lpftLastWriteTime);
        }
        return ErrorCode;
    }

    /* Get the fallback key */
    ErrorCode = GetFallbackHKCRKey(hKey, &FallbackKey, FALSE);
    if (ErrorCode != ERROR_SUCCESS)
    {
        if (PreferredKey != hKey)
            RegCloseKey(PreferredKey);
        if (ErrorCode == ERROR_FILE_NOT_FOUND)
        {
            /* Only the HKCU key exists */
            return RegEnumKeyExW(
                hKey,
                dwIndex,
                lpName,
                lpcbName,
                lpReserved,
                lpClass,
                lpcbClass,
                lpftLastWriteTime);
        }
        return ErrorCode;
    }

    /* Get some info on the HKCU side */
    ErrorCode = RegQueryInfoKeyW(
        PreferredKey,
        NULL,
        NULL,
        NULL,
        &NumPreferredSubKeys,
        NULL,
        NULL,
        NULL,
        NULL,
        NULL,
        NULL,
        NULL);
    if (ErrorCode != ERROR_SUCCESS)
        goto Exit;

    if (dwIndex < NumPreferredSubKeys)
    {
        /* HKCU side takes precedence */
        ErrorCode = RegEnumKeyExW(
            PreferredKey,
            dwIndex,
            lpName,
            lpcbName,
            lpReserved,
            lpClass,
            lpcbClass,
            lpftLastWriteTime);
        goto Exit;
    }

    /* Here it gets tricky. We must enumerate the values from the HKLM side,
     * without reporting those which are present on the HKCU side */

    /* Squash out the indices from HKCU */
    dwIndex -= NumPreferredSubKeys;

    /* Get some info */
    ErrorCode = RegQueryInfoKeyW(
        FallbackKey,
        NULL,
        NULL,
        NULL,
        NULL,
        &MaxFallbackSubKeyLen,
        NULL,
        NULL,
        NULL,
        NULL,
        NULL,
        NULL);
    if (ErrorCode != ERROR_SUCCESS)
    {
        ERR("Could not query info of key %p (Err: %d)\n", FallbackKey, ErrorCode);
        goto Exit;
    }

    MaxFallbackSubKeyLen++;
    TRACE("Maxfallbacksubkeylen: %d\n", MaxFallbackSubKeyLen);

    /* Allocate our buffer */
    FallbackSubKeyName = RtlAllocateHeap(
        RtlGetProcessHeap(), 0, MaxFallbackSubKeyLen * sizeof(WCHAR));
    if (!FallbackSubKeyName)
    {
        ErrorCode = ERROR_NOT_ENOUGH_MEMORY;
        goto Exit;
    }

    /* We must begin at the very first subkey of the fallback key,
     * and then see if we meet keys that already are in the preferred key.
     * In that case, we must bump dwIndex, as otherwise we would enumerate a key we already
     * saw in a previous call.
     */
    FallbackIndex = 0;
    while (TRUE)
    {
        HKEY PreferredSubKey;
        DWORD FallbackSubkeyLen = MaxFallbackSubKeyLen;

        /* Try enumerating */
        ErrorCode = RegEnumKeyExW(
            FallbackKey,
            FallbackIndex,
            FallbackSubKeyName,
            &FallbackSubkeyLen,
            NULL,
            NULL,
            NULL,
            NULL);
        if (ErrorCode != ERROR_SUCCESS)
        {
            if (ErrorCode != ERROR_NO_MORE_ITEMS)
                ERR("Returning %d.\n", ErrorCode);
            goto Exit;
        }
        FallbackSubKeyName[FallbackSubkeyLen] = L'\0';

        /* See if there is such a value on HKCU side */
        ErrorCode = RegOpenKeyExW(
            PreferredKey,
            FallbackSubKeyName,
            0,
            READ_CONTROL,
            &PreferredSubKey);

        if (ErrorCode == ERROR_SUCCESS)
        {
            RegCloseKey(PreferredSubKey);
            /* So we already enumerated it on HKCU side. */
            dwIndex++;
        }
        else if (ErrorCode != ERROR_FILE_NOT_FOUND)
        {
            ERR("Got error %d while querying for %s on HKCU side.\n", ErrorCode, FallbackSubKeyName);
            goto Exit;
        }

        /* See if we caught up */
        if (FallbackIndex == dwIndex)
            break;

        FallbackIndex++;
    }

    /* We can finally enumerate on the fallback side */
    ErrorCode = RegEnumKeyExW(
        FallbackKey,
        dwIndex,
        lpName,
        lpcbName,
        lpReserved,
        lpClass,
        lpcbClass,
        lpftLastWriteTime);

Exit:
    if (PreferredKey != hKey)
        RegCloseKey(PreferredKey);
    if (FallbackKey != hKey)
        RegCloseKey(FallbackKey);
    if (FallbackSubKeyName)
        RtlFreeHeap(RtlGetProcessHeap(), 0, FallbackSubKeyName);

    return ErrorCode;
}

/* HKCR version of RegEnumValueW */
LONG
WINAPI
EnumHKCRValue(
    _In_ HKEY hKey,
    _In_ DWORD dwIndex,
    _Out_ LPWSTR lpName,
    _Inout_ PDWORD lpcbName,
    _Reserved_ PDWORD lpReserved,
    _Out_opt_ PDWORD lpdwType,
    _Out_opt_ LPBYTE lpData,
    _Inout_opt_ PDWORD lpcbData)
{
    HKEY PreferredKey, FallbackKey;
    DWORD NumPreferredValues;
    DWORD MaxFallbackValueNameLen;
    DWORD FallbackIndex;
    WCHAR* FallbackValueName = NULL;
    LONG ErrorCode;

    ASSERT(IsHKCRKey(hKey));

    /* Remove the HKCR flag while we're working */
    hKey = (HKEY)(((ULONG_PTR)hKey) & ~0x2);

    /* Get the preferred key */
    ErrorCode = GetPreferredHKCRKey(hKey, &PreferredKey);
    if (ErrorCode != ERROR_SUCCESS)
    {
        if (ErrorCode == ERROR_FILE_NOT_FOUND)
        {
            /* Only the HKLM key exists */
            return RegEnumValueW(
                hKey,
                dwIndex,
                lpName,
                lpcbName,
                lpReserved,
                lpdwType,
                lpData,
                lpcbData);
        }
        return ErrorCode;
    }

    /* Get the fallback key */
    ErrorCode = GetFallbackHKCRKey(hKey, &FallbackKey, FALSE);
    if (ErrorCode != ERROR_SUCCESS)
    {
        if (PreferredKey != hKey)
            RegCloseKey(PreferredKey);
        if (ErrorCode == ERROR_FILE_NOT_FOUND)
        {
            /* Only the HKCU key exists */
            return RegEnumValueW(
                hKey,
                dwIndex,
                lpName,
                lpcbName,
                lpReserved,
                lpdwType,
                lpData,
                lpcbData);
        }
        return ErrorCode;
    }

    /* Get some info on the HKCU side */
    ErrorCode = RegQueryInfoKeyW(
        PreferredKey,
        NULL,
        NULL,
        NULL,
        NULL,
        NULL,
        NULL,
        &NumPreferredValues,
        NULL,
        NULL,
        NULL,
        NULL);
    if (ErrorCode != ERROR_SUCCESS)
        goto Exit;

    if (dwIndex < NumPreferredValues)
    {
        /* HKCU side takes precedence */
        return RegEnumValueW(
            PreferredKey,
            dwIndex,
            lpName,
            lpcbName,
            lpReserved,
            lpdwType,
            lpData,
            lpcbData);
        goto Exit;
    }

    /* Here it gets tricky. We must enumerate the values from the HKLM side,
     * without reporting those which are present on the HKCU side */

    /* Squash out the indices from HKCU */
    dwIndex -= NumPreferredValues;

    /* Get some info */
    ErrorCode = RegQueryInfoKeyW(
        FallbackKey,
        NULL,
        NULL,
        NULL,
        NULL,
        NULL,
        NULL,
        NULL,
        &MaxFallbackValueNameLen,
        NULL,
        NULL,
        NULL);
    if (ErrorCode != ERROR_SUCCESS)
    {
        ERR("Could not query info of key %p (Err: %d)\n", FallbackKey, ErrorCode);
        goto Exit;
    }

    MaxFallbackValueNameLen++;
    TRACE("Maxfallbacksubkeylen: %d\n", MaxFallbackValueNameLen);

    /* Allocate our buffer */
    FallbackValueName = RtlAllocateHeap(
        RtlGetProcessHeap(), 0, MaxFallbackValueNameLen * sizeof(WCHAR));
    if (!FallbackValueName)
    {
        ErrorCode = ERROR_NOT_ENOUGH_MEMORY;
        goto Exit;
    }

    /* We must begin at the very first subkey of the fallback key,
     * and then see if we meet keys that already are in the preferred key.
     * In that case, we must bump dwIndex, as otherwise we would enumerate a key we already
     * saw in a previous call.
     */
    FallbackIndex = 0;
    while (TRUE)
    {
        DWORD FallbackValueNameLen = MaxFallbackValueNameLen;

        /* Try enumerating */
        ErrorCode = RegEnumValueW(
            FallbackKey,
            FallbackIndex,
            FallbackValueName,
            &FallbackValueNameLen,
            NULL,
            NULL,
            NULL,
            NULL);
        if (ErrorCode != ERROR_SUCCESS)
        {
            if (ErrorCode != ERROR_NO_MORE_ITEMS)
                ERR("Returning %d.\n", ErrorCode);
            goto Exit;
        }
        FallbackValueName[FallbackValueNameLen] = L'\0';

        /* See if there is such a value on HKCU side */
        ErrorCode = RegQueryValueExW(
            PreferredKey,
            FallbackValueName,
            NULL,
            NULL,
            NULL,
            NULL);

        if (ErrorCode == ERROR_SUCCESS)
        {
            /* So we already enumerated it on HKCU side. */
            dwIndex++;
        }
        else if (ErrorCode != ERROR_FILE_NOT_FOUND)
        {
            ERR("Got error %d while querying for %s on HKCU side.\n", ErrorCode, FallbackValueName);
            goto Exit;
        }

        /* See if we caught up */
        if (FallbackIndex == dwIndex)
            break;

        FallbackIndex++;
    }

    /* We can finally enumerate on the fallback side */
    ErrorCode = RegEnumValueW(
        FallbackKey,
        dwIndex,
        lpName,
        lpcbName,
        lpReserved,
        lpdwType,
        lpData,
        lpcbData);

Exit:
    if (PreferredKey != hKey)
        RegCloseKey(PreferredKey);
    if (FallbackKey != hKey)
        RegCloseKey(FallbackKey);
    if (FallbackValueName)
        RtlFreeHeap(RtlGetProcessHeap(), 0, FallbackValueName);

    return ErrorCode;
}