implemented RegDeleteTree() (untested!)
[reactos.git] / reactos / lib / advapi32 / reg / reg.c
index 0f495f4..98a46ef 100644 (file)
@@ -13,9 +13,9 @@
 
 /* INCLUDES *****************************************************************/
 
-#include "advapi32.h"
+#include <advapi32.h>
 #define NDEBUG
-#include <debug.h>
+#include <wine/debug.h>
 
 /* DEFINES ******************************************************************/
 
 static RTL_CRITICAL_SECTION HandleTableCS;
 static HANDLE DefaultHandleTable[MAX_DEFAULT_HANDLES];
 static HANDLE ProcessHeap;
+static BOOLEAN DefaultHandlesDisabled = FALSE;
 
 /* PROTOTYPES ***************************************************************/
 
 static NTSTATUS MapDefaultKey (PHANDLE ParentKey, HKEY Key);
 static VOID CloseDefaultKeys(VOID);
+#define CloseDefaultKey(Handle)                                                \
+    if ((ULONG_PTR)Handle & 0x1) {                                             \
+        NtClose(Handle);                                                       \
+    }
 
 static NTSTATUS OpenClassesRootKey(PHANDLE KeyHandle);
 static NTSTATUS OpenLocalMachineKey (PHANDLE KeyHandle);
@@ -56,7 +61,7 @@ inline static int is_string( DWORD type )
 BOOL
 RegInitialize (VOID)
 {
-  DPRINT("RegInitialize()\n");
+  TRACE("RegInitialize()\n");
 
   ProcessHeap = RtlGetProcessHeap();
   RtlZeroMemory (DefaultHandleTable,
@@ -73,7 +78,7 @@ RegInitialize (VOID)
 BOOL
 RegCleanup (VOID)
 {
-  DPRINT("RegCleanup()\n");
+  TRACE("RegCleanup()\n");
 
   CloseDefaultKeys ();
   RtlDeleteCriticalSection (&HandleTableCS);
@@ -83,18 +88,19 @@ RegCleanup (VOID)
 
 
 static NTSTATUS
-MapDefaultKey (PHANDLE RealKey,
-              HKEY Key)
+MapDefaultKey (OUT PHANDLE RealKey,
+               IN HKEY Key)
 {
   PHANDLE Handle;
   ULONG Index;
+  BOOLEAN DoOpen;
   NTSTATUS Status = STATUS_SUCCESS;
 
-  DPRINT("MapDefaultKey (Key %x)\n", Key);
+  TRACE("MapDefaultKey (Key %x)\n", Key);
 
   if (((ULONG)Key & 0xF0000000) != 0x80000000)
     {
-      *RealKey = (HANDLE)Key;
+      *RealKey = (HANDLE)((ULONG_PTR)Key & ~0x1);
       return STATUS_SUCCESS;
     }
 
@@ -106,8 +112,19 @@ MapDefaultKey (PHANDLE RealKey,
     }
 
   RtlEnterCriticalSection (&HandleTableCS);
-  Handle = &DefaultHandleTable[Index];
-  if (*Handle == NULL)
+  
+  if (!DefaultHandlesDisabled)
+    {
+      Handle = &DefaultHandleTable[Index];
+      DoOpen = (*Handle == NULL);
+    }
+  else
+    {
+      Handle = RealKey;
+      DoOpen = TRUE;
+    }
+  
+  if (DoOpen)
     {
       /* create/open the default handle */
       switch (Index)
@@ -142,16 +159,21 @@ MapDefaultKey (PHANDLE RealKey,
            break;
 
          default:
-           DPRINT("MapDefaultHandle() no handle creator\n");
+           WARN("MapDefaultHandle() no handle creator\n");
            Status = STATUS_INVALID_PARAMETER;
+           break;
        }
     }
-  RtlLeaveCriticalSection (&HandleTableCS);
 
-  if (NT_SUCCESS(Status))
-    {
-      *RealKey = *Handle;
-    }
+   if (NT_SUCCESS(Status))
+     {
+       if (!DefaultHandlesDisabled)
+          *RealKey = *Handle;
+       else
+          *(PULONG_PTR)Handle |= 0x1;
+     }
+  
+   RtlLeaveCriticalSection (&HandleTableCS);
 
    return Status;
 }
@@ -179,9 +201,9 @@ static NTSTATUS
 OpenClassesRootKey (PHANDLE KeyHandle)
 {
   OBJECT_ATTRIBUTES Attributes;
-  UNICODE_STRING KeyName = ROS_STRING_INITIALIZER(L"\\Registry\\Machine\\Software\\CLASSES");
+  UNICODE_STRING KeyName = RTL_CONSTANT_STRING(L"\\Registry\\Machine\\Software\\CLASSES");
 
-  DPRINT("OpenClassesRootKey()\n");
+  TRACE("OpenClassesRootKey()\n");
 
   InitializeObjectAttributes (&Attributes,
                              &KeyName,
@@ -198,10 +220,10 @@ static NTSTATUS
 OpenLocalMachineKey (PHANDLE KeyHandle)
 {
   OBJECT_ATTRIBUTES Attributes;
-  UNICODE_STRING KeyName = ROS_STRING_INITIALIZER(L"\\Registry\\Machine");
+  UNICODE_STRING KeyName = RTL_CONSTANT_STRING(L"\\Registry\\Machine");
   NTSTATUS Status;
 
-  DPRINT("OpenLocalMachineKey()\n");
+  TRACE("OpenLocalMachineKey()\n");
 
   InitializeObjectAttributes (&Attributes,
                              &KeyName,
@@ -212,7 +234,7 @@ OpenLocalMachineKey (PHANDLE KeyHandle)
                      MAXIMUM_ALLOWED,
                      &Attributes);
 
-  DPRINT("NtOpenKey(%wZ) => %08x\n", &KeyName, Status);
+  TRACE("NtOpenKey(%wZ) => %08x\n", &KeyName, Status);
   return Status;
 }
 
@@ -221,9 +243,9 @@ static NTSTATUS
 OpenUsersKey (PHANDLE KeyHandle)
 {
   OBJECT_ATTRIBUTES Attributes;
-  UNICODE_STRING KeyName = ROS_STRING_INITIALIZER(L"\\Registry\\User");
+  UNICODE_STRING KeyName = RTL_CONSTANT_STRING(L"\\Registry\\User");
 
-  DPRINT("OpenUsersKey()\n");
+  TRACE("OpenUsersKey()\n");
 
   InitializeObjectAttributes (&Attributes,
                              &KeyName,
@@ -241,9 +263,9 @@ OpenCurrentConfigKey (PHANDLE KeyHandle)
 {
   OBJECT_ATTRIBUTES Attributes;
   UNICODE_STRING KeyName =
-  ROS_STRING_INITIALIZER(L"\\Registry\\Machine\\System\\CurrentControlSet\\Hardware Profiles\\Current");
+  RTL_CONSTANT_STRING(L"\\Registry\\Machine\\System\\CurrentControlSet\\Hardware Profiles\\Current");
 
-  DPRINT("OpenCurrentConfigKey()\n");
+  TRACE("OpenCurrentConfigKey()\n");
 
   InitializeObjectAttributes (&Attributes,
                              &KeyName,
@@ -256,6 +278,21 @@ OpenCurrentConfigKey (PHANDLE KeyHandle)
 }
 
 
+/************************************************************************
+ *  RegDisablePredefinedCacheEx
+ *
+ * @implemented
+ */
+LONG STDCALL
+RegDisablePredefinedCacheEx(VOID)
+{
+    RtlEnterCriticalSection (&HandleTableCS);
+    DefaultHandlesDisabled = TRUE;
+    RtlLeaveCriticalSection (&HandleTableCS);
+    return ERROR_SUCCESS;
+}
+
+
 /************************************************************************
  *  RegCloseKey
  *
@@ -297,6 +334,117 @@ RegConnectRegistryA (LPCSTR lpMachineName,
 }
 
 
+/************************************************************************
+ *  RegCopyTreeW
+ *
+ * @unimplemented
+ */
+LONG STDCALL
+RegCopyTreeW(IN HKEY hKeySrc,
+             IN LPCWSTR lpSubKey  OPTIONAL,
+             IN HKEY hKeyDest)
+{
+    HANDLE DestKeyHandle, KeyHandle, CurKey, SubKeyHandle = NULL;
+    NTSTATUS Status;
+    
+    Status = MapDefaultKey(&KeyHandle,
+                           hKeySrc);
+    if (!NT_SUCCESS(Status))
+    {
+        return RtlNtStatusToDosError(Status);
+    }
+    
+    Status = MapDefaultKey(&DestKeyHandle,
+                           hKeyDest);
+    if (!NT_SUCCESS(Status))
+    {
+        goto Cleanup2;
+    }
+
+    if (lpSubKey != NULL)
+    {
+        OBJECT_ATTRIBUTES ObjectAttributes;
+        UNICODE_STRING SubKeyName;
+
+        RtlInitUnicodeString(&SubKeyName,
+                             (LPWSTR)lpSubKey);
+
+        InitializeObjectAttributes(&ObjectAttributes,
+                                   &SubKeyName,
+                                   OBJ_CASE_INSENSITIVE,
+                                   KeyHandle,
+                                   NULL);
+
+        Status = NtOpenKey(&SubKeyHandle,
+                           KEY_READ,
+                           &ObjectAttributes);
+        if (!NT_SUCCESS(Status))
+        {
+            goto Cleanup;
+        }
+        
+        CurKey = SubKeyHandle;
+    }
+    else
+        CurKey = KeyHandle;
+    
+    /* FIXME - copy all keys and values recursively */
+    Status = STATUS_NOT_IMPLEMENTED;
+    
+    if (SubKeyHandle != NULL)
+    {
+        NtClose(SubKeyHandle);
+    }
+    
+Cleanup:
+    CloseDefaultKey(DestKeyHandle);
+Cleanup2:
+    CloseDefaultKey(KeyHandle);
+    
+    if (!NT_SUCCESS(Status))
+    {
+        return RtlNtStatusToDosError(Status);
+    }
+    
+    return ERROR_SUCCESS;
+}
+
+
+/************************************************************************
+ *  RegCopyTreeA
+ *
+ * @implemented
+ */
+LONG STDCALL
+RegCopyTreeA(IN HKEY hKeySrc,
+             IN LPCSTR lpSubKey  OPTIONAL,
+             IN HKEY hKeyDest)
+{
+    UNICODE_STRING SubKeyName;
+    LONG Ret;
+    
+    if (lpSubKey != NULL)
+    {
+        if (!RtlCreateUnicodeStringFromAsciiz(&SubKeyName,
+                                              (LPSTR)lpSubKey))
+        {
+            return ERROR_NOT_ENOUGH_MEMORY;
+        }
+    }
+    else
+        RtlInitUnicodeString(&SubKeyName,
+                             NULL);
+
+    Ret = RegCopyTreeW(hKeySrc,
+                       SubKeyName.Buffer,
+                       hKeyDest);
+
+    RtlFreeUnicodeString(&SubKeyName);
+    
+    return Ret;
+}
+
+
 /************************************************************************
  *  RegConnectRegistryW
  *
@@ -341,7 +489,7 @@ CreateNestedKey(PHKEY KeyHandle,
                        ClassString,
                        dwOptions,
                        (PULONG)lpdwDisposition);
-  DPRINT("NtCreateKey(%wZ) called (Status %lx)\n", ObjectAttributes->ObjectName, Status);
+  TRACE("NtCreateKey(%wZ) called (Status %lx)\n", ObjectAttributes->ObjectName, Status);
   if (Status != STATUS_OBJECT_NAME_NOT_FOUND)
     return Status;
 
@@ -373,7 +521,7 @@ CreateNestedKey(PHKEY KeyHandle,
                            NULL,
                            0,
                            &Disposition);
-      DPRINT("NtCreateKey(%wZ) called (Status %lx)\n", &LocalKeyName, Status);
+      TRACE("NtCreateKey(%wZ) called (Status %lx)\n", &LocalKeyName, Status);
     }
 
   if (!NT_SUCCESS(Status))
@@ -410,7 +558,7 @@ CreateNestedKey(PHKEY KeyHandle,
                            NULL,
                            0,
                            &Disposition);
-      DPRINT("NtCreateKey(%wZ) called (Status %lx)\n", &LocalKeyName, Status);
+      TRACE("NtCreateKey(%wZ) called (Status %lx)\n", &LocalKeyName, Status);
       if (!NT_SUCCESS(Status))
        break;
     }
@@ -443,16 +591,16 @@ RegCreateKeyExA (HKEY hKey,
   HANDLE ParentKey;
   NTSTATUS Status;
 
-  DPRINT("RegCreateKeyExA() called\n");
+  TRACE("RegCreateKeyExA() called\n");
 
   /* get the real parent key */
   Status = MapDefaultKey (&ParentKey,
-                         hKey);
+                          hKey);
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
     }
-  DPRINT("ParentKey %x\n", (ULONG)ParentKey);
+  TRACE("ParentKey %x\n", (ULONG)ParentKey);
 
   if (lpClass != NULL)
     {
@@ -479,7 +627,9 @@ RegCreateKeyExA (HKEY hKey,
       RtlFreeUnicodeString (&ClassString);
     }
 
-  DPRINT("Status %x\n", Status);
+  CloseDefaultKey(ParentKey);
+
+  TRACE("Status %x\n", Status);
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -511,16 +661,16 @@ RegCreateKeyExW (HKEY hKey,
   HANDLE ParentKey;
   NTSTATUS Status;
 
-  DPRINT("RegCreateKeyExW() called\n");
+  TRACE("RegCreateKeyExW() called\n");
 
   /* get the real parent key */
   Status = MapDefaultKey (&ParentKey,
-                         hKey);
+                          hKey);
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError(Status);
     }
-  DPRINT("ParentKey %x\n", (ULONG)ParentKey);
+  TRACE("ParentKey %x\n", (ULONG)ParentKey);
 
   RtlInitUnicodeString (&ClassString,
                        lpClass);
@@ -537,7 +687,10 @@ RegCreateKeyExW (HKEY hKey,
                            dwOptions,
                            samDesired,
                            lpdwDisposition);
-  DPRINT("Status %x\n", Status);
+
+  CloseDefaultKey(ParentKey);
+
+  TRACE("Status %x\n", Status);
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -607,7 +760,7 @@ RegDeleteKeyA (HKEY hKey,
   NTSTATUS Status;
 
   Status = MapDefaultKey (&ParentKey,
-                         hKey);
+                          hKey);
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -618,7 +771,7 @@ RegDeleteKeyA (HKEY hKey,
   InitializeObjectAttributes(&ObjectAttributes,
                             &SubKeyName,
                             OBJ_CASE_INSENSITIVE,
-                            (HANDLE)ParentKey,
+                            ParentKey,
                             NULL);
 
   Status = NtOpenKey (&TargetKey,
@@ -627,11 +780,15 @@ RegDeleteKeyA (HKEY hKey,
   RtlFreeUnicodeString (&SubKeyName);
   if (!NT_SUCCESS(Status))
     {
-      return RtlNtStatusToDosError (Status);
+      goto Cleanup;
     }
 
   Status = NtDeleteKey (TargetKey);
   NtClose (TargetKey);
+  
+Cleanup:
+  CloseDefaultKey(ParentKey);
+
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError(Status);
@@ -657,7 +814,7 @@ RegDeleteKeyW (HKEY hKey,
   NTSTATUS Status;
 
   Status = MapDefaultKey (&ParentKey,
-                         hKey);
+                          hKey);
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -668,18 +825,22 @@ RegDeleteKeyW (HKEY hKey,
   InitializeObjectAttributes (&ObjectAttributes,
                              &SubKeyName,
                              OBJ_CASE_INSENSITIVE,
-                             (HANDLE)ParentKey,
+                             ParentKey,
                              NULL);
   Status = NtOpenKey (&TargetKey,
                      DELETE,
                      &ObjectAttributes);
   if (!NT_SUCCESS(Status))
     {
-      return RtlNtStatusToDosError (Status);
+      goto Cleanup;
     }
 
   Status = NtDeleteKey (TargetKey);
   NtClose (TargetKey);
+  
+Cleanup:
+  CloseDefaultKey(ParentKey);
+
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -689,6 +850,545 @@ RegDeleteKeyW (HKEY hKey,
 }
 
 
+/************************************************************************
+ *  RegDeleteKeyValueW
+ *
+ * @implemented
+ */
+LONG STDCALL
+RegDeleteKeyValueW(IN HKEY hKey,
+                   IN LPCWSTR lpSubKey  OPTIONAL,
+                   IN LPCWSTR lpValueName  OPTIONAL)
+{
+    UNICODE_STRING ValueName;
+    HANDLE KeyHandle, CurKey, SubKeyHandle = NULL;
+    NTSTATUS Status;
+
+    Status = MapDefaultKey(&KeyHandle,
+                           hKey);
+    if (!NT_SUCCESS(Status))
+    {
+        return RtlNtStatusToDosError(Status);
+    }
+
+    if (lpSubKey != NULL)
+    {
+        OBJECT_ATTRIBUTES ObjectAttributes;
+        UNICODE_STRING SubKeyName;
+
+        RtlInitUnicodeString(&SubKeyName,
+                             (LPWSTR)lpSubKey);
+
+        InitializeObjectAttributes(&ObjectAttributes,
+                                   &SubKeyName,
+                                   OBJ_CASE_INSENSITIVE,
+                                   KeyHandle,
+                                   NULL);
+
+        Status = NtOpenKey(&SubKeyHandle,
+                           KEY_SET_VALUE,
+                           &ObjectAttributes);
+        if (!NT_SUCCESS(Status))
+        {
+            goto Cleanup;
+        }
+        
+        CurKey = SubKeyHandle;
+    }
+    else
+        CurKey = KeyHandle;
+
+    RtlInitUnicodeString(&ValueName,
+                         (LPWSTR)lpValueName);
+
+    Status = NtDeleteValueKey(CurKey,
+                              &ValueName);
+
+    if (SubKeyHandle != NULL)
+    {
+        NtClose(SubKeyHandle);
+    }
+    
+Cleanup:
+    CloseDefaultKey(KeyHandle);
+
+    if (!NT_SUCCESS(Status))
+    {
+        return RtlNtStatusToDosError(Status);
+    }
+
+    return ERROR_SUCCESS;
+}
+
+
+/************************************************************************
+ *  RegDeleteKeyValueA
+ *
+ * @implemented
+ */
+LONG STDCALL
+RegDeleteKeyValueA(IN HKEY hKey,
+                   IN LPCSTR lpSubKey  OPTIONAL,
+                   IN LPCSTR lpValueName  OPTIONAL)
+{
+    UNICODE_STRING SubKey, ValueName;
+    LONG Ret;
+    
+    if (lpSubKey != NULL)
+    {
+        if (!RtlCreateUnicodeStringFromAsciiz(&SubKey,
+                                              (LPSTR)lpSubKey))
+        {
+            return ERROR_NOT_ENOUGH_MEMORY;
+        }
+    }
+    else
+        RtlInitUnicodeString(&SubKey,
+                             NULL);
+
+    if (lpValueName != NULL)
+    {
+        if (!RtlCreateUnicodeStringFromAsciiz(&ValueName,
+                                              (LPSTR)lpValueName))
+        {
+            RtlFreeUnicodeString(&SubKey);
+            return ERROR_NOT_ENOUGH_MEMORY;
+        }
+    }
+    else
+        RtlInitUnicodeString(&ValueName,
+                             NULL);
+
+    Ret = RegDeleteKeyValueW(hKey,
+                             SubKey.Buffer,
+                             SubKey.Buffer);
+
+    RtlFreeUnicodeString(&SubKey);
+    RtlFreeUnicodeString(&ValueName);
+    
+    return Ret;
+}
+
+
+static NTSTATUS
+RegpDeleteTree(IN HKEY hKey)
+{
+    typedef struct
+    {
+        LIST_ENTRY ListEntry;
+        HANDLE KeyHandle;
+    } REGP_DEL_KEYS, *PREG_DEL_KEYS;
+
+    LIST_ENTRY delQueueHead;
+    PREG_DEL_KEYS delKeys = NULL, newDelKeys;
+    HANDLE ProcessHeap;
+    ULONG BufferSize;
+    PKEY_BASIC_INFORMATION BasicInfo;
+    PREG_DEL_KEYS KeyDelRoot;
+    NTSTATUS Status = STATUS_SUCCESS;
+    NTSTATUS Status2 = STATUS_SUCCESS;
+    
+    InitializeListHead(&delQueueHead);
+    
+    ProcessHeap = RtlGetProcessHeap();
+    
+    /* NOTE: no need to allocate enough memory for an additional KEY_BASIC_INFORMATION
+             structure for the root key, we only do that for subkeys as we need to
+             allocate REGP_DEL_KEYS structures anyway! */
+    KeyDelRoot = RtlAllocateHeap(ProcessHeap,
+                                 0,
+                                 sizeof(REGP_DEL_KEYS));
+    if (KeyDelRoot != NULL)
+    {
+        KeyDelRoot->KeyHandle = hKey;
+        InsertTailList(&delQueueHead,
+                       &KeyDelRoot->ListEntry);
+
+        do
+        {
+            delKeys = CONTAINING_RECORD(delQueueHead.Flink,
+                                        REGP_DEL_KEYS,
+                                        ListEntry);
+
+            BufferSize = 0;
+            BasicInfo = NULL;
+            newDelKeys = NULL;
+
+ReadFirstSubKey:
+            /* check if this key contains subkeys and delete them first by queuing
+               them at the head of the list */
+            Status2 = NtEnumerateKey(delKeys->KeyHandle,
+                                     0,
+                                     KeyBasicInformation,
+                                     BasicInfo,
+                                     BufferSize,
+                                     &BufferSize);
+
+            if (NT_SUCCESS(Status2))
+            {
+                OBJECT_ATTRIBUTES ObjectAttributes;
+                UNICODE_STRING SubKeyName;
+                
+                ASSERT(newDelKeys != NULL);
+                ASSERT(BasicInfo != NULL);
+
+                /* don't use RtlInitUnicodeString as the string is not NULL-terminated! */
+                SubKeyName.Length = BasicInfo->NameLength;
+                SubKeyName.MaximumLength = BasicInfo->NameLength;
+                SubKeyName.Buffer = BasicInfo->Name;
+
+                InitializeObjectAttributes(&ObjectAttributes,
+                                           &SubKeyName,
+                                           OBJ_CASE_INSENSITIVE,
+                                           delKeys->KeyHandle,
+                                           NULL);
+
+                /* open the subkey */
+                Status2 = NtOpenKey(&newDelKeys->KeyHandle,
+                                    DELETE | KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE,
+                                    &ObjectAttributes);
+                if (!NT_SUCCESS(Status2))
+                {
+                    goto SubKeyFailure;
+                }
+
+                /* enqueue this key to the head of the deletion queue */
+                InsertHeadList(&delQueueHead,
+                               &newDelKeys->ListEntry);
+
+                /* try again from the head of the list */
+                continue;
+            }
+            else
+            {
+                if (Status2 == STATUS_BUFFER_TOO_SMALL)
+                {
+                    newDelKeys = RtlAllocateHeap(ProcessHeap,
+                                                 0,
+                                                 BufferSize + sizeof(REGP_DEL_KEYS));
+                    if (newDelKeys != NULL)
+                    {
+                        BasicInfo = (PKEY_BASIC_INFORMATION)(newDelKeys + 1);
+
+                        /* try again */
+                        goto ReadFirstSubKey;
+                    }
+                    else
+                    {
+                        /* don't break, let's try to delete as many keys as possible */
+                        Status2 = STATUS_INSUFFICIENT_RESOURCES;
+                        goto SubKeyFailureNoFree;
+                    }
+                }
+                else if (Status2 == STATUS_BUFFER_OVERFLOW)
+                {
+                    PREG_DEL_KEYS newDelKeys2;
+
+                    ASSERT(newDelKeys != NULL);
+
+                    /* we need more memory to query the key name */
+                    newDelKeys2 = RtlReAllocateHeap(ProcessHeap,
+                                                    0,
+                                                    newDelKeys,
+                                                    BufferSize + sizeof(REGP_DEL_KEYS));
+                    if (newDelKeys2 != NULL)
+                    {
+                        newDelKeys = newDelKeys2;
+                        BasicInfo = (PKEY_BASIC_INFORMATION)(newDelKeys + 1);
+
+                        /* try again */
+                        goto ReadFirstSubKey;
+                    }
+                    else
+                    {
+                        /* don't break, let's try to delete as many keys as possible */
+                        Status2 = STATUS_INSUFFICIENT_RESOURCES;
+                    }
+                }
+SubKeyFailure:
+                RtlFreeHeap(ProcessHeap,
+                            0,
+                            newDelKeys);
+SubKeyFailureNoFree:
+                /* don't break, let's try to delete as many keys as possible */
+                if (Status2 != STATUS_NO_MORE_ENTRIES && NT_SUCCESS(Status))
+                {
+                    Status = Status2;
+                }
+            }
+
+            Status2 = NtDeleteKey(delKeys->KeyHandle);
+            
+            /* NOTE: do NOT close the handle anymore, it's invalid already! */
+
+            if (!NT_SUCCESS(Status2) && NT_SUCCESS(Status))
+            {
+                /* don't break, let's try to delete as many keys as possible */
+                Status = Status2;
+            }
+            
+            /* remove the entry from the list */
+            RemoveEntryList(&delKeys->ListEntry);
+
+            RtlFreeHeap(ProcessHeap,
+                        0,
+                        delKeys);
+        } while (!IsListEmpty(&delQueueHead));
+    }
+    else
+        Status = STATUS_INSUFFICIENT_RESOURCES;
+    
+    return Status;
+}
+
+
+/************************************************************************
+ *  RegDeleteTreeW
+ *
+ * @implemented
+ */
+LONG STDCALL
+RegDeleteTreeW(IN HKEY hKey,
+               IN LPCWSTR lpSubKey  OPTIONAL)
+{
+    HANDLE KeyHandle, CurKey, SubKeyHandle = NULL;
+    NTSTATUS Status;
+
+    Status = MapDefaultKey(&KeyHandle,
+                           hKey);
+    if (!NT_SUCCESS(Status))
+    {
+        return RtlNtStatusToDosError(Status);
+    }
+
+    if (lpSubKey != NULL)
+    {
+        OBJECT_ATTRIBUTES ObjectAttributes;
+        UNICODE_STRING SubKeyName;
+
+        RtlInitUnicodeString(&SubKeyName,
+                             (LPWSTR)lpSubKey);
+
+        InitializeObjectAttributes(&ObjectAttributes,
+                                   &SubKeyName,
+                                   OBJ_CASE_INSENSITIVE,
+                                   KeyHandle,
+                                   NULL);
+
+        Status = NtOpenKey(&SubKeyHandle,
+                           DELETE | KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE,
+                           &ObjectAttributes);
+        if (!NT_SUCCESS(Status))
+        {
+            goto Cleanup;
+        }
+        
+        CurKey = SubKeyHandle;
+    }
+    else
+        CurKey = KeyHandle;
+
+    Status = RegpDeleteTree(CurKey);
+
+    if (SubKeyHandle != NULL)
+    {
+        NtClose(SubKeyHandle);
+    }
+
+Cleanup:
+    CloseDefaultKey(KeyHandle);
+
+    if (!NT_SUCCESS(Status))
+    {
+        return RtlNtStatusToDosError(Status);
+    }
+
+    return ERROR_SUCCESS;
+}
+
+
+/************************************************************************
+ *  RegDeleteTreeA
+ *
+ * @implemented
+ */
+LONG STDCALL
+RegDeleteTreeA(IN HKEY hKey,
+               IN LPCSTR lpSubKey  OPTIONAL)
+{
+    UNICODE_STRING SubKeyName;
+    LONG Ret;
+
+    if (lpSubKey != NULL)
+    {
+        if (!RtlCreateUnicodeStringFromAsciiz(&SubKeyName,
+                                              (LPSTR)lpSubKey))
+        {
+            return ERROR_NOT_ENOUGH_MEMORY;
+        }
+    }
+    else
+        RtlInitUnicodeString(&SubKeyName,
+                             NULL);
+
+    Ret = RegDeleteTreeW(hKey,
+                         SubKeyName.Buffer);
+
+    RtlFreeUnicodeString(&SubKeyName);
+
+    return Ret;
+}
+
+
+/************************************************************************
+ *  RegSetKeyValueW
+ *
+ * @implemented
+ */
+LONG STDCALL
+RegSetKeyValueW(IN HKEY hKey,
+                IN LPCWSTR lpSubKey  OPTIONAL,
+                IN LPCWSTR lpValueName  OPTIONAL,
+                IN DWORD dwType,
+                IN LPCVOID lpData  OPTIONAL,
+                IN DWORD cbData)
+{
+    HANDLE KeyHandle, CurKey, SubKeyHandle = NULL;
+    NTSTATUS Status;
+    LONG Ret;
+
+    Status = MapDefaultKey(&KeyHandle,
+                           hKey);
+    if (!NT_SUCCESS(Status))
+    {
+        return RtlNtStatusToDosError(Status);
+    }
+    
+    if (lpSubKey != NULL)
+    {
+        OBJECT_ATTRIBUTES ObjectAttributes;
+        UNICODE_STRING SubKeyName;
+
+        RtlInitUnicodeString(&SubKeyName,
+                             (LPWSTR)lpSubKey);
+
+        InitializeObjectAttributes(&ObjectAttributes,
+                                   &SubKeyName,
+                                   OBJ_CASE_INSENSITIVE,
+                                   KeyHandle,
+                                   NULL);
+
+        Status = NtOpenKey(&SubKeyHandle,
+                           KEY_SET_VALUE,
+                           &ObjectAttributes);
+        if (!NT_SUCCESS(Status))
+        {
+            Ret = RtlNtStatusToDosError(Status);
+            goto Cleanup;
+        }
+        
+        CurKey = SubKeyHandle;
+    }
+    else
+        CurKey = KeyHandle;
+    
+    Ret = RegSetValueExW(CurKey,
+                         lpValueName,
+                         0,
+                         dwType,
+                         lpData,
+                         cbData);
+
+    if (SubKeyHandle != NULL)
+    {
+        NtClose(SubKeyHandle);
+    }
+    
+Cleanup:
+    CloseDefaultKey(KeyHandle);
+
+    return Ret;
+}
+
+
+/************************************************************************
+ *  RegSetKeyValueA
+ *
+ * @implemented
+ */
+LONG STDCALL
+RegSetKeyValueA(IN HKEY hKey,
+                IN LPCSTR lpSubKey  OPTIONAL,
+                IN LPCSTR lpValueName  OPTIONAL,
+                IN DWORD dwType,
+                IN LPCVOID lpData  OPTIONAL,
+                IN DWORD cbData)
+{
+    HANDLE KeyHandle, CurKey, SubKeyHandle = NULL;
+    NTSTATUS Status;
+    LONG Ret;
+
+    Status = MapDefaultKey(&KeyHandle,
+                           hKey);
+    if (!NT_SUCCESS(Status))
+    {
+        return RtlNtStatusToDosError(Status);
+    }
+
+    if (lpSubKey != NULL)
+    {
+        OBJECT_ATTRIBUTES ObjectAttributes;
+        UNICODE_STRING SubKeyName;
+
+        if (!RtlCreateUnicodeStringFromAsciiz(&SubKeyName,
+                                              (LPSTR)lpSubKey))
+        {
+            Ret = ERROR_NOT_ENOUGH_MEMORY;
+            goto Cleanup;
+        }
+
+        InitializeObjectAttributes(&ObjectAttributes,
+                                   &SubKeyName,
+                                   OBJ_CASE_INSENSITIVE,
+                                   KeyHandle,
+                                   NULL);
+
+        Status = NtOpenKey(&SubKeyHandle,
+                           KEY_SET_VALUE,
+                           &ObjectAttributes);
+
+        RtlFreeUnicodeString(&SubKeyName);
+
+        if (!NT_SUCCESS(Status))
+        {
+            Ret = RtlNtStatusToDosError(Status);
+            goto Cleanup;
+        }
+        
+        CurKey = SubKeyHandle;
+    }
+    else
+        CurKey = KeyHandle;
+
+    Ret = RegSetValueExA(CurKey,
+                         lpValueName,
+                         0,
+                         dwType,
+                         lpData,
+                         cbData);
+
+    if (SubKeyHandle != NULL)
+    {
+        NtClose(SubKeyHandle);
+    }
+    
+Cleanup:
+    CloseDefaultKey(KeyHandle);
+
+    return Ret;
+}
+
+
 /************************************************************************
  *  RegDeleteValueA
  *
@@ -703,7 +1403,7 @@ RegDeleteValueA (HKEY hKey,
   NTSTATUS Status;
 
   Status = MapDefaultKey (&KeyHandle,
-                         hKey);
+                          hKey);
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -714,6 +1414,9 @@ RegDeleteValueA (HKEY hKey,
   Status = NtDeleteValueKey (KeyHandle,
                             &ValueName);
   RtlFreeUnicodeString (&ValueName);
+  
+  CloseDefaultKey(KeyHandle);
+  
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -737,7 +1440,7 @@ RegDeleteValueW (HKEY hKey,
   HANDLE KeyHandle;
 
   Status = MapDefaultKey (&KeyHandle,
-                         hKey);
+                          hKey);
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -748,6 +1451,9 @@ RegDeleteValueW (HKEY hKey,
 
   Status = NtDeleteValueKey (KeyHandle,
                             &ValueName);
+
+  CloseDefaultKey(KeyHandle);
+
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -838,7 +1544,7 @@ RegEnumKeyExA (HKEY hKey,
        HANDLE KeyHandle;
        NTSTATUS Status;
 
-       DPRINT("RegEnumKeyExA(hKey 0x%x, dwIndex %d, lpName 0x%x, *lpcbName %d, lpClass 0x%x, lpcbClass %d)\n",
+       TRACE("RegEnumKeyExA(hKey 0x%x, dwIndex %d, lpName 0x%x, *lpcbName %d, lpClass 0x%x, lpcbClass %d)\n",
                hKey, dwIndex, lpName, *lpcbName, lpClass, lpcbClass ? *lpcbClass : 0);
 
        if ((lpClass) && (!lpcbClass))
@@ -883,7 +1589,8 @@ RegEnumKeyExA (HKEY hKey,
        KeyInfo = RtlAllocateHeap (ProcessHeap, 0, BufferSize);
        if (KeyInfo == NULL)
        {
-               return ERROR_OUTOFMEMORY;
+               ErrorCode = ERROR_OUTOFMEMORY;
+               goto Cleanup;
        }
 
        Status = NtEnumerateKey (KeyHandle,
@@ -892,7 +1599,7 @@ RegEnumKeyExA (HKEY hKey,
                                                                KeyInfo,
                                                                BufferSize,
                                                                &ResultSize);
-       DPRINT("NtEnumerateKey() returned status 0x%X\n", Status);
+       TRACE("NtEnumerateKey() returned status 0x%X\n", Status);
        if (!NT_SUCCESS(Status))
        {
                ErrorCode = RtlNtStatusToDosError (Status);
@@ -960,16 +1667,19 @@ RegEnumKeyExA (HKEY hKey,
                }
        }
 
-       DPRINT("Key Namea0 Length %d\n", StringU.Length);
-       DPRINT("Key Namea1 Length %d\n", NameLength);
-       DPRINT("Key Namea Length %d\n", *lpcbName);
-       DPRINT("Key Namea %s\n", lpName);
+       TRACE("Key Namea0 Length %d\n", StringU.Length);
+       TRACE("Key Namea1 Length %d\n", NameLength);
+       TRACE("Key Namea Length %d\n", *lpcbName);
+       TRACE("Key Namea %s\n", lpName);
 
        RtlFreeHeap (ProcessHeap,
                0,
                KeyInfo);
 
-       return ErrorCode;
+Cleanup:
+    CloseDefaultKey(KeyHandle);
+
+    return ErrorCode;
 }
 
 
@@ -1003,7 +1713,7 @@ RegEnumKeyExW (HKEY hKey,
   NTSTATUS Status;
 
   Status = MapDefaultKey(&KeyHandle,
-                        hKey);
+                         hKey);
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -1041,7 +1751,8 @@ RegEnumKeyExW (HKEY hKey,
                             BufferSize);
   if (KeyInfo == NULL)
     {
-      return ERROR_OUTOFMEMORY;
+      ErrorCode = ERROR_OUTOFMEMORY;
+      goto Cleanup;
     }
 
   Status = NtEnumerateKey (KeyHandle,
@@ -1050,7 +1761,7 @@ RegEnumKeyExW (HKEY hKey,
                           KeyInfo,
                           BufferSize,
                           &ResultSize);
-  DPRINT("NtEnumerateKey() returned status 0x%X\n", Status);
+  TRACE("NtEnumerateKey() returned status 0x%X\n", Status);
   if (!NT_SUCCESS(Status))
     {
       ErrorCode = RtlNtStatusToDosError (Status);
@@ -1113,6 +1824,9 @@ RegEnumKeyExW (HKEY hKey,
               0,
               KeyInfo);
 
+Cleanup:
+  CloseDefaultKey(KeyHandle);
+
   return ErrorCode;
 }
 
@@ -1160,7 +1874,10 @@ RegEnumValueA( HKEY hKey, DWORD index, LPSTR value, LPDWORD val_count,
         {
             if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
             if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
-                return ERROR_NOT_ENOUGH_MEMORY;
+            {
+                status = STATUS_INSUFFICIENT_RESOURCES;
+                goto done;
+            }
             info = (KEY_VALUE_FULL_INFORMATION *)buf_ptr;
             status = NtEnumerateValueKey( KeyHandle, index, KeyValueFullInformation,
                                           buf_ptr, total_size, &total_size );
@@ -1178,7 +1895,7 @@ RegEnumValueA( HKEY hKey, DWORD index, LPSTR value, LPDWORD val_count,
                 if (len > *count) status = STATUS_BUFFER_OVERFLOW;
                 else
                 {
-                    RtlUnicodeToMultiByteN( data, len, NULL, (WCHAR *)(buf_ptr + info->DataOffset),
+                    RtlUnicodeToMultiByteN( (PCHAR)data, len, NULL, (WCHAR *)(buf_ptr + info->DataOffset),
                                             total_size - info->DataOffset );
                     /* if the type is REG_SZ and data is not 0-terminated
                      * and there is enough space in the buffer NT appends a \0 */
@@ -1223,13 +1940,14 @@ RegEnumValueA( HKEY hKey, DWORD index, LPSTR value, LPDWORD val_count,
 
  done:
     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
+    CloseDefaultKey(KeyHandle);
     return RtlNtStatusToDosError(status);
 }
 
 /******************************************************************************
  * RegEnumValueW   [ADVAPI32.@]
  * @implemented
- * 
+ *
  * PARAMS
  *  hkey       [I] Handle to key to query
  *  index      [I] Index of value to query
@@ -1260,7 +1978,7 @@ RegEnumValueW( HKEY hKey, DWORD index, LPWSTR value, PDWORD val_count,
 
     /* NT only checks count, not val_count */
     if ((data && !count) || reserved) return ERROR_INVALID_PARAMETER;
-       
+
        status = MapDefaultKey (&KeyHandle, hKey);
        if (!NT_SUCCESS(status))
        {
@@ -1282,7 +2000,10 @@ RegEnumValueW( HKEY hKey, DWORD index, LPWSTR value, PDWORD val_count,
         {
             if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
             if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
-                return ERROR_NOT_ENOUGH_MEMORY;
+            {
+                status = ERROR_NOT_ENOUGH_MEMORY;
+                goto done;
+            }
             info = (KEY_VALUE_FULL_INFORMATION *)buf_ptr;
             status = NtEnumerateValueKey( KeyHandle, index, KeyValueFullInformation,
                                           buf_ptr, total_size, &total_size );
@@ -1327,6 +2048,7 @@ RegEnumValueW( HKEY hKey, DWORD index, LPWSTR value, PDWORD val_count,
 
  done:
     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
+    CloseDefaultKey(KeyHandle);
     return RtlNtStatusToDosError(status);
 }
 
@@ -1347,13 +2069,16 @@ RegFlushKey(HKEY hKey)
     }
 
   Status = MapDefaultKey (&KeyHandle,
-                         hKey);
+                          hKey);
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
     }
 
   Status = NtFlushKey (KeyHandle);
+  
+  CloseDefaultKey(KeyHandle);
+  
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -1383,10 +2108,10 @@ RegGetKeySecurity(HKEY hKey,
     }
 
   Status = MapDefaultKey(&KeyHandle,
-                        hKey);
+                         hKey);
   if (!NT_SUCCESS(Status))
     {
-      DPRINT("MapDefaultKey() failed (Status %lx)\n", Status);
+      TRACE("MapDefaultKey() failed (Status %lx)\n", Status);
       return RtlNtStatusToDosError (Status);
     }
 
@@ -1395,9 +2120,12 @@ RegGetKeySecurity(HKEY hKey,
                                 pSecurityDescriptor,
                                 *lpcbSecurityDescriptor,
                                 lpcbSecurityDescriptor);
+
+  CloseDefaultKey(KeyHandle);
+
   if (!NT_SUCCESS(Status))
     {
-      DPRINT("NtQuerySecurityObject() failed (Status %lx)\n", Status);
+      WARN("NtQuerySecurityObject() failed (Status %lx)\n", Status);
       return RtlNtStatusToDosError (Status);
     }
 
@@ -1451,6 +2179,7 @@ RegLoadKeyW (HKEY hKey,
   UNICODE_STRING KeyName;
   HANDLE KeyHandle;
   NTSTATUS Status;
+  LONG ErrorCode = ERROR_SUCCESS;
 
   if (hKey == HKEY_PERFORMANCE_DATA)
     {
@@ -1458,7 +2187,7 @@ RegLoadKeyW (HKEY hKey,
     }
 
   Status = MapDefaultKey (&KeyHandle,
-                         hKey);
+                          hKey);
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -1469,7 +2198,8 @@ RegLoadKeyW (HKEY hKey,
                                     NULL,
                                     NULL))
     {
-      return ERROR_BAD_PATHNAME;
+      ErrorCode = ERROR_BAD_PATHNAME;
+      goto Cleanup;
     }
 
   InitializeObjectAttributes (&FileObjectAttributes,
@@ -1494,10 +2224,14 @@ RegLoadKeyW (HKEY hKey,
 
   if (!NT_SUCCESS(Status))
     {
-      return RtlNtStatusToDosError (Status);
+      ErrorCode = RtlNtStatusToDosError (Status);
+      goto Cleanup;
     }
 
-  return ERROR_SUCCESS;
+Cleanup:
+  CloseDefaultKey(KeyHandle);
+
+  return ErrorCode;
 }
 
 
@@ -1516,6 +2250,7 @@ RegNotifyChangeKeyValue (HKEY hKey,
   IO_STATUS_BLOCK IoStatusBlock;
   HANDLE KeyHandle;
   NTSTATUS Status;
+  LONG ErrorCode = ERROR_SUCCESS;
 
   if (hKey == HKEY_PERFORMANCE_DATA)
     {
@@ -1528,7 +2263,7 @@ RegNotifyChangeKeyValue (HKEY hKey,
     }
 
   Status = MapDefaultKey (&KeyHandle,
-                         hKey);
+                          hKey);
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -1548,10 +2283,12 @@ RegNotifyChangeKeyValue (HKEY hKey,
                              fAsynchronous);
   if (!NT_SUCCESS(Status) && Status != STATUS_TIMEOUT)
     {
-      return RtlNtStatusToDosError (Status);
+      ErrorCode = RtlNtStatusToDosError (Status);
     }
 
-  return ERROR_SUCCESS;
+  CloseDefaultKey(KeyHandle);
+
+  return ErrorCode;
 }
 
 
@@ -1590,7 +2327,7 @@ RegOpenKeyA (HKEY hKey,
             LPCSTR lpSubKey,
             PHKEY phkResult)
 {
-       DPRINT("RegOpenKeyA hKey 0x%x lpSubKey %s phkResult %p\n", hKey, lpSubKey, phkResult);
+       TRACE("RegOpenKeyA hKey 0x%x lpSubKey %s phkResult %p\n", hKey, lpSubKey, phkResult);
 
        if (!lpSubKey || !*lpSubKey)
        {
@@ -1616,7 +2353,7 @@ RegOpenKeyW (HKEY hKey,
             LPCWSTR lpSubKey,
             PHKEY phkResult)
 {
-       DPRINT("RegOpenKeyW hKey 0x%x lpSubKey %S phkResult %p\n", hKey, lpSubKey, phkResult);
+       TRACE("RegOpenKeyW hKey 0x%x lpSubKey %S phkResult %p\n", hKey, lpSubKey, phkResult);
 
        if (!lpSubKey || !*lpSubKey)
        {
@@ -1643,8 +2380,9 @@ RegOpenKeyExA (HKEY hKey,
        UNICODE_STRING SubKeyString;
        HANDLE KeyHandle;
        NTSTATUS Status;
+       LONG ErrorCode = ERROR_SUCCESS;
 
-       DPRINT("RegOpenKeyExA hKey 0x%x lpSubKey %s ulOptions 0x%x samDesired 0x%x phkResult %p\n",
+       TRACE("RegOpenKeyExA hKey 0x%x lpSubKey %s ulOptions 0x%x samDesired 0x%x phkResult %p\n",
                hKey, lpSubKey, ulOptions, samDesired, phkResult);
 
        Status = MapDefaultKey (&KeyHandle, hKey);
@@ -1664,10 +2402,12 @@ RegOpenKeyExA (HKEY hKey,
        RtlFreeUnicodeString (&SubKeyString);
        if (!NT_SUCCESS(Status))
        {
-               return RtlNtStatusToDosError (Status);
+               ErrorCode = RtlNtStatusToDosError (Status);
        }
+       
+       CloseDefaultKey(KeyHandle);
 
-       return ERROR_SUCCESS;
+       return ErrorCode;
 }
 
 
@@ -1687,10 +2427,11 @@ RegOpenKeyExW (HKEY hKey,
        UNICODE_STRING SubKeyString;
        HANDLE KeyHandle;
        NTSTATUS Status;
+       LONG ErrorCode = ERROR_SUCCESS;
 
-       DPRINT("RegOpenKeyExW hKey 0x%x lpSubKey %S ulOptions 0x%x samDesired 0x%x phkResult %p\n",
+       TRACE("RegOpenKeyExW hKey 0x%x lpSubKey %S ulOptions 0x%x samDesired 0x%x phkResult %p\n",
                hKey, lpSubKey, ulOptions, samDesired, phkResult);
-       
+
        Status = MapDefaultKey (&KeyHandle, hKey);
        if (!NT_SUCCESS(Status))
        {
@@ -1712,10 +2453,155 @@ RegOpenKeyExW (HKEY hKey,
 
        if (!NT_SUCCESS(Status))
        {
-               return RtlNtStatusToDosError (Status);
+               ErrorCode = RtlNtStatusToDosError (Status);
        }
+       
+       CloseDefaultKey(KeyHandle);
+
+       return ErrorCode;
+}
+
+
+/************************************************************************
+ *  RegOpenUserClassesRoot
+ *
+ * @implemented
+ */
+LONG STDCALL
+RegOpenUserClassesRoot (IN HANDLE hToken,
+                        IN DWORD dwOptions,
+                        IN REGSAM samDesired,
+                        OUT PHKEY phkResult)
+{
+  const WCHAR UserClassesKeyPrefix[] = L"\\Registry\\User\\";
+  const WCHAR UserClassesKeySuffix[] = L"_Classes";
+  PTOKEN_USER TokenUserData;
+  ULONG RequiredLength;
+  UNICODE_STRING UserSidString, UserClassesKeyRoot;
+  OBJECT_ATTRIBUTES ObjectAttributes;
+  NTSTATUS Status;
+
+  /* check parameters */
+  if (hToken == NULL || dwOptions != 0 || phkResult == NULL)
+  {
+    return ERROR_INVALID_PARAMETER;
+  }
+
+  /*
+   * Get the user sid from the token
+   */
+
+ReadTokenSid:
+  /* determine how much memory we need */
+  Status = NtQueryInformationToken(hToken,
+                                   TokenUser,
+                                   NULL,
+                                   0,
+                                   &RequiredLength);
+  if (!NT_SUCCESS(Status) && (Status != STATUS_BUFFER_TOO_SMALL))
+  {
+    /* NOTE - as opposed to all other registry functions windows does indeed
+              change the last error code in case the caller supplied a invalid
+              handle for example! */
+    return RtlNtStatusToDosError (Status);
+  }
+
+  TokenUserData = RtlAllocateHeap(ProcessHeap,
+                                  0,
+                                  RequiredLength);
+  if (TokenUserData == NULL)
+  {
+    return ERROR_NOT_ENOUGH_MEMORY;
+  }
+
+  /* attempt to read the information */
+  Status = NtQueryInformationToken(hToken,
+                                   TokenUser,
+                                   TokenUserData,
+                                   RequiredLength,
+                                   &RequiredLength);
+  if (!NT_SUCCESS(Status))
+  {
+    RtlFreeHeap(ProcessHeap,
+                0,
+                TokenUserData);
+    if (Status == STATUS_BUFFER_TOO_SMALL)
+    {
+      /* the information appears to have changed?! try again */
+      goto ReadTokenSid;
+    }
+
+    /* NOTE - as opposed to all other registry functions windows does indeed
+              change the last error code in case the caller supplied a invalid
+              handle for example! */
+    return RtlNtStatusToDosError (Status);
+  }
+
+  /*
+   * Build the absolute path for the user's registry in the form
+   * "\Registry\User\<SID>_Classes"
+   */
+  Status = RtlConvertSidToUnicodeString(&UserSidString,
+                                        TokenUserData->User.Sid,
+                                        TRUE);
+
+  /* we don't need the user data anymore, free it */
+  RtlFreeHeap(ProcessHeap,
+              0,
+              TokenUserData);
+
+  if (!NT_SUCCESS(Status))
+  {
+    return RtlNtStatusToDosError (Status);
+  }
+
+  /* allocate enough memory for the entire key string */
+  UserClassesKeyRoot.Length = 0;
+  UserClassesKeyRoot.MaximumLength = UserSidString.Length +
+                                     sizeof(UserClassesKeyPrefix) +
+                                     sizeof(UserClassesKeySuffix);
+  UserClassesKeyRoot.Buffer = RtlAllocateHeap(ProcessHeap,
+                                              0,
+                                              UserClassesKeyRoot.MaximumLength);
+  if (UserClassesKeyRoot.Buffer == NULL)
+  {
+    RtlFreeUnicodeString(&UserSidString);
+    return RtlNtStatusToDosError (Status);
+  }
+
+  /* build the string */
+  RtlAppendUnicodeToString(&UserClassesKeyRoot,
+                           UserClassesKeyPrefix);
+  RtlAppendUnicodeStringToString(&UserClassesKeyRoot,
+                                 &UserSidString);
+  RtlAppendUnicodeToString(&UserClassesKeyRoot,
+                           UserClassesKeySuffix);
+
+  TRACE("RegOpenUserClassesRoot: Absolute path: %wZ\n", &UserClassesKeyRoot);
+
+  /*
+   * Open the key
+   */
 
-       return ERROR_SUCCESS;
+  InitializeObjectAttributes (&ObjectAttributes,
+                             &UserClassesKeyRoot,
+                             OBJ_CASE_INSENSITIVE,
+                             NULL,
+                             NULL);
+
+  Status = NtOpenKey((PHANDLE)phkResult,
+                     samDesired,
+                     &ObjectAttributes);
+
+  RtlFreeUnicodeString(&UserSidString);
+  RtlFreeUnicodeString(&UserClassesKeyRoot);
+
+  if (!NT_SUCCESS(Status))
+  {
+    return RtlNtStatusToDosError (Status);
+  }
+
+  return ERROR_SUCCESS;
 }
 
 
@@ -1837,7 +2723,8 @@ RegQueryInfoKeyW (HKEY hKey,
                                  FullInfoSize);
       if (FullInfo == NULL)
        {
-         return ERROR_OUTOFMEMORY;
+         ErrorCode = ERROR_OUTOFMEMORY;
+         goto Cleanup;
        }
 
       FullInfo->ClassLength = ClassLength;
@@ -1855,7 +2742,7 @@ RegQueryInfoKeyW (HKEY hKey,
                       FullInfo,
                       FullInfoSize,
                       &Length);
-  DPRINT("NtQueryKey() returned status 0x%X\n", Status);
+  TRACE("NtQueryKey() returned status 0x%X\n", Status);
   if (!NT_SUCCESS(Status))
     {
       if (lpClass != NULL)
@@ -1865,40 +2752,41 @@ RegQueryInfoKeyW (HKEY hKey,
                       FullInfo);
        }
 
-      return RtlNtStatusToDosError (Status);
+      ErrorCode = RtlNtStatusToDosError (Status);
+      goto Cleanup;
     }
 
-  DPRINT("SubKeys %d\n", FullInfo->SubKeys);
+  TRACE("SubKeys %d\n", FullInfo->SubKeys);
   if (lpcSubKeys != NULL)
     {
       *lpcSubKeys = FullInfo->SubKeys;
     }
 
-  DPRINT("MaxNameLen %lu\n", FullInfo->MaxNameLen);
+  TRACE("MaxNameLen %lu\n", FullInfo->MaxNameLen);
   if (lpcbMaxSubKeyLen != NULL)
     {
       *lpcbMaxSubKeyLen = FullInfo->MaxNameLen / sizeof(WCHAR) + 1;
     }
 
-  DPRINT("MaxClassLen %lu\n", FullInfo->MaxClassLen);
+  TRACE("MaxClassLen %lu\n", FullInfo->MaxClassLen);
   if (lpcbMaxClassLen != NULL)
     {
       *lpcbMaxClassLen = FullInfo->MaxClassLen / sizeof(WCHAR) + 1;
     }
 
-  DPRINT("Values %lu\n", FullInfo->Values);
+  TRACE("Values %lu\n", FullInfo->Values);
   if (lpcValues != NULL)
     {
       *lpcValues = FullInfo->Values;
     }
 
-  DPRINT("MaxValueNameLen %lu\n", FullInfo->MaxValueNameLen);
+  TRACE("MaxValueNameLen %lu\n", FullInfo->MaxValueNameLen);
   if (lpcbMaxValueNameLen != NULL)
     {
       *lpcbMaxValueNameLen = FullInfo->MaxValueNameLen / sizeof(WCHAR) + 1;
     }
 
-  DPRINT("MaxValueDataLen %lu\n", FullInfo->MaxValueDataLen);
+  TRACE("MaxValueDataLen %lu\n", FullInfo->MaxValueDataLen);
   if (lpcbMaxValueLen != NULL)
     {
       *lpcbMaxValueLen = FullInfo->MaxValueDataLen;
@@ -1922,7 +2810,8 @@ RegQueryInfoKeyW (HKEY hKey,
                          FullInfo);
            }
 
-         return RtlNtStatusToDosError (Status);
+         ErrorCode = RtlNtStatusToDosError (Status);
+         goto Cleanup;
        }
     }
 
@@ -1952,6 +2841,9 @@ RegQueryInfoKeyW (HKEY hKey,
                   FullInfo);
     }
 
+Cleanup:
+  CloseDefaultKey(KeyHandle);
+  
   return ErrorCode;
 }
 
@@ -1978,7 +2870,7 @@ RegQueryMultipleValuesA (HKEY hKey,
 
   *ldwTotsize = 0;
 
-  DPRINT ("RegQueryMultipleValuesA(%p,%p,%ld,%p,%p=%ld)\n",
+  TRACE("RegQueryMultipleValuesA(%p,%p,%ld,%p,%p=%ld)\n",
          hKey, val_list, num_vals, lpValueBuf, ldwTotsize, *ldwTotsize);
 
   for (i = 0; i < num_vals; i++)
@@ -2042,7 +2934,7 @@ RegQueryMultipleValuesW (HKEY hKey,
 
   *ldwTotsize = 0;
 
-  DPRINT ("RegQueryMultipleValuesW(%p,%p,%ld,%p,%p=%ld)\n",
+  TRACE ("RegQueryMultipleValuesW(%p,%p,%ld,%p,%p=%ld)\n",
          hKey, val_list, num_vals, lpValueBuf, ldwTotsize, *ldwTotsize);
 
   for (i = 0; i < num_vals; i++)
@@ -2106,7 +2998,7 @@ RegQueryValueExW (HKEY hKey,
   LONG ErrorCode = ERROR_SUCCESS;
   ULONG MaxCopy = lpcbData != NULL && lpData != NULL ? *lpcbData : 0;
 
-  DPRINT("hKey 0x%X  lpValueName %S  lpData 0x%X  lpcbData %d\n",
+  TRACE("hKey 0x%X  lpValueName %S  lpData 0x%X  lpcbData %d\n",
         hKey, lpValueName, lpData, lpcbData ? *lpcbData : 0);
 
   Status = MapDefaultKey (&KeyHandle,
@@ -2118,7 +3010,8 @@ RegQueryValueExW (HKEY hKey,
 
   if (lpData != NULL && lpcbData == NULL)
     {
-      return ERROR_INVALID_PARAMETER;
+      ErrorCode = ERROR_INVALID_PARAMETER;
+      goto Cleanup;
     }
 
   RtlInitUnicodeString (&ValueName,
@@ -2129,7 +3022,8 @@ RegQueryValueExW (HKEY hKey,
                               BufferSize);
   if (ValueInfo == NULL)
     {
-      return ERROR_OUTOFMEMORY;
+      ErrorCode = ERROR_OUTOFMEMORY;
+      goto Cleanup;
     }
 
   Status = NtQueryValueKey (KeyHandle,
@@ -2138,7 +3032,7 @@ RegQueryValueExW (HKEY hKey,
                            ValueInfo,
                            BufferSize,
                            &ResultSize);
-  DPRINT("Status 0x%X\n", Status);
+  TRACE("Status 0x%X\n", Status);
   if (Status == STATUS_BUFFER_OVERFLOW)
     {
       /* Return ERROR_SUCCESS and the buffer space needed for a successful call */
@@ -2179,7 +3073,7 @@ RegQueryValueExW (HKEY hKey,
       if (lpcbData != NULL)
        {
          *lpcbData = (ResultSize - FIELD_OFFSET(KEY_VALUE_PARTIAL_INFORMATION, Data[0]));
-         DPRINT("(string) Returning Size: %lu\n", *lpcbData);
+         TRACE("(string) Returning Size: %lu\n", *lpcbData);
        }
     }
   else
@@ -2187,16 +3081,19 @@ RegQueryValueExW (HKEY hKey,
       if (lpcbData != NULL)
        {
          *lpcbData = ResultSize - FIELD_OFFSET(KEY_VALUE_PARTIAL_INFORMATION, Data[0]);
-         DPRINT("(other) Returning Size: %lu\n", *lpcbData);
+         TRACE("(other) Returning Size: %lu\n", *lpcbData);
        }
     }
 
-  DPRINT("Type %d  Size %d\n", ValueInfo->Type, ValueInfo->DataLength);
+  TRACE("Type %d  Size %d\n", ValueInfo->Type, ValueInfo->DataLength);
 
   RtlFreeHeap (ProcessHeap,
               0,
               ValueInfo);
 
+Cleanup:
+  CloseDefaultKey(KeyHandle);
+
   return ErrorCode;
 }
 
@@ -2221,7 +3118,7 @@ RegQueryValueExA (HKEY hKey,
   DWORD Length;
   DWORD Type;
 
-  DPRINT("hKey 0x%X  lpValueName %s  lpData 0x%X  lpcbData %d\n",
+  TRACE("hKey 0x%X  lpValueName %s  lpData 0x%X  lpcbData %d\n",
         hKey, lpValueName, lpData, lpcbData ? *lpcbData : 0);
 
   if (lpData != NULL && lpcbData == NULL)
@@ -2258,7 +3155,7 @@ RegQueryValueExA (HKEY hKey,
                                &Type,
                                (lpData == NULL) ? NULL : (LPBYTE)ValueData.Buffer,
                                &Length);
-  DPRINT("ErrorCode %lu\n", ErrorCode);
+  TRACE("ErrorCode %lu\n", ErrorCode);
   RtlFreeUnicodeString(&ValueName);
 
   if (ErrorCode == ERROR_SUCCESS ||
@@ -2327,7 +3224,7 @@ RegQueryValueA (HKEY hKey,
   LONG ValueSize;
   LONG ErrorCode;
 
-  DPRINT("hKey 0x%X lpSubKey %s lpValue %p lpcbValue %d\n",
+  TRACE("hKey 0x%X lpSubKey %s lpValue %p lpcbValue %d\n",
         hKey, lpSubKey, lpValue, lpcbValue ? *lpcbValue : 0);
 
   if (lpValue != NULL &&
@@ -2416,11 +3313,11 @@ RegQueryValueW (HKEY hKey,
   BOOL CloseRealKey;
   NTSTATUS Status;
 
-  DPRINT("hKey 0x%X lpSubKey %S lpValue %p lpcbValue %d\n",
+  TRACE("hKey 0x%X lpSubKey %S lpValue %p lpcbValue %d\n",
         hKey, lpSubKey, lpValue, lpcbValue ? *lpcbValue : 0);
 
   Status = MapDefaultKey (&KeyHandle,
-                         hKey);
+                          hKey);
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -2441,7 +3338,8 @@ RegQueryValueW (HKEY hKey,
                          &ObjectAttributes);
       if (!NT_SUCCESS(Status))
        {
-         return RtlNtStatusToDosError (Status);
+         ErrorCode = RtlNtStatusToDosError (Status);
+         goto Cleanup;
        }
       CloseRealKey = TRUE;
     }
@@ -2462,6 +3360,9 @@ RegQueryValueW (HKEY hKey,
       NtClose (RealKey);
     }
 
+Cleanup:
+  CloseDefaultKey(KeyHandle);
+
   return ErrorCode;
 }
 
@@ -2523,6 +3424,7 @@ RegReplaceKeyW (HKEY hKey,
   HANDLE RealKeyHandle;
   HANDLE KeyHandle;
   NTSTATUS Status;
+  LONG ErrorCode = ERROR_SUCCESS;
 
   if (hKey == HKEY_PERFORMANCE_DATA)
     {
@@ -2530,7 +3432,7 @@ RegReplaceKeyW (HKEY hKey,
     }
 
   Status = MapDefaultKey (&KeyHandle,
-                         hKey);
+                          hKey);
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -2551,7 +3453,8 @@ RegReplaceKeyW (HKEY hKey,
                          &KeyObjectAttributes);
       if (!NT_SUCCESS(Status))
        {
-         return RtlNtStatusToDosError (Status);
+         ErrorCode = RtlNtStatusToDosError (Status);
+         goto Cleanup;
        }
       CloseRealKey = TRUE;
     }
@@ -2571,7 +3474,8 @@ RegReplaceKeyW (HKEY hKey,
        {
          NtClose (RealKeyHandle);
        }
-      return ERROR_INVALID_PARAMETER;
+      ErrorCode = ERROR_INVALID_PARAMETER;
+      goto Cleanup;
     }
 
   InitializeObjectAttributes (&NewObjectAttributes,
@@ -2591,7 +3495,8 @@ RegReplaceKeyW (HKEY hKey,
        {
          NtClose (RealKeyHandle);
        }
-      return ERROR_INVALID_PARAMETER;
+      ErrorCode = ERROR_INVALID_PARAMETER;
+      goto Cleanup;
     }
 
   InitializeObjectAttributes (&OldObjectAttributes,
@@ -2617,7 +3522,10 @@ RegReplaceKeyW (HKEY hKey,
       return RtlNtStatusToDosError (Status);
     }
 
-  return ERROR_SUCCESS;
+Cleanup:
+  CloseDefaultKey(KeyHandle);
+
+  return ErrorCode;
 }
 
 
@@ -2670,7 +3578,7 @@ RegRestoreKeyW (HKEY hKey,
     }
 
   Status = MapDefaultKey (&KeyHandle,
-                         hKey);
+                          hKey);
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -2681,7 +3589,8 @@ RegRestoreKeyW (HKEY hKey,
                                     NULL,
                                     NULL))
     {
-      return ERROR_INVALID_PARAMETER;
+      Status = STATUS_INVALID_PARAMETER;
+      goto Cleanup;
     }
 
   InitializeObjectAttributes (&ObjectAttributes,
@@ -2699,13 +3608,17 @@ RegRestoreKeyW (HKEY hKey,
   RtlFreeUnicodeString (&FileName);
   if (!NT_SUCCESS(Status))
     {
-      return RtlNtStatusToDosError (Status);
+      goto Cleanup;
     }
 
   Status = NtRestoreKey (KeyHandle,
                         FileHandle,
                         (ULONG)dwFlags);
   NtClose (FileHandle);
+  
+Cleanup:
+  CloseDefaultKey(KeyHandle);
+
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -2758,7 +3671,7 @@ RegSaveKeyW (HKEY hKey,
   NTSTATUS Status;
 
   Status = MapDefaultKey (&KeyHandle,
-                         hKey);
+                          hKey);
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -2769,7 +3682,8 @@ RegSaveKeyW (HKEY hKey,
                                     NULL,
                                     NULL))
     {
-      return ERROR_INVALID_PARAMETER;
+      Status = STATUS_INVALID_PARAMETER;
+      goto Cleanup;
     }
 
   if (lpSecurityAttributes != NULL)
@@ -2796,12 +3710,16 @@ RegSaveKeyW (HKEY hKey,
   RtlFreeUnicodeString (&FileName);
   if (!NT_SUCCESS(Status))
     {
-      return RtlNtStatusToDosError (Status);
+      goto Cleanup;
     }
 
   Status = NtSaveKey (KeyHandle,
                      FileHandle);
   NtClose (FileHandle);
+
+Cleanup:
+  CloseDefaultKey(KeyHandle);
+
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -2830,7 +3748,7 @@ RegSetKeySecurity (HKEY hKey,
     }
 
   Status = MapDefaultKey (&KeyHandle,
-                         hKey);
+                          hKey);
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -2839,6 +3757,9 @@ RegSetKeySecurity (HKEY hKey,
   Status = NtSetSecurityObject (KeyHandle,
                                SecurityInformation,
                                pSecurityDescriptor);
+
+  CloseDefaultKey(KeyHandle);
+  
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -2891,7 +3812,7 @@ RegSetValueExA (HKEY hKey,
       {
          cbData++;
       }
-      
+
       RtlInitAnsiString (&AnsiString,
                         NULL);
       AnsiString.Buffer = (PSTR)lpData;
@@ -2954,7 +3875,7 @@ RegSetValueExW (HKEY hKey,
   NTSTATUS Status;
 
   Status = MapDefaultKey (&KeyHandle,
-                         hKey);
+                          hKey);
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -2970,7 +3891,7 @@ RegSetValueExW (HKEY hKey,
       RtlInitUnicodeString (&ValueName, L"");
     }
   pValueName = &ValueName;
-  
+
   if (((dwType == REG_SZ) ||
        (dwType == REG_MULTI_SZ) ||
        (dwType == REG_EXPAND_SZ)) &&
@@ -2986,6 +3907,9 @@ RegSetValueExW (HKEY hKey,
                          dwType,
                          (PVOID)lpData,
                          (ULONG)cbData);
+
+  CloseDefaultKey(KeyHandle);
+
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -3009,12 +3933,12 @@ RegSetValueA (HKEY hKey,
 {
   LONG ret;
   HKEY hSubKey;
-  
+
   if (dwType != REG_SZ)
   {
      return ERROR_INVALID_PARAMETER;
   }
-  
+
   if (lpSubKey != NULL && lpSubKey[0] != '\0')
   {
      ret = RegCreateKeyA(hKey,
@@ -3028,14 +3952,14 @@ RegSetValueA (HKEY hKey,
   }
   else
      hSubKey = hKey;
-  
+
   ret = RegSetValueExA(hSubKey,
                        NULL,
                        0,
                        REG_SZ,
-                       lpData,
+                       (CONST BYTE*)lpData,
                        strlen(lpData) + 1);
-  
+
   if (hSubKey != hKey)
   {
      RegCloseKey(hSubKey);
@@ -3066,7 +3990,7 @@ RegSetValueW (HKEY hKey,
   LONG ErrorCode;
 
   Status = MapDefaultKey (&KeyHandle,
-                         hKey);
+                          hKey);
   if (!NT_SUCCESS(Status))
     {
       return RtlNtStatusToDosError (Status);
@@ -3086,7 +4010,8 @@ RegSetValueW (HKEY hKey,
                          &ObjectAttributes);
       if (!NT_SUCCESS(Status))
        {
-         return RtlNtStatusToDosError (Status);
+         ErrorCode = RtlNtStatusToDosError (Status);
+         goto Cleanup;
        }
       CloseRealKey = TRUE;
     }
@@ -3107,6 +4032,9 @@ RegSetValueW (HKEY hKey,
       NtClose (RealKey);
     }
 
+Cleanup:
+  CloseDefaultKey(KeyHandle);
+
   return ErrorCode;
 }
 
@@ -3170,6 +4098,8 @@ RegUnLoadKeyW (HKEY hKey,
                              NULL);
 
   Status = NtUnloadKey (&ObjectAttributes);
+  
+  CloseDefaultKey(KeyHandle);
 
   if (!NT_SUCCESS(Status))
     {
@@ -3179,4 +4109,43 @@ RegUnLoadKeyW (HKEY hKey,
   return ERROR_SUCCESS;
 }
 
+
+/************************************************************************
+ *  RegLoadMUIStringW
+ *
+ * @unimplemented
+ */
+LONG STDCALL
+RegLoadMUIStringW(IN HKEY hKey,
+                  IN LPCWSTR pszValue  OPTIONAL,
+                  OUT LPWSTR pszOutBuf,
+                  IN ULONG cbOutBuf,
+                  IN ULONG Reserved,
+                  IN LPCWSTR pszDirectory  OPTIONAL)
+{
+    DPRINT1("RegLoadMUIStringW(0x%p, 0x%p, 0x%p, 0x%x, 0x%x, 0x%p) UNIMPLEMENTED!\n",
+            hKey, pszValue, pszOutBuf, cbOutBuf, Reserved, pszDirectory);
+    return ERROR_CALL_NOT_IMPLEMENTED;
+}
+
+
+/************************************************************************
+ *  RegLoadMUIStringA
+ *
+ * @unimplemented
+ */
+LONG STDCALL
+RegLoadMUIStringA(IN HKEY hKey,
+                  IN LPCSTR pszValue  OPTIONAL,
+                  OUT LPSTR pszOutBuf,
+                  IN ULONG cbOutBuf,
+                  IN ULONG Reserved,
+                  IN LPCSTR pszDirectory  OPTIONAL)
+{
+    DPRINT1("RegLoadMUIStringA(0x%p, 0x%p, 0x%p, 0x%x, 0x%x, 0x%p) UNIMPLEMENTED!\n",
+            hKey, pszValue, pszOutBuf, cbOutBuf, Reserved, pszDirectory);
+    return ERROR_CALL_NOT_IMPLEMENTED;
+}
+
+
 /* EOF */