advapi32: Sign-compare warnings fix.
[wine] / dlls / advapi32 / registry.c
1 /*
2  * Registry management
3  *
4  * Copyright (C) 1999 Alexandre Julliard
5  *
6  * Based on misc/registry.c code
7  * Copyright (C) 1996 Marcus Meissner
8  * Copyright (C) 1998 Matthew Becker
9  * Copyright (C) 1999 Sylvain St-Germain
10  *
11  * This file is concerned about handle management and interaction with the Wine server.
12  * Registry file I/O is in misc/registry.c.
13  *
14  * This library is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU Lesser General Public
16  * License as published by the Free Software Foundation; either
17  * version 2.1 of the License, or (at your option) any later version.
18  *
19  * This library is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22  * Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public
25  * License along with this library; if not, write to the Free Software
26  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27  */
28
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32
33 #include "ntstatus.h"
34 #define WIN32_NO_STATUS
35 #include "windef.h"
36 #include "winbase.h"
37 #include "winreg.h"
38 #include "winerror.h"
39 #include "winternl.h"
40 #include "winuser.h"
41
42 #include "wine/unicode.h"
43 #include "wine/debug.h"
44
45 WINE_DEFAULT_DEBUG_CHANNEL(reg);
46
47 /* allowed bits for access mask */
48 #define KEY_ACCESS_MASK (KEY_ALL_ACCESS | MAXIMUM_ALLOWED)
49
50 #define HKEY_SPECIAL_ROOT_FIRST   HKEY_CLASSES_ROOT
51 #define HKEY_SPECIAL_ROOT_LAST    HKEY_DYN_DATA
52 #define NB_SPECIAL_ROOT_KEYS      ((UINT)HKEY_SPECIAL_ROOT_LAST - (UINT)HKEY_SPECIAL_ROOT_FIRST + 1)
53
54 static HKEY special_root_keys[NB_SPECIAL_ROOT_KEYS];
55 static BOOL hkcu_cache_disabled;
56
57 static const WCHAR name_CLASSES_ROOT[] =
58     {'M','a','c','h','i','n','e','\\',
59      'S','o','f','t','w','a','r','e','\\',
60      'C','l','a','s','s','e','s',0};
61 static const WCHAR name_LOCAL_MACHINE[] =
62     {'M','a','c','h','i','n','e',0};
63 static const WCHAR name_USERS[] =
64     {'U','s','e','r',0};
65 static const WCHAR name_PERFORMANCE_DATA[] =
66     {'P','e','r','f','D','a','t','a',0};
67 static const WCHAR name_CURRENT_CONFIG[] =
68     {'M','a','c','h','i','n','e','\\',
69      'S','y','s','t','e','m','\\',
70      'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
71      'H','a','r','d','w','a','r','e',' ','P','r','o','f','i','l','e','s','\\',
72      'C','u','r','r','e','n','t',0};
73 static const WCHAR name_DYN_DATA[] =
74     {'D','y','n','D','a','t','a',0};
75
76 static const WCHAR * const root_key_names[NB_SPECIAL_ROOT_KEYS] =
77 {
78     name_CLASSES_ROOT,
79     NULL,         /* HKEY_CURRENT_USER is determined dynamically */
80     name_LOCAL_MACHINE,
81     name_USERS,
82     name_PERFORMANCE_DATA,
83     name_CURRENT_CONFIG,
84     name_DYN_DATA
85 };
86
87
88 /* check if value type needs string conversion (Ansi<->Unicode) */
89 static inline int is_string( DWORD type )
90 {
91     return (type == REG_SZ) || (type == REG_EXPAND_SZ) || (type == REG_MULTI_SZ);
92 }
93
94 /* check if current version is NT or Win95 */
95 static inline int is_version_nt(void)
96 {
97     return !(GetVersion() & 0x80000000);
98 }
99
100 /* create one of the HKEY_* special root keys */
101 static HKEY create_special_root_hkey( HANDLE hkey, DWORD access )
102 {
103     HKEY ret = 0;
104     int idx = (UINT_PTR)hkey - (UINT_PTR)HKEY_SPECIAL_ROOT_FIRST;
105
106     if (hkey == HKEY_CURRENT_USER)
107     {
108         if (RtlOpenCurrentUser( access, &hkey )) return 0;
109         TRACE( "HKEY_CURRENT_USER -> %p\n", hkey );
110
111         /* don't cache the key in the table if caching is disabled */
112         if (hkcu_cache_disabled)
113             return hkey;
114     }
115     else
116     {
117         OBJECT_ATTRIBUTES attr;
118         UNICODE_STRING name;
119
120         attr.Length = sizeof(attr);
121         attr.RootDirectory = 0;
122         attr.ObjectName = &name;
123         attr.Attributes = 0;
124         attr.SecurityDescriptor = NULL;
125         attr.SecurityQualityOfService = NULL;
126         RtlInitUnicodeString( &name, root_key_names[idx] );
127         if (NtCreateKey( &hkey, access, &attr, 0, NULL, 0, NULL )) return 0;
128         TRACE( "%s -> %p\n", debugstr_w(attr.ObjectName->Buffer), hkey );
129     }
130
131     if (!(ret = InterlockedCompareExchangePointer( (void **)&special_root_keys[idx], hkey, 0 )))
132         ret = hkey;
133     else
134         NtClose( hkey );  /* somebody beat us to it */
135     return ret;
136 }
137
138 /* map the hkey from special root to normal key if necessary */
139 static inline HKEY get_special_root_hkey( HKEY hkey )
140 {
141     HKEY ret = hkey;
142
143     if ((hkey >= HKEY_SPECIAL_ROOT_FIRST) && (hkey <= HKEY_SPECIAL_ROOT_LAST))
144     {
145         if (!(ret = special_root_keys[(UINT_PTR)hkey - (UINT_PTR)HKEY_SPECIAL_ROOT_FIRST]))
146             ret = create_special_root_hkey( hkey, KEY_ALL_ACCESS );
147     }
148     return ret;
149 }
150
151
152 /******************************************************************************
153  * RegOverridePredefKey   [ADVAPI32.@]
154  */
155 LSTATUS WINAPI RegOverridePredefKey( HKEY hkey, HKEY override )
156 {
157     HKEY old_key;
158     int idx;
159
160     if ((hkey < HKEY_SPECIAL_ROOT_FIRST) || (hkey > HKEY_SPECIAL_ROOT_LAST))
161         return ERROR_INVALID_PARAMETER;
162     idx = (UINT_PTR)hkey - (UINT_PTR)HKEY_SPECIAL_ROOT_FIRST;
163
164     if (override)
165     {
166         NTSTATUS status = NtDuplicateObject( GetCurrentProcess(), override,
167                                              GetCurrentProcess(), (HANDLE *)&override,
168                                              0, 0, DUPLICATE_SAME_ACCESS );
169         if (status) return RtlNtStatusToDosError( status );
170     }
171
172     old_key = InterlockedExchangePointer( (void **)&special_root_keys[idx], override );
173     if (old_key) NtClose( old_key );
174     return ERROR_SUCCESS;
175 }
176
177
178 /******************************************************************************
179  * RegCreateKeyExW   [ADVAPI32.@]
180  *
181  * See RegCreateKeyExA.
182  */
183 LSTATUS WINAPI RegCreateKeyExW( HKEY hkey, LPCWSTR name, DWORD reserved, LPWSTR class,
184                              DWORD options, REGSAM access, SECURITY_ATTRIBUTES *sa,
185                              PHKEY retkey, LPDWORD dispos )
186 {
187     OBJECT_ATTRIBUTES attr;
188     UNICODE_STRING nameW, classW;
189
190     if (reserved) return ERROR_INVALID_PARAMETER;
191     if (!(access & KEY_ACCESS_MASK) || (access & ~KEY_ACCESS_MASK)) return ERROR_ACCESS_DENIED;
192     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
193
194     attr.Length = sizeof(attr);
195     attr.RootDirectory = hkey;
196     attr.ObjectName = &nameW;
197     attr.Attributes = 0;
198     attr.SecurityDescriptor = NULL;
199     attr.SecurityQualityOfService = NULL;
200     RtlInitUnicodeString( &nameW, name );
201     RtlInitUnicodeString( &classW, class );
202
203     return RtlNtStatusToDosError( NtCreateKey( (PHANDLE)retkey, access, &attr, 0,
204                                                &classW, options, dispos ) );
205 }
206
207
208 /******************************************************************************
209  * RegCreateKeyExA   [ADVAPI32.@]
210  *
211  * Open a registry key, creating it if it doesn't exist.
212  *
213  * PARAMS
214  *  hkey       [I] Handle of the parent registry key
215  *  name       [I] Name of the new key to open or create
216  *  reserved   [I] Reserved, pass 0
217  *  class      [I] The object type of the new key
218  *  options    [I] Flags controlling the key creation (REG_OPTION_* flags from "winnt.h")
219  *  access     [I] Access level desired
220  *  sa         [I] Security attributes for the key
221  *  retkey     [O] Destination for the resulting handle
222  *  dispos     [O] Receives REG_CREATED_NEW_KEY or REG_OPENED_EXISTING_KEY
223  *
224  * RETURNS
225  *  Success: ERROR_SUCCESS.
226  *  Failure: A standard Win32 error code. retkey remains untouched.
227  *
228  * FIXME
229  *  MAXIMUM_ALLOWED in access mask not supported by server
230  */
231 LSTATUS WINAPI RegCreateKeyExA( HKEY hkey, LPCSTR name, DWORD reserved, LPSTR class,
232                              DWORD options, REGSAM access, SECURITY_ATTRIBUTES *sa,
233                              PHKEY retkey, LPDWORD dispos )
234 {
235     OBJECT_ATTRIBUTES attr;
236     UNICODE_STRING classW;
237     ANSI_STRING nameA, classA;
238     NTSTATUS status;
239
240     if (reserved) return ERROR_INVALID_PARAMETER;
241     if (!is_version_nt())
242     {
243         access = KEY_ALL_ACCESS;  /* Win95 ignores the access mask */
244         if (name && *name == '\\') name++; /* win9x,ME ignores one (and only one) beginning backslash */
245     }
246     else if (!(access & KEY_ACCESS_MASK) || (access & ~KEY_ACCESS_MASK)) return ERROR_ACCESS_DENIED;
247     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
248
249     attr.Length = sizeof(attr);
250     attr.RootDirectory = hkey;
251     attr.ObjectName = &NtCurrentTeb()->StaticUnicodeString;
252     attr.Attributes = 0;
253     attr.SecurityDescriptor = NULL;
254     attr.SecurityQualityOfService = NULL;
255     RtlInitAnsiString( &nameA, name );
256     RtlInitAnsiString( &classA, class );
257
258     if (!(status = RtlAnsiStringToUnicodeString( &NtCurrentTeb()->StaticUnicodeString,
259                                                  &nameA, FALSE )))
260     {
261         if (!(status = RtlAnsiStringToUnicodeString( &classW, &classA, TRUE )))
262         {
263             status = NtCreateKey( (PHANDLE)retkey, access, &attr, 0, &classW, options, dispos );
264             RtlFreeUnicodeString( &classW );
265         }
266     }
267     return RtlNtStatusToDosError( status );
268 }
269
270
271 /******************************************************************************
272  * RegCreateKeyW   [ADVAPI32.@]
273  *
274  * Creates the specified reg key.
275  *
276  * PARAMS
277  *  hKey      [I] Handle to an open key.
278  *  lpSubKey  [I] Name of a key that will be opened or created.
279  *  phkResult [O] Receives a handle to the opened or created key.
280  *
281  * RETURNS
282  *  Success: ERROR_SUCCESS
283  *  Failure: nonzero error code defined in Winerror.h
284  */
285 LSTATUS WINAPI RegCreateKeyW( HKEY hkey, LPCWSTR lpSubKey, PHKEY phkResult )
286 {
287     /* FIXME: previous implementation converted ERROR_INVALID_HANDLE to ERROR_BADKEY, */
288     /* but at least my version of NT (4.0 SP5) doesn't do this.  -- AJ */
289     return RegCreateKeyExW( hkey, lpSubKey, 0, NULL, REG_OPTION_NON_VOLATILE,
290                             KEY_ALL_ACCESS, NULL, phkResult, NULL );
291 }
292
293
294 /******************************************************************************
295  * RegCreateKeyA   [ADVAPI32.@]
296  *
297  * See RegCreateKeyW.
298  */
299 LSTATUS WINAPI RegCreateKeyA( HKEY hkey, LPCSTR lpSubKey, PHKEY phkResult )
300 {
301     return RegCreateKeyExA( hkey, lpSubKey, 0, NULL, REG_OPTION_NON_VOLATILE,
302                             KEY_ALL_ACCESS, NULL, phkResult, NULL );
303 }
304
305
306
307 /******************************************************************************
308  * RegOpenKeyExW   [ADVAPI32.@]
309  * 
310  * See RegOpenKeyExA.
311  */
312 LSTATUS WINAPI RegOpenKeyExW( HKEY hkey, LPCWSTR name, DWORD reserved, REGSAM access, PHKEY retkey )
313 {
314     OBJECT_ATTRIBUTES attr;
315     UNICODE_STRING nameW;
316
317     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
318
319     attr.Length = sizeof(attr);
320     attr.RootDirectory = hkey;
321     attr.ObjectName = &nameW;
322     attr.Attributes = 0;
323     attr.SecurityDescriptor = NULL;
324     attr.SecurityQualityOfService = NULL;
325     RtlInitUnicodeString( &nameW, name );
326     return RtlNtStatusToDosError( NtOpenKey( (PHANDLE)retkey, access, &attr ) );
327 }
328
329
330 /******************************************************************************
331  * RegOpenKeyExA   [ADVAPI32.@]
332  *
333  * Open a registry key.
334  *
335  * PARAMS
336  *  hkey       [I] Handle of open key
337  *  name       [I] Name of subkey to open
338  *  reserved   [I] Reserved - must be zero
339  *  access     [I] Security access mask
340  *  retkey     [O] Handle to open key
341  *
342  * RETURNS
343  *  Success: ERROR_SUCCESS
344  *  Failure: A standard Win32 error code. retkey is set to 0.
345  *
346  * NOTES
347  *  Unlike RegCreateKeyExA(), this function will not create the key if it
348  *  does not exist.
349  */
350 LSTATUS WINAPI RegOpenKeyExA( HKEY hkey, LPCSTR name, DWORD reserved, REGSAM access, PHKEY retkey )
351 {
352     OBJECT_ATTRIBUTES attr;
353     STRING nameA;
354     NTSTATUS status;
355
356     if (!is_version_nt()) access = KEY_ALL_ACCESS;  /* Win95 ignores the access mask */
357
358     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
359
360     attr.Length = sizeof(attr);
361     attr.RootDirectory = hkey;
362     attr.ObjectName = &NtCurrentTeb()->StaticUnicodeString;
363     attr.Attributes = 0;
364     attr.SecurityDescriptor = NULL;
365     attr.SecurityQualityOfService = NULL;
366
367     RtlInitAnsiString( &nameA, name );
368     if (!(status = RtlAnsiStringToUnicodeString( &NtCurrentTeb()->StaticUnicodeString,
369                                                  &nameA, FALSE )))
370     {
371         status = NtOpenKey( (PHANDLE)retkey, access, &attr );
372     }
373     return RtlNtStatusToDosError( status );
374 }
375
376
377 /******************************************************************************
378  * RegOpenKeyW   [ADVAPI32.@]
379  *
380  * See RegOpenKeyA.
381  */
382 LSTATUS WINAPI RegOpenKeyW( HKEY hkey, LPCWSTR name, PHKEY retkey )
383 {
384     if (!name || !*name)
385     {
386         *retkey = hkey;
387         return ERROR_SUCCESS;
388     }
389     return RegOpenKeyExW( hkey, name, 0, KEY_ALL_ACCESS, retkey );
390 }
391
392
393 /******************************************************************************
394  * RegOpenKeyA   [ADVAPI32.@]
395  *           
396  * Open a registry key.
397  *
398  * PARAMS
399  *  hkey    [I] Handle of parent key to open the new key under
400  *  name    [I] Name of the key under hkey to open
401  *  retkey  [O] Destination for the resulting Handle
402  *
403  * RETURNS
404  *  Success: ERROR_SUCCESS
405  *  Failure: A standard Win32 error code. retkey is set to 0.
406  */
407 LSTATUS WINAPI RegOpenKeyA( HKEY hkey, LPCSTR name, PHKEY retkey )
408 {
409     if (!name || !*name)
410     {
411         *retkey = hkey;
412         return ERROR_SUCCESS;
413     }
414     return RegOpenKeyExA( hkey, name, 0, KEY_ALL_ACCESS, retkey );
415 }
416
417
418 /******************************************************************************
419  * RegOpenCurrentUser   [ADVAPI32.@]
420  *
421  * Get a handle to the HKEY_CURRENT_USER key for the user 
422  * the current thread is impersonating.
423  *
424  * PARAMS
425  *  access [I] Desired access rights to the key
426  *  retkey [O] Handle to the opened key
427  *
428  * RETURNS
429  *  Success: ERROR_SUCCESS
430  *  Failure: nonzero error code from Winerror.h
431  *
432  * FIXME
433  *  This function is supposed to retrieve a handle to the
434  *  HKEY_CURRENT_USER for the user the current thread is impersonating.
435  *  Since Wine does not currently allow threads to impersonate other users,
436  *  this stub should work fine.
437  */
438 LSTATUS WINAPI RegOpenCurrentUser( REGSAM access, PHKEY retkey )
439 {
440     return RegOpenKeyExA( HKEY_CURRENT_USER, "", 0, access, retkey );
441 }
442
443
444
445 /******************************************************************************
446  * RegEnumKeyExW   [ADVAPI32.@]
447  *
448  * Enumerate subkeys of the specified open registry key.
449  *
450  * PARAMS
451  *  hkey         [I] Handle to key to enumerate
452  *  index        [I] Index of subkey to enumerate
453  *  name         [O] Buffer for subkey name
454  *  name_len     [O] Size of subkey buffer
455  *  reserved     [I] Reserved
456  *  class        [O] Buffer for class string
457  *  class_len    [O] Size of class buffer
458  *  ft           [O] Time key last written to
459  *
460  * RETURNS
461  *  Success: ERROR_SUCCESS
462  *  Failure: System error code. If there are no more subkeys available, the
463  *           function returns ERROR_NO_MORE_ITEMS.
464  */
465 LSTATUS WINAPI RegEnumKeyExW( HKEY hkey, DWORD index, LPWSTR name, LPDWORD name_len,
466                            LPDWORD reserved, LPWSTR class, LPDWORD class_len, FILETIME *ft )
467 {
468     NTSTATUS status;
469     char buffer[256], *buf_ptr = buffer;
470     KEY_NODE_INFORMATION *info = (KEY_NODE_INFORMATION *)buffer;
471     DWORD total_size;
472
473     TRACE( "(%p,%d,%p,%p(%u),%p,%p,%p,%p)\n", hkey, index, name, name_len,
474            name_len ? *name_len : 0, reserved, class, class_len, ft );
475
476     if (reserved) return ERROR_INVALID_PARAMETER;
477     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
478
479     status = NtEnumerateKey( hkey, index, KeyNodeInformation,
480                              buffer, sizeof(buffer), &total_size );
481
482     while (status == STATUS_BUFFER_OVERFLOW)
483     {
484         /* retry with a dynamically allocated buffer */
485         if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
486         if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
487             return ERROR_NOT_ENOUGH_MEMORY;
488         info = (KEY_NODE_INFORMATION *)buf_ptr;
489         status = NtEnumerateKey( hkey, index, KeyNodeInformation,
490                                  buf_ptr, total_size, &total_size );
491     }
492
493     if (!status)
494     {
495         DWORD len = info->NameLength / sizeof(WCHAR);
496         DWORD cls_len = info->ClassLength / sizeof(WCHAR);
497
498         if (ft) *ft = *(FILETIME *)&info->LastWriteTime;
499
500         if (len >= *name_len || (class && class_len && (cls_len >= *class_len)))
501             status = STATUS_BUFFER_OVERFLOW;
502         else
503         {
504             *name_len = len;
505             memcpy( name, info->Name, info->NameLength );
506             name[len] = 0;
507             if (class_len)
508             {
509                 *class_len = cls_len;
510                 if (class)
511                 {
512                     memcpy( class, buf_ptr + info->ClassOffset, info->ClassLength );
513                     class[cls_len] = 0;
514                 }
515             }
516         }
517     }
518
519     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
520     return RtlNtStatusToDosError( status );
521 }
522
523
524 /******************************************************************************
525  * RegEnumKeyExA   [ADVAPI32.@]
526  *
527  * See RegEnumKeyExW.
528  */
529 LSTATUS WINAPI RegEnumKeyExA( HKEY hkey, DWORD index, LPSTR name, LPDWORD name_len,
530                            LPDWORD reserved, LPSTR class, LPDWORD class_len, FILETIME *ft )
531 {
532     NTSTATUS status;
533     char buffer[256], *buf_ptr = buffer;
534     KEY_NODE_INFORMATION *info = (KEY_NODE_INFORMATION *)buffer;
535     DWORD total_size;
536
537     TRACE( "(%p,%d,%p,%p(%u),%p,%p,%p,%p)\n", hkey, index, name, name_len,
538            name_len ? *name_len : 0, reserved, class, class_len, ft );
539
540     if (reserved) return ERROR_INVALID_PARAMETER;
541     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
542
543     status = NtEnumerateKey( hkey, index, KeyNodeInformation,
544                              buffer, sizeof(buffer), &total_size );
545
546     while (status == STATUS_BUFFER_OVERFLOW)
547     {
548         /* retry with a dynamically allocated buffer */
549         if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
550         if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
551             return ERROR_NOT_ENOUGH_MEMORY;
552         info = (KEY_NODE_INFORMATION *)buf_ptr;
553         status = NtEnumerateKey( hkey, index, KeyNodeInformation,
554                                  buf_ptr, total_size, &total_size );
555     }
556
557     if (!status)
558     {
559         DWORD len, cls_len;
560
561         RtlUnicodeToMultiByteSize( &len, info->Name, info->NameLength );
562         RtlUnicodeToMultiByteSize( &cls_len, (WCHAR *)(buf_ptr + info->ClassOffset),
563                                    info->ClassLength );
564         if (ft) *ft = *(FILETIME *)&info->LastWriteTime;
565
566         if (len >= *name_len || (class && class_len && (cls_len >= *class_len)))
567             status = STATUS_BUFFER_OVERFLOW;
568         else
569         {
570             *name_len = len;
571             RtlUnicodeToMultiByteN( name, len, NULL, info->Name, info->NameLength );
572             name[len] = 0;
573             if (class_len)
574             {
575                 *class_len = cls_len;
576                 if (class)
577                 {
578                     RtlUnicodeToMultiByteN( class, cls_len, NULL,
579                                             (WCHAR *)(buf_ptr + info->ClassOffset),
580                                             info->ClassLength );
581                     class[cls_len] = 0;
582                 }
583             }
584         }
585     }
586
587     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
588     return RtlNtStatusToDosError( status );
589 }
590
591
592 /******************************************************************************
593  * RegEnumKeyW   [ADVAPI32.@]
594  *
595  * Enumerates subkeys of the specified open reg key.
596  *
597  * PARAMS
598  *  hKey    [I] Handle to an open key.
599  *  dwIndex [I] Index of the subkey of hKey to retrieve.
600  *  lpName  [O] Name of the subkey.
601  *  cchName [I] Size of lpName in TCHARS.
602  *
603  * RETURNS
604  *  Success: ERROR_SUCCESS
605  *  Failure: system error code. If there are no more subkeys available, the
606  *           function returns ERROR_NO_MORE_ITEMS.
607  */
608 LSTATUS WINAPI RegEnumKeyW( HKEY hkey, DWORD index, LPWSTR name, DWORD name_len )
609 {
610     return RegEnumKeyExW( hkey, index, name, &name_len, NULL, NULL, NULL, NULL );
611 }
612
613
614 /******************************************************************************
615  * RegEnumKeyA   [ADVAPI32.@]
616  *
617  * See RegEnumKeyW.
618  */
619 LSTATUS WINAPI RegEnumKeyA( HKEY hkey, DWORD index, LPSTR name, DWORD name_len )
620 {
621     return RegEnumKeyExA( hkey, index, name, &name_len, NULL, NULL, NULL, NULL );
622 }
623
624
625 /******************************************************************************
626  * RegQueryInfoKeyW   [ADVAPI32.@]
627  *
628  * Retrieves information about the specified registry key.
629  *
630  * PARAMS
631  *    hkey       [I] Handle to key to query
632  *    class      [O] Buffer for class string
633  *    class_len  [O] Size of class string buffer
634  *    reserved   [I] Reserved
635  *    subkeys    [O] Buffer for number of subkeys
636  *    max_subkey [O] Buffer for longest subkey name length
637  *    max_class  [O] Buffer for longest class string length
638  *    values     [O] Buffer for number of value entries
639  *    max_value  [O] Buffer for longest value name length
640  *    max_data   [O] Buffer for longest value data length
641  *    security   [O] Buffer for security descriptor length
642  *    modif      [O] Modification time
643  *
644  * RETURNS
645  *  Success: ERROR_SUCCESS
646  *  Failure: system error code.
647  *
648  * NOTES
649  *  - win95 allows class to be valid and class_len to be NULL
650  *  - winnt returns ERROR_INVALID_PARAMETER if class is valid and class_len is NULL
651  *  - both allow class to be NULL and class_len to be NULL
652  *    (it's hard to test validity, so test !NULL instead)
653  */
654 LSTATUS WINAPI RegQueryInfoKeyW( HKEY hkey, LPWSTR class, LPDWORD class_len, LPDWORD reserved,
655                               LPDWORD subkeys, LPDWORD max_subkey, LPDWORD max_class,
656                               LPDWORD values, LPDWORD max_value, LPDWORD max_data,
657                               LPDWORD security, FILETIME *modif )
658 {
659     NTSTATUS status;
660     char buffer[256], *buf_ptr = buffer;
661     KEY_FULL_INFORMATION *info = (KEY_FULL_INFORMATION *)buffer;
662     DWORD total_size;
663
664     TRACE( "(%p,%p,%d,%p,%p,%p,%p,%p,%p,%p,%p)\n", hkey, class, class_len ? *class_len : 0,
665            reserved, subkeys, max_subkey, values, max_value, max_data, security, modif );
666
667     if (class && !class_len && is_version_nt()) return ERROR_INVALID_PARAMETER;
668     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
669
670     status = NtQueryKey( hkey, KeyFullInformation, buffer, sizeof(buffer), &total_size );
671     if (status && status != STATUS_BUFFER_OVERFLOW) goto done;
672
673     if (class)
674     {
675         /* retry with a dynamically allocated buffer */
676         while (status == STATUS_BUFFER_OVERFLOW)
677         {
678             if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
679             if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
680                 return ERROR_NOT_ENOUGH_MEMORY;
681             info = (KEY_FULL_INFORMATION *)buf_ptr;
682             status = NtQueryKey( hkey, KeyFullInformation, buf_ptr, total_size, &total_size );
683         }
684
685         if (status) goto done;
686
687         if (class_len && (info->ClassLength/sizeof(WCHAR) + 1 > *class_len))
688         {
689             status = STATUS_BUFFER_OVERFLOW;
690         }
691         else
692         {
693             memcpy( class, buf_ptr + info->ClassOffset, info->ClassLength );
694             class[info->ClassLength/sizeof(WCHAR)] = 0;
695         }
696     }
697     else status = STATUS_SUCCESS;
698
699     if (class_len) *class_len = info->ClassLength / sizeof(WCHAR);
700     if (subkeys) *subkeys = info->SubKeys;
701     if (max_subkey) *max_subkey = info->MaxNameLen;
702     if (max_class) *max_class = info->MaxClassLen;
703     if (values) *values = info->Values;
704     if (max_value) *max_value = info->MaxValueNameLen;
705     if (max_data) *max_data = info->MaxValueDataLen;
706     if (modif) *modif = *(FILETIME *)&info->LastWriteTime;
707
708  done:
709     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
710     return RtlNtStatusToDosError( status );
711 }
712
713
714 /******************************************************************************
715  * RegQueryMultipleValuesA   [ADVAPI32.@]
716  *
717  * Retrieves the type and data for a list of value names associated with a key.
718  *
719  * PARAMS
720  *  hKey       [I] Handle to an open key.
721  *  val_list   [O] Array of VALENT structures that describes the entries.
722  *  num_vals   [I] Number of elements in val_list.
723  *  lpValueBuf [O] Pointer to a buffer that receives the data for each value.
724  *  ldwTotsize [I/O] Size of lpValueBuf.
725  *
726  * RETURNS
727  *  Success: ERROR_SUCCESS. ldwTotsize contains num bytes copied.
728  *  Failure: nonzero error code from Winerror.h ldwTotsize contains num needed
729  *           bytes.
730  */
731 LSTATUS WINAPI RegQueryMultipleValuesA( HKEY hkey, PVALENTA val_list, DWORD num_vals,
732                                      LPSTR lpValueBuf, LPDWORD ldwTotsize )
733 {
734     unsigned int i;
735     DWORD maxBytes = *ldwTotsize;
736     HRESULT status;
737     LPSTR bufptr = lpValueBuf;
738     *ldwTotsize = 0;
739
740     TRACE("(%p,%p,%d,%p,%p=%d)\n", hkey, val_list, num_vals, lpValueBuf, ldwTotsize, *ldwTotsize);
741
742     for(i=0; i < num_vals; ++i)
743     {
744
745         val_list[i].ve_valuelen=0;
746         status = RegQueryValueExA(hkey, val_list[i].ve_valuename, NULL, NULL, NULL, &val_list[i].ve_valuelen);
747         if(status != ERROR_SUCCESS)
748         {
749             return status;
750         }
751
752         if(lpValueBuf != NULL && *ldwTotsize + val_list[i].ve_valuelen <= maxBytes)
753         {
754             status = RegQueryValueExA(hkey, val_list[i].ve_valuename, NULL, &val_list[i].ve_type,
755                                       (LPBYTE)bufptr, &val_list[i].ve_valuelen);
756             if(status != ERROR_SUCCESS)
757             {
758                 return status;
759             }
760
761             val_list[i].ve_valueptr = (DWORD_PTR)bufptr;
762
763             bufptr += val_list[i].ve_valuelen;
764         }
765
766         *ldwTotsize += val_list[i].ve_valuelen;
767     }
768     return lpValueBuf != NULL && *ldwTotsize <= maxBytes ? ERROR_SUCCESS : ERROR_MORE_DATA;
769 }
770
771
772 /******************************************************************************
773  * RegQueryMultipleValuesW   [ADVAPI32.@]
774  *
775  * See RegQueryMultipleValuesA.
776  */
777 LSTATUS WINAPI RegQueryMultipleValuesW( HKEY hkey, PVALENTW val_list, DWORD num_vals,
778                                      LPWSTR lpValueBuf, LPDWORD ldwTotsize )
779 {
780     unsigned int i;
781     DWORD maxBytes = *ldwTotsize;
782     HRESULT status;
783     LPSTR bufptr = (LPSTR)lpValueBuf;
784     *ldwTotsize = 0;
785
786     TRACE("(%p,%p,%d,%p,%p=%d)\n", hkey, val_list, num_vals, lpValueBuf, ldwTotsize, *ldwTotsize);
787
788     for(i=0; i < num_vals; ++i)
789     {
790         val_list[i].ve_valuelen=0;
791         status = RegQueryValueExW(hkey, val_list[i].ve_valuename, NULL, NULL, NULL, &val_list[i].ve_valuelen);
792         if(status != ERROR_SUCCESS)
793         {
794             return status;
795         }
796
797         if(lpValueBuf != NULL && *ldwTotsize + val_list[i].ve_valuelen <= maxBytes)
798         {
799             status = RegQueryValueExW(hkey, val_list[i].ve_valuename, NULL, &val_list[i].ve_type,
800                                       (LPBYTE)bufptr, &val_list[i].ve_valuelen);
801             if(status != ERROR_SUCCESS)
802             {
803                 return status;
804             }
805
806             val_list[i].ve_valueptr = (DWORD_PTR)bufptr;
807
808             bufptr += val_list[i].ve_valuelen;
809         }
810
811         *ldwTotsize += val_list[i].ve_valuelen;
812     }
813     return lpValueBuf != NULL && *ldwTotsize <= maxBytes ? ERROR_SUCCESS : ERROR_MORE_DATA;
814 }
815
816 /******************************************************************************
817  * RegQueryInfoKeyA   [ADVAPI32.@]
818  *
819  * Retrieves information about a registry key.
820  *
821  * PARAMS
822  *  hKey                   [I] Handle to an open key.
823  *  lpClass                [O] Class string of the key.
824  *  lpcClass               [I/O] size of lpClass.
825  *  lpReserved             [I] Reserved; must be NULL.
826  *  lpcSubKeys             [O] Number of subkeys contained by the key.
827  *  lpcMaxSubKeyLen        [O] Size of the key's subkey with the longest name.
828  *  lpcMaxClassLen         [O] Size of the longest string specifying a subkey
829  *                             class in TCHARS.
830  *  lpcValues              [O] Number of values associated with the key.
831  *  lpcMaxValueNameLen     [O] Size of the key's longest value name in TCHARS.
832  *  lpcMaxValueLen         [O] Longest data component among the key's values
833  *  lpcbSecurityDescriptor [O] Size of the key's security descriptor.
834  *  lpftLastWriteTime      [O] FILETIME structure that is the last write time.
835  *
836  *  RETURNS
837  *   Success: ERROR_SUCCESS
838  *   Failure: nonzero error code from Winerror.h
839  */
840 LSTATUS WINAPI RegQueryInfoKeyA( HKEY hkey, LPSTR class, LPDWORD class_len, LPDWORD reserved,
841                               LPDWORD subkeys, LPDWORD max_subkey, LPDWORD max_class,
842                               LPDWORD values, LPDWORD max_value, LPDWORD max_data,
843                               LPDWORD security, FILETIME *modif )
844 {
845     NTSTATUS status;
846     char buffer[256], *buf_ptr = buffer;
847     KEY_FULL_INFORMATION *info = (KEY_FULL_INFORMATION *)buffer;
848     DWORD total_size, len;
849
850     TRACE( "(%p,%p,%d,%p,%p,%p,%p,%p,%p,%p,%p)\n", hkey, class, class_len ? *class_len : 0,
851            reserved, subkeys, max_subkey, values, max_value, max_data, security, modif );
852
853     if (class && !class_len && is_version_nt()) return ERROR_INVALID_PARAMETER;
854     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
855
856     status = NtQueryKey( hkey, KeyFullInformation, buffer, sizeof(buffer), &total_size );
857     if (status && status != STATUS_BUFFER_OVERFLOW) goto done;
858
859     if (class || class_len)
860     {
861         /* retry with a dynamically allocated buffer */
862         while (status == STATUS_BUFFER_OVERFLOW)
863         {
864             if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
865             if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
866                 return ERROR_NOT_ENOUGH_MEMORY;
867             info = (KEY_FULL_INFORMATION *)buf_ptr;
868             status = NtQueryKey( hkey, KeyFullInformation, buf_ptr, total_size, &total_size );
869         }
870
871         if (status) goto done;
872
873         RtlUnicodeToMultiByteSize( &len, (WCHAR *)(buf_ptr + info->ClassOffset), info->ClassLength);
874         if (class_len)
875         {
876             if (len + 1 > *class_len) status = STATUS_BUFFER_OVERFLOW;
877             *class_len = len;
878         }
879         if (class && !status)
880         {
881             RtlUnicodeToMultiByteN( class, len, NULL, (WCHAR *)(buf_ptr + info->ClassOffset),
882                                     info->ClassLength );
883             class[len] = 0;
884         }
885     }
886     else status = STATUS_SUCCESS;
887
888     if (subkeys) *subkeys = info->SubKeys;
889     if (max_subkey) *max_subkey = info->MaxNameLen;
890     if (max_class) *max_class = info->MaxClassLen;
891     if (values) *values = info->Values;
892     if (max_value) *max_value = info->MaxValueNameLen;
893     if (max_data) *max_data = info->MaxValueDataLen;
894     if (modif) *modif = *(FILETIME *)&info->LastWriteTime;
895
896  done:
897     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
898     return RtlNtStatusToDosError( status );
899 }
900
901
902 /******************************************************************************
903  * RegCloseKey   [ADVAPI32.@]
904  *
905  * Close an open registry key.
906  *
907  * PARAMS
908  *  hkey [I] Handle of key to close
909  *
910  * RETURNS
911  *  Success: ERROR_SUCCESS
912  *  Failure: Error code
913  */
914 LSTATUS WINAPI RegCloseKey( HKEY hkey )
915 {
916     if (!hkey) return ERROR_INVALID_HANDLE;
917     if (hkey >= (HKEY)0x80000000) return ERROR_SUCCESS;
918     return RtlNtStatusToDosError( NtClose( hkey ) );
919 }
920
921
922 /******************************************************************************
923  * RegDeleteKeyW   [ADVAPI32.@]
924  *
925  * See RegDeleteKeyA.
926  */
927 LSTATUS WINAPI RegDeleteKeyW( HKEY hkey, LPCWSTR name )
928 {
929     DWORD ret;
930     HKEY tmp;
931
932     if (!name) return ERROR_INVALID_PARAMETER;
933
934     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
935
936     if (!(ret = RegOpenKeyExW( hkey, name, 0, DELETE, &tmp )))
937     {
938         ret = RtlNtStatusToDosError( NtDeleteKey( tmp ) );
939         RegCloseKey( tmp );
940     }
941     TRACE("%s ret=%08x\n", debugstr_w(name), ret);
942     return ret;
943 }
944
945
946 /******************************************************************************
947  * RegDeleteKeyA   [ADVAPI32.@]
948  *
949  * Delete a registry key.
950  *
951  * PARAMS
952  *  hkey   [I] Handle to parent key containing the key to delete
953  *  name   [I] Name of the key user hkey to delete
954  *
955  * NOTES
956  *
957  * MSDN is wrong when it says that hkey must be opened with the DELETE access
958  * right. In reality, it opens a new handle with DELETE access.
959  *
960  * RETURNS
961  *  Success: ERROR_SUCCESS
962  *  Failure: Error code
963  */
964 LSTATUS WINAPI RegDeleteKeyA( HKEY hkey, LPCSTR name )
965 {
966     DWORD ret;
967     HKEY tmp;
968
969     if (!name) return ERROR_INVALID_PARAMETER;
970
971     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
972
973     if (!(ret = RegOpenKeyExA( hkey, name, 0, DELETE, &tmp )))
974     {
975         if (!is_version_nt()) /* win95 does recursive key deletes */
976         {
977             CHAR name[MAX_PATH];
978
979             while(!RegEnumKeyA(tmp, 0, name, sizeof(name)))
980             {
981                 if(RegDeleteKeyA(tmp, name))  /* recurse */
982                     break;
983             }
984         }
985         ret = RtlNtStatusToDosError( NtDeleteKey( tmp ) );
986         RegCloseKey( tmp );
987     }
988     TRACE("%s ret=%08x\n", debugstr_a(name), ret);
989     return ret;
990 }
991
992
993
994 /******************************************************************************
995  * RegSetValueExW   [ADVAPI32.@]
996  *
997  * Set the data and contents of a registry value.
998  *
999  * PARAMS
1000  *  hkey       [I] Handle of key to set value for
1001  *  name       [I] Name of value to set
1002  *  reserved   [I] Reserved, must be zero
1003  *  type       [I] Type of the value being set
1004  *  data       [I] The new contents of the value to set
1005  *  count      [I] Size of data
1006  *
1007  * RETURNS
1008  *  Success: ERROR_SUCCESS
1009  *  Failure: Error code
1010  */
1011 LSTATUS WINAPI RegSetValueExW( HKEY hkey, LPCWSTR name, DWORD reserved,
1012                             DWORD type, CONST BYTE *data, DWORD count )
1013 {
1014     UNICODE_STRING nameW;
1015
1016     /* no need for version check, not implemented on win9x anyway */
1017     if (count && is_string(type))
1018     {
1019         LPCWSTR str = (LPCWSTR)data;
1020         /* if user forgot to count terminating null, add it (yes NT does this) */
1021         if (str[count / sizeof(WCHAR) - 1] && !str[count / sizeof(WCHAR)])
1022             count += sizeof(WCHAR);
1023     }
1024     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1025
1026     RtlInitUnicodeString( &nameW, name );
1027     return RtlNtStatusToDosError( NtSetValueKey( hkey, &nameW, 0, type, data, count ) );
1028 }
1029
1030
1031 /******************************************************************************
1032  * RegSetValueExA   [ADVAPI32.@]
1033  *
1034  * See RegSetValueExW.
1035  *
1036  * NOTES
1037  *  win95 does not care about count for REG_SZ and finds out the len by itself (js)
1038  *  NT does definitely care (aj)
1039  */
1040 LSTATUS WINAPI RegSetValueExA( HKEY hkey, LPCSTR name, DWORD reserved, DWORD type,
1041                             CONST BYTE *data, DWORD count )
1042 {
1043     ANSI_STRING nameA;
1044     WCHAR *dataW = NULL;
1045     NTSTATUS status;
1046
1047     if (!is_version_nt())  /* win95 */
1048     {
1049         if (type == REG_SZ)
1050         {
1051             if (!data) return ERROR_INVALID_PARAMETER;
1052             count = strlen((const char *)data) + 1;
1053         }
1054     }
1055     else if (count && is_string(type))
1056     {
1057         /* if user forgot to count terminating null, add it (yes NT does this) */
1058         if (data[count-1] && !data[count]) count++;
1059     }
1060
1061     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1062
1063     if (is_string( type )) /* need to convert to Unicode */
1064     {
1065         DWORD lenW;
1066         RtlMultiByteToUnicodeSize( &lenW, (const char *)data, count );
1067         if (!(dataW = HeapAlloc( GetProcessHeap(), 0, lenW ))) return ERROR_OUTOFMEMORY;
1068         RtlMultiByteToUnicodeN( dataW, lenW, NULL, (const char *)data, count );
1069         count = lenW;
1070         data = (BYTE *)dataW;
1071     }
1072
1073     RtlInitAnsiString( &nameA, name );
1074     if (!(status = RtlAnsiStringToUnicodeString( &NtCurrentTeb()->StaticUnicodeString,
1075                                                  &nameA, FALSE )))
1076     {
1077         status = NtSetValueKey( hkey, &NtCurrentTeb()->StaticUnicodeString, 0, type, data, count );
1078     }
1079     HeapFree( GetProcessHeap(), 0, dataW );
1080     return RtlNtStatusToDosError( status );
1081 }
1082
1083
1084 /******************************************************************************
1085  * RegSetValueW   [ADVAPI32.@]
1086  *
1087  * Sets the data for the default or unnamed value of a reg key.
1088  *
1089  * PARAMS
1090  *  hKey     [I] Handle to an open key.
1091  *  lpSubKey [I] Name of a subkey of hKey.
1092  *  dwType   [I] Type of information to store.
1093  *  lpData   [I] String that contains the data to set for the default value.
1094  *  cbData   [I] Ignored.
1095  *
1096  * RETURNS
1097  *  Success: ERROR_SUCCESS
1098  *  Failure: nonzero error code from Winerror.h
1099  */
1100 LSTATUS WINAPI RegSetValueW( HKEY hkey, LPCWSTR name, DWORD type, LPCWSTR data, DWORD count )
1101 {
1102     HKEY subkey = hkey;
1103     DWORD ret;
1104
1105     TRACE("(%p,%s,%d,%s,%d)\n", hkey, debugstr_w(name), type, debugstr_w(data), count );
1106
1107     if (type != REG_SZ || !data) return ERROR_INVALID_PARAMETER;
1108
1109     if (name && name[0])  /* need to create the subkey */
1110     {
1111         if ((ret = RegCreateKeyW( hkey, name, &subkey )) != ERROR_SUCCESS) return ret;
1112     }
1113
1114     ret = RegSetValueExW( subkey, NULL, 0, REG_SZ, (const BYTE*)data,
1115                           (strlenW( data ) + 1) * sizeof(WCHAR) );
1116     if (subkey != hkey) RegCloseKey( subkey );
1117     return ret;
1118 }
1119
1120
1121 /******************************************************************************
1122  * RegSetValueA   [ADVAPI32.@]
1123  *
1124  * See RegSetValueW.
1125  */
1126 LSTATUS WINAPI RegSetValueA( HKEY hkey, LPCSTR name, DWORD type, LPCSTR data, DWORD count )
1127 {
1128     HKEY subkey = hkey;
1129     DWORD ret;
1130
1131     TRACE("(%p,%s,%d,%s,%d)\n", hkey, debugstr_a(name), type, debugstr_a(data), count );
1132
1133     if (type != REG_SZ || !data) return ERROR_INVALID_PARAMETER;
1134
1135     if (name && name[0])  /* need to create the subkey */
1136     {
1137         if ((ret = RegCreateKeyA( hkey, name, &subkey )) != ERROR_SUCCESS) return ret;
1138     }
1139     ret = RegSetValueExA( subkey, NULL, 0, REG_SZ, (const BYTE*)data, strlen(data)+1 );
1140     if (subkey != hkey) RegCloseKey( subkey );
1141     return ret;
1142 }
1143
1144
1145
1146 /******************************************************************************
1147  * RegQueryValueExW   [ADVAPI32.@]
1148  *
1149  * See RegQueryValueExA.
1150  */
1151 LSTATUS WINAPI RegQueryValueExW( HKEY hkey, LPCWSTR name, LPDWORD reserved, LPDWORD type,
1152                               LPBYTE data, LPDWORD count )
1153 {
1154     NTSTATUS status;
1155     UNICODE_STRING name_str;
1156     DWORD total_size;
1157     char buffer[256], *buf_ptr = buffer;
1158     KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
1159     static const int info_size = offsetof( KEY_VALUE_PARTIAL_INFORMATION, Data );
1160
1161     TRACE("(%p,%s,%p,%p,%p,%p=%d)\n",
1162           hkey, debugstr_w(name), reserved, type, data, count,
1163           (count && data) ? *count : 0 );
1164
1165     if ((data && !count) || reserved) return ERROR_INVALID_PARAMETER;
1166     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1167
1168     RtlInitUnicodeString( &name_str, name );
1169
1170     if (data) total_size = min( sizeof(buffer), *count + info_size );
1171     else
1172     {
1173         total_size = info_size;
1174         if (count) *count = 0;
1175     }
1176
1177     status = NtQueryValueKey( hkey, &name_str, KeyValuePartialInformation,
1178                               buffer, total_size, &total_size );
1179     if (status && status != STATUS_BUFFER_OVERFLOW) goto done;
1180
1181     if (data)
1182     {
1183         /* retry with a dynamically allocated buffer */
1184         while (status == STATUS_BUFFER_OVERFLOW && total_size - info_size <= *count)
1185         {
1186             if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
1187             if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
1188                 return ERROR_NOT_ENOUGH_MEMORY;
1189             info = (KEY_VALUE_PARTIAL_INFORMATION *)buf_ptr;
1190             status = NtQueryValueKey( hkey, &name_str, KeyValuePartialInformation,
1191                                       buf_ptr, total_size, &total_size );
1192         }
1193
1194         if (!status)
1195         {
1196             memcpy( data, buf_ptr + info_size, total_size - info_size );
1197             /* if the type is REG_SZ and data is not 0-terminated
1198              * and there is enough space in the buffer NT appends a \0 */
1199             if (total_size - info_size <= *count-sizeof(WCHAR) && is_string(info->Type))
1200             {
1201                 WCHAR *ptr = (WCHAR *)(data + total_size - info_size);
1202                 if (ptr > (WCHAR *)data && ptr[-1]) *ptr = 0;
1203             }
1204         }
1205         else if (status != STATUS_BUFFER_OVERFLOW) goto done;
1206     }
1207     else status = STATUS_SUCCESS;
1208
1209     if (type) *type = info->Type;
1210     if (count) *count = total_size - info_size;
1211
1212  done:
1213     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
1214     return RtlNtStatusToDosError(status);
1215 }
1216
1217
1218 /******************************************************************************
1219  * RegQueryValueExA   [ADVAPI32.@]
1220  *
1221  * Get the type and contents of a specified value under with a key.
1222  *
1223  * PARAMS
1224  *  hkey      [I]   Handle of the key to query
1225  *  name      [I]   Name of value under hkey to query
1226  *  reserved  [I]   Reserved - must be NULL
1227  *  type      [O]   Destination for the value type, or NULL if not required
1228  *  data      [O]   Destination for the values contents, or NULL if not required
1229  *  count     [I/O] Size of data, updated with the number of bytes returned
1230  *
1231  * RETURNS
1232  *  Success: ERROR_SUCCESS. *count is updated with the number of bytes copied to data.
1233  *  Failure: ERROR_INVALID_HANDLE, if hkey is invalid.
1234  *           ERROR_INVALID_PARAMETER, if any other parameter is invalid.
1235  *           ERROR_MORE_DATA, if on input *count is too small to hold the contents.
1236  *                     
1237  * NOTES
1238  *   MSDN states that if data is too small it is partially filled. In reality 
1239  *   it remains untouched.
1240  */
1241 LSTATUS WINAPI RegQueryValueExA( HKEY hkey, LPCSTR name, LPDWORD reserved, LPDWORD type,
1242                               LPBYTE data, LPDWORD count )
1243 {
1244     NTSTATUS status;
1245     ANSI_STRING nameA;
1246     DWORD total_size, datalen = 0;
1247     char buffer[256], *buf_ptr = buffer;
1248     KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
1249     static const int info_size = offsetof( KEY_VALUE_PARTIAL_INFORMATION, Data );
1250
1251     TRACE("(%p,%s,%p,%p,%p,%p=%d)\n",
1252           hkey, debugstr_a(name), reserved, type, data, count, count ? *count : 0 );
1253
1254     if ((data && !count) || reserved) return ERROR_INVALID_PARAMETER;
1255     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1256
1257     if (count) datalen = *count;
1258     if (!data && count) *count = 0;
1259
1260     /* this matches Win9x behaviour - NT sets *type to a random value */
1261     if (type) *type = REG_NONE;
1262
1263     RtlInitAnsiString( &nameA, name );
1264     if ((status = RtlAnsiStringToUnicodeString( &NtCurrentTeb()->StaticUnicodeString,
1265                                                 &nameA, FALSE )))
1266         return RtlNtStatusToDosError(status);
1267
1268     status = NtQueryValueKey( hkey, &NtCurrentTeb()->StaticUnicodeString,
1269                               KeyValuePartialInformation, buffer, sizeof(buffer), &total_size );
1270     if (status && status != STATUS_BUFFER_OVERFLOW) goto done;
1271
1272     /* we need to fetch the contents for a string type even if not requested,
1273      * because we need to compute the length of the ASCII string. */
1274     if (data || is_string(info->Type))
1275     {
1276         /* retry with a dynamically allocated buffer */
1277         while (status == STATUS_BUFFER_OVERFLOW)
1278         {
1279             if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
1280             if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
1281             {
1282                 status = STATUS_NO_MEMORY;
1283                 goto done;
1284             }
1285             info = (KEY_VALUE_PARTIAL_INFORMATION *)buf_ptr;
1286             status = NtQueryValueKey( hkey, &NtCurrentTeb()->StaticUnicodeString,
1287                                     KeyValuePartialInformation, buf_ptr, total_size, &total_size );
1288         }
1289
1290         if (status) goto done;
1291
1292         if (is_string(info->Type))
1293         {
1294             DWORD len;
1295
1296             RtlUnicodeToMultiByteSize( &len, (WCHAR *)(buf_ptr + info_size),
1297                                        total_size - info_size );
1298             if (data && len)
1299             {
1300                 if (len > datalen) status = STATUS_BUFFER_OVERFLOW;
1301                 else
1302                 {
1303                     RtlUnicodeToMultiByteN( (char*)data, len, NULL, (WCHAR *)(buf_ptr + info_size),
1304                                             total_size - info_size );
1305                     /* if the type is REG_SZ and data is not 0-terminated
1306                      * and there is enough space in the buffer NT appends a \0 */
1307                     if (len < datalen && data[len-1]) data[len] = 0;
1308                 }
1309             }
1310             total_size = len + info_size;
1311         }
1312         else if (data)
1313         {
1314             if (total_size - info_size > datalen) status = STATUS_BUFFER_OVERFLOW;
1315             else memcpy( data, buf_ptr + info_size, total_size - info_size );
1316         }
1317     }
1318     else status = STATUS_SUCCESS;
1319
1320     if (type) *type = info->Type;
1321     if (count) *count = total_size - info_size;
1322
1323  done:
1324     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
1325     return RtlNtStatusToDosError(status);
1326 }
1327
1328
1329 /******************************************************************************
1330  * RegQueryValueW   [ADVAPI32.@]
1331  *
1332  * Retrieves the data associated with the default or unnamed value of a key.
1333  *
1334  * PARAMS
1335  *  hkey      [I] Handle to an open key.
1336  *  name      [I] Name of the subkey of hKey.
1337  *  data      [O] Receives the string associated with the default value
1338  *                of the key.
1339  *  count     [I/O] Size of lpValue in bytes.
1340  *
1341  *  RETURNS
1342  *   Success: ERROR_SUCCESS
1343  *   Failure: nonzero error code from Winerror.h
1344  */
1345 LSTATUS WINAPI RegQueryValueW( HKEY hkey, LPCWSTR name, LPWSTR data, LPLONG count )
1346 {
1347     DWORD ret;
1348     HKEY subkey = hkey;
1349
1350     TRACE("(%p,%s,%p,%d)\n", hkey, debugstr_w(name), data, count ? *count : 0 );
1351
1352     if (name && name[0])
1353     {
1354         if ((ret = RegOpenKeyW( hkey, name, &subkey )) != ERROR_SUCCESS) return ret;
1355     }
1356     ret = RegQueryValueExW( subkey, NULL, NULL, NULL, (LPBYTE)data, (LPDWORD)count );
1357     if (subkey != hkey) RegCloseKey( subkey );
1358     if (ret == ERROR_FILE_NOT_FOUND)
1359     {
1360         /* return empty string if default value not found */
1361         if (data) *data = 0;
1362         if (count) *count = sizeof(WCHAR);
1363         ret = ERROR_SUCCESS;
1364     }
1365     return ret;
1366 }
1367
1368
1369 /******************************************************************************
1370  * RegQueryValueA   [ADVAPI32.@]
1371  *
1372  * See RegQueryValueW.
1373  */
1374 LSTATUS WINAPI RegQueryValueA( HKEY hkey, LPCSTR name, LPSTR data, LPLONG count )
1375 {
1376     DWORD ret;
1377     HKEY subkey = hkey;
1378
1379     TRACE("(%p,%s,%p,%d)\n", hkey, debugstr_a(name), data, count ? *count : 0 );
1380
1381     if (name && name[0])
1382     {
1383         if ((ret = RegOpenKeyA( hkey, name, &subkey )) != ERROR_SUCCESS) return ret;
1384     }
1385     ret = RegQueryValueExA( subkey, NULL, NULL, NULL, (LPBYTE)data, (LPDWORD)count );
1386     if (subkey != hkey) RegCloseKey( subkey );
1387     if (ret == ERROR_FILE_NOT_FOUND)
1388     {
1389         /* return empty string if default value not found */
1390         if (data) *data = 0;
1391         if (count) *count = 1;
1392         ret = ERROR_SUCCESS;
1393     }
1394     return ret;
1395 }
1396
1397
1398 /******************************************************************************
1399  * ADVAPI_ApplyRestrictions   [internal]
1400  *
1401  * Helper function for RegGetValueA/W.
1402  */
1403 static VOID ADVAPI_ApplyRestrictions( DWORD dwFlags, DWORD dwType,
1404                                       DWORD cbData, PLONG ret )
1405 {
1406     /* Check if the type is restricted by the passed flags */
1407     if (*ret == ERROR_SUCCESS || *ret == ERROR_MORE_DATA)
1408     {
1409         DWORD dwMask = 0;
1410
1411         switch (dwType)
1412         {
1413         case REG_NONE: dwMask = RRF_RT_REG_NONE; break;
1414         case REG_SZ: dwMask = RRF_RT_REG_SZ; break;
1415         case REG_EXPAND_SZ: dwMask = RRF_RT_REG_EXPAND_SZ; break;
1416         case REG_MULTI_SZ: dwMask = RRF_RT_REG_MULTI_SZ; break;
1417         case REG_BINARY: dwMask = RRF_RT_REG_BINARY; break;
1418         case REG_DWORD: dwMask = RRF_RT_REG_DWORD; break;
1419         case REG_QWORD: dwMask = RRF_RT_REG_QWORD; break;
1420         }
1421
1422         if (dwFlags & dwMask)
1423         {
1424             /* Type is not restricted, check for size mismatch */
1425             if (dwType == REG_BINARY)
1426             {
1427                 DWORD cbExpect = 0;
1428
1429                 if ((dwFlags & RRF_RT_DWORD) == RRF_RT_DWORD)
1430                     cbExpect = 4;
1431                 else if ((dwFlags & RRF_RT_QWORD) == RRF_RT_QWORD)
1432                     cbExpect = 8;
1433
1434                 if (cbExpect && cbData != cbExpect)
1435                     *ret = ERROR_DATATYPE_MISMATCH;
1436             }
1437         }
1438         else *ret = ERROR_UNSUPPORTED_TYPE;
1439     }
1440 }
1441
1442
1443 /******************************************************************************
1444  * RegGetValueW   [ADVAPI32.@]
1445  *
1446  * Retrieves the type and data for a value name associated with a key,
1447  * optionally expanding its content and restricting its type.
1448  *
1449  * PARAMS
1450  *  hKey      [I] Handle to an open key.
1451  *  pszSubKey [I] Name of the subkey of hKey.
1452  *  pszValue  [I] Name of value under hKey/szSubKey to query.
1453  *  dwFlags   [I] Flags restricting the value type to retrieve.
1454  *  pdwType   [O] Destination for the values type, may be NULL.
1455  *  pvData    [O] Destination for the values content, may be NULL.
1456  *  pcbData   [I/O] Size of pvData, updated with the size in bytes required to
1457  *                  retrieve the whole content, including the trailing '\0'
1458  *                  for strings.
1459  *
1460  * RETURNS
1461  *  Success: ERROR_SUCCESS
1462  *  Failure: nonzero error code from Winerror.h
1463  *
1464  * NOTES
1465  *  - Unless RRF_NOEXPAND is specified, REG_EXPAND_SZ values are automatically
1466  *    expanded and pdwType is set to REG_SZ instead.
1467  *  - Restrictions are applied after expanding, using RRF_RT_REG_EXPAND_SZ 
1468  *    without RRF_NOEXPAND is thus not allowed.
1469  *    An exception is the case where RRF_RT_ANY is specified, because then
1470  *    RRF_NOEXPAND is allowed.
1471  */
1472 LSTATUS WINAPI RegGetValueW( HKEY hKey, LPCWSTR pszSubKey, LPCWSTR pszValue,
1473                           DWORD dwFlags, LPDWORD pdwType, PVOID pvData,
1474                           LPDWORD pcbData )
1475 {
1476     DWORD dwType, cbData = pcbData ? *pcbData : 0;
1477     PVOID pvBuf = NULL;
1478     LONG ret;
1479
1480     TRACE("(%p,%s,%s,%d,%p,%p,%p=%d)\n", 
1481           hKey, debugstr_w(pszSubKey), debugstr_w(pszValue), dwFlags, pdwType,
1482           pvData, pcbData, cbData);
1483
1484     if (pvData && !pcbData)
1485         return ERROR_INVALID_PARAMETER;
1486     if ((dwFlags & RRF_RT_REG_EXPAND_SZ) && !(dwFlags & RRF_NOEXPAND) &&
1487             ((dwFlags & RRF_RT_ANY) != RRF_RT_ANY))
1488         return ERROR_INVALID_PARAMETER;
1489
1490     if (pszSubKey && pszSubKey[0])
1491     {
1492         ret = RegOpenKeyExW(hKey, pszSubKey, 0, KEY_QUERY_VALUE, &hKey);
1493         if (ret != ERROR_SUCCESS) return ret;
1494     }
1495
1496     ret = RegQueryValueExW(hKey, pszValue, NULL, &dwType, pvData, &cbData);
1497     
1498     /* If we are going to expand we need to read in the whole the value even
1499      * if the passed buffer was too small as the expanded string might be
1500      * smaller than the unexpanded one and could fit into cbData bytes. */
1501     if ((ret == ERROR_SUCCESS || ret == ERROR_MORE_DATA) &&
1502         dwType == REG_EXPAND_SZ && !(dwFlags & RRF_NOEXPAND))
1503     {
1504         do {
1505             HeapFree(GetProcessHeap(), 0, pvBuf);
1506             
1507             pvBuf = HeapAlloc(GetProcessHeap(), 0, cbData);
1508             if (!pvBuf)
1509             {
1510                 ret = ERROR_NOT_ENOUGH_MEMORY;
1511                 break;
1512             }
1513
1514             if (ret == ERROR_MORE_DATA || !pvData)
1515                 ret = RegQueryValueExW(hKey, pszValue, NULL, 
1516                                        &dwType, pvBuf, &cbData);
1517             else
1518             {
1519                 /* Even if cbData was large enough we have to copy the 
1520                  * string since ExpandEnvironmentStrings can't handle
1521                  * overlapping buffers. */
1522                 CopyMemory(pvBuf, pvData, cbData);
1523             }
1524
1525             /* Both the type or the value itself could have been modified in
1526              * between so we have to keep retrying until the buffer is large
1527              * enough or we no longer have to expand the value. */
1528         } while (dwType == REG_EXPAND_SZ && ret == ERROR_MORE_DATA);
1529
1530         if (ret == ERROR_SUCCESS)
1531         {
1532             /* Recheck dwType in case it changed since the first call */
1533             if (dwType == REG_EXPAND_SZ)
1534             {
1535                 cbData = ExpandEnvironmentStringsW(pvBuf, pvData,
1536                                                    pcbData ? *pcbData : 0) * sizeof(WCHAR);
1537                 dwType = REG_SZ;
1538                 if(pvData && pcbData && cbData > *pcbData)
1539                     ret = ERROR_MORE_DATA;
1540             }
1541             else if (pvData)
1542                 CopyMemory(pvData, pvBuf, *pcbData);
1543         }
1544
1545         HeapFree(GetProcessHeap(), 0, pvBuf);
1546     }
1547
1548     if (pszSubKey && pszSubKey[0])
1549         RegCloseKey(hKey);
1550
1551     ADVAPI_ApplyRestrictions(dwFlags, dwType, cbData, &ret);
1552
1553     if (pvData && ret != ERROR_SUCCESS && (dwFlags & RRF_ZEROONFAILURE))
1554         ZeroMemory(pvData, *pcbData);
1555
1556     if (pdwType) *pdwType = dwType;
1557     if (pcbData) *pcbData = cbData;
1558
1559     return ret;
1560 }
1561
1562
1563 /******************************************************************************
1564  * RegGetValueA   [ADVAPI32.@]
1565  *
1566  * See RegGetValueW.
1567  */
1568 LSTATUS WINAPI RegGetValueA( HKEY hKey, LPCSTR pszSubKey, LPCSTR pszValue,
1569                           DWORD dwFlags, LPDWORD pdwType, PVOID pvData, 
1570                           LPDWORD pcbData )
1571 {
1572     DWORD dwType, cbData = pcbData ? *pcbData : 0;
1573     PVOID pvBuf = NULL;
1574     LONG ret;
1575
1576     TRACE("(%p,%s,%s,%d,%p,%p,%p=%d)\n", 
1577           hKey, pszSubKey, pszValue, dwFlags, pdwType, pvData, pcbData,
1578           cbData);
1579
1580     if (pvData && !pcbData)
1581         return ERROR_INVALID_PARAMETER;
1582     if ((dwFlags & RRF_RT_REG_EXPAND_SZ) && !(dwFlags & RRF_NOEXPAND) &&
1583             ((dwFlags & RRF_RT_ANY) != RRF_RT_ANY))
1584         return ERROR_INVALID_PARAMETER;
1585
1586     if (pszSubKey && pszSubKey[0])
1587     {
1588         ret = RegOpenKeyExA(hKey, pszSubKey, 0, KEY_QUERY_VALUE, &hKey);
1589         if (ret != ERROR_SUCCESS) return ret;
1590     }
1591
1592     ret = RegQueryValueExA(hKey, pszValue, NULL, &dwType, pvData, &cbData);
1593
1594     /* If we are going to expand we need to read in the whole the value even
1595      * if the passed buffer was too small as the expanded string might be
1596      * smaller than the unexpanded one and could fit into cbData bytes. */
1597     if ((ret == ERROR_SUCCESS || ret == ERROR_MORE_DATA) &&
1598         dwType == REG_EXPAND_SZ && !(dwFlags & RRF_NOEXPAND))
1599     {
1600         do {
1601             HeapFree(GetProcessHeap(), 0, pvBuf);
1602
1603             pvBuf = HeapAlloc(GetProcessHeap(), 0, cbData);
1604             if (!pvBuf)
1605             {
1606                 ret = ERROR_NOT_ENOUGH_MEMORY;
1607                 break;
1608             }
1609
1610             if (ret == ERROR_MORE_DATA || !pvData)
1611                 ret = RegQueryValueExA(hKey, pszValue, NULL, 
1612                                        &dwType, pvBuf, &cbData);
1613             else
1614             {
1615                 /* Even if cbData was large enough we have to copy the 
1616                  * string since ExpandEnvironmentStrings can't handle
1617                  * overlapping buffers. */
1618                 CopyMemory(pvBuf, pvData, cbData);
1619             }
1620
1621             /* Both the type or the value itself could have been modified in
1622              * between so we have to keep retrying until the buffer is large
1623              * enough or we no longer have to expand the value. */
1624         } while (dwType == REG_EXPAND_SZ && ret == ERROR_MORE_DATA);
1625
1626         if (ret == ERROR_SUCCESS)
1627         {
1628             /* Recheck dwType in case it changed since the first call */
1629             if (dwType == REG_EXPAND_SZ)
1630             {
1631                 cbData = ExpandEnvironmentStringsA(pvBuf, pvData,
1632                                                    pcbData ? *pcbData : 0);
1633                 dwType = REG_SZ;
1634                 if(pvData && pcbData && cbData > *pcbData)
1635                     ret = ERROR_MORE_DATA;
1636             }
1637             else if (pvData)
1638                 CopyMemory(pvData, pvBuf, *pcbData);
1639         }
1640
1641         HeapFree(GetProcessHeap(), 0, pvBuf);
1642     }
1643
1644     if (pszSubKey && pszSubKey[0])
1645         RegCloseKey(hKey);
1646
1647     ADVAPI_ApplyRestrictions(dwFlags, dwType, cbData, &ret);
1648
1649     if (pvData && ret != ERROR_SUCCESS && (dwFlags & RRF_ZEROONFAILURE))
1650         ZeroMemory(pvData, *pcbData);
1651
1652     if (pdwType) *pdwType = dwType;
1653     if (pcbData) *pcbData = cbData;
1654
1655     return ret;
1656 }
1657
1658
1659 /******************************************************************************
1660  * RegEnumValueW   [ADVAPI32.@]
1661  *
1662  * Enumerates the values for the specified open registry key.
1663  *
1664  * PARAMS
1665  *  hkey       [I] Handle to key to query
1666  *  index      [I] Index of value to query
1667  *  value      [O] Value string
1668  *  val_count  [I/O] Size of value buffer (in wchars)
1669  *  reserved   [I] Reserved
1670  *  type       [O] Type code
1671  *  data       [O] Value data
1672  *  count      [I/O] Size of data buffer (in bytes)
1673  *
1674  * RETURNS
1675  *  Success: ERROR_SUCCESS
1676  *  Failure: nonzero error code from Winerror.h
1677  */
1678
1679 LSTATUS WINAPI RegEnumValueW( HKEY hkey, DWORD index, LPWSTR value, LPDWORD val_count,
1680                            LPDWORD reserved, LPDWORD type, LPBYTE data, LPDWORD count )
1681 {
1682     NTSTATUS status;
1683     DWORD total_size;
1684     char buffer[256], *buf_ptr = buffer;
1685     KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
1686     static const int info_size = offsetof( KEY_VALUE_FULL_INFORMATION, Name );
1687
1688     TRACE("(%p,%d,%p,%p,%p,%p,%p,%p)\n",
1689           hkey, index, value, val_count, reserved, type, data, count );
1690
1691     /* NT only checks count, not val_count */
1692     if ((data && !count) || reserved) return ERROR_INVALID_PARAMETER;
1693     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1694
1695     total_size = info_size + (MAX_PATH + 1) * sizeof(WCHAR);
1696     if (data) total_size += *count;
1697     total_size = min( sizeof(buffer), total_size );
1698
1699     status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
1700                                   buffer, total_size, &total_size );
1701     if (status && status != STATUS_BUFFER_OVERFLOW) goto done;
1702
1703     if (value || data)
1704     {
1705         /* retry with a dynamically allocated buffer */
1706         while (status == STATUS_BUFFER_OVERFLOW)
1707         {
1708             if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
1709             if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
1710                 return ERROR_NOT_ENOUGH_MEMORY;
1711             info = (KEY_VALUE_FULL_INFORMATION *)buf_ptr;
1712             status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
1713                                           buf_ptr, total_size, &total_size );
1714         }
1715
1716         if (status) goto done;
1717
1718         if (value)
1719         {
1720             if (info->NameLength/sizeof(WCHAR) >= *val_count)
1721             {
1722                 status = STATUS_BUFFER_OVERFLOW;
1723                 goto overflow;
1724             }
1725             memcpy( value, info->Name, info->NameLength );
1726             *val_count = info->NameLength / sizeof(WCHAR);
1727             value[*val_count] = 0;
1728         }
1729
1730         if (data)
1731         {
1732             if (total_size - info->DataOffset > *count)
1733             {
1734                 status = STATUS_BUFFER_OVERFLOW;
1735                 goto overflow;
1736             }
1737             memcpy( data, buf_ptr + info->DataOffset, total_size - info->DataOffset );
1738             if (total_size - info->DataOffset <= *count-sizeof(WCHAR) && is_string(info->Type))
1739             {
1740                 /* if the type is REG_SZ and data is not 0-terminated
1741                  * and there is enough space in the buffer NT appends a \0 */
1742                 WCHAR *ptr = (WCHAR *)(data + total_size - info->DataOffset);
1743                 if (ptr > (WCHAR *)data && ptr[-1]) *ptr = 0;
1744             }
1745         }
1746     }
1747     else status = STATUS_SUCCESS;
1748
1749  overflow:
1750     if (type) *type = info->Type;
1751     if (count) *count = info->DataLength;
1752
1753  done:
1754     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
1755     return RtlNtStatusToDosError(status);
1756 }
1757
1758
1759 /******************************************************************************
1760  * RegEnumValueA   [ADVAPI32.@]
1761  *
1762  * See RegEnumValueW.
1763  */
1764 LSTATUS WINAPI RegEnumValueA( HKEY hkey, DWORD index, LPSTR value, LPDWORD val_count,
1765                            LPDWORD reserved, LPDWORD type, LPBYTE data, LPDWORD count )
1766 {
1767     NTSTATUS status;
1768     DWORD total_size;
1769     char buffer[256], *buf_ptr = buffer;
1770     KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
1771     static const int info_size = offsetof( KEY_VALUE_FULL_INFORMATION, Name );
1772
1773     TRACE("(%p,%d,%p,%p,%p,%p,%p,%p)\n",
1774           hkey, index, value, val_count, reserved, type, data, count );
1775
1776     /* NT only checks count, not val_count */
1777     if ((data && !count) || reserved) return ERROR_INVALID_PARAMETER;
1778     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1779
1780     total_size = info_size + (MAX_PATH + 1) * sizeof(WCHAR);
1781     if (data) total_size += *count;
1782     total_size = min( sizeof(buffer), total_size );
1783
1784     status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
1785                                   buffer, total_size, &total_size );
1786     if (status && status != STATUS_BUFFER_OVERFLOW) goto done;
1787
1788     /* we need to fetch the contents for a string type even if not requested,
1789      * because we need to compute the length of the ASCII string. */
1790     if (value || data || is_string(info->Type))
1791     {
1792         /* retry with a dynamically allocated buffer */
1793         while (status == STATUS_BUFFER_OVERFLOW)
1794         {
1795             if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
1796             if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
1797                 return ERROR_NOT_ENOUGH_MEMORY;
1798             info = (KEY_VALUE_FULL_INFORMATION *)buf_ptr;
1799             status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
1800                                           buf_ptr, total_size, &total_size );
1801         }
1802
1803         if (status) goto done;
1804
1805         if (is_string(info->Type))
1806         {
1807             DWORD len;
1808             RtlUnicodeToMultiByteSize( &len, (WCHAR *)(buf_ptr + info->DataOffset),
1809                                        total_size - info->DataOffset );
1810             if (data && len)
1811             {
1812                 if (len > *count) status = STATUS_BUFFER_OVERFLOW;
1813                 else
1814                 {
1815                     RtlUnicodeToMultiByteN( (char*)data, len, NULL, (WCHAR *)(buf_ptr + info->DataOffset),
1816                                             total_size - info->DataOffset );
1817                     /* if the type is REG_SZ and data is not 0-terminated
1818                      * and there is enough space in the buffer NT appends a \0 */
1819                     if (len < *count && data[len-1]) data[len] = 0;
1820                 }
1821             }
1822             info->DataLength = len;
1823         }
1824         else if (data)
1825         {
1826             if (total_size - info->DataOffset > *count) status = STATUS_BUFFER_OVERFLOW;
1827             else memcpy( data, buf_ptr + info->DataOffset, total_size - info->DataOffset );
1828         }
1829
1830         if (value && !status)
1831         {
1832             DWORD len;
1833
1834             RtlUnicodeToMultiByteSize( &len, info->Name, info->NameLength );
1835             if (len >= *val_count)
1836             {
1837                 status = STATUS_BUFFER_OVERFLOW;
1838                 if (*val_count)
1839                 {
1840                     len = *val_count - 1;
1841                     RtlUnicodeToMultiByteN( value, len, NULL, info->Name, info->NameLength );
1842                     value[len] = 0;
1843                 }
1844             }
1845             else
1846             {
1847                 RtlUnicodeToMultiByteN( value, len, NULL, info->Name, info->NameLength );
1848                 value[len] = 0;
1849                 *val_count = len;
1850             }
1851         }
1852     }
1853     else status = STATUS_SUCCESS;
1854
1855     if (type) *type = info->Type;
1856     if (count) *count = info->DataLength;
1857
1858  done:
1859     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
1860     return RtlNtStatusToDosError(status);
1861 }
1862
1863
1864
1865 /******************************************************************************
1866  * RegDeleteValueW   [ADVAPI32.@]
1867  *
1868  * See RegDeleteValueA.
1869  */
1870 LSTATUS WINAPI RegDeleteValueW( HKEY hkey, LPCWSTR name )
1871 {
1872     UNICODE_STRING nameW;
1873
1874     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1875
1876     RtlInitUnicodeString( &nameW, name );
1877     return RtlNtStatusToDosError( NtDeleteValueKey( hkey, &nameW ) );
1878 }
1879
1880
1881 /******************************************************************************
1882  * RegDeleteValueA   [ADVAPI32.@]
1883  *
1884  * Delete a value from the registry.
1885  *
1886  * PARAMS
1887  *  hkey [I] Registry handle of the key holding the value
1888  *  name [I] Name of the value under hkey to delete
1889  *
1890  * RETURNS
1891  *  Success: ERROR_SUCCESS
1892  *  Failure: nonzero error code from Winerror.h
1893  */
1894 LSTATUS WINAPI RegDeleteValueA( HKEY hkey, LPCSTR name )
1895 {
1896     STRING nameA;
1897     NTSTATUS status;
1898
1899     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1900
1901     RtlInitAnsiString( &nameA, name );
1902     if (!(status = RtlAnsiStringToUnicodeString( &NtCurrentTeb()->StaticUnicodeString,
1903                                                  &nameA, FALSE )))
1904         status = NtDeleteValueKey( hkey, &NtCurrentTeb()->StaticUnicodeString );
1905     return RtlNtStatusToDosError( status );
1906 }
1907
1908
1909 /******************************************************************************
1910  * RegLoadKeyW   [ADVAPI32.@]
1911  *
1912  * Create a subkey under HKEY_USERS or HKEY_LOCAL_MACHINE and store
1913  * registration information from a specified file into that subkey.
1914  *
1915  * PARAMS
1916  *  hkey      [I] Handle of open key
1917  *  subkey    [I] Address of name of subkey
1918  *  filename  [I] Address of filename for registry information
1919  *
1920  * RETURNS
1921  *  Success: ERROR_SUCCESS
1922  *  Failure: nonzero error code from Winerror.h
1923  */
1924 LSTATUS WINAPI RegLoadKeyW( HKEY hkey, LPCWSTR subkey, LPCWSTR filename )
1925 {
1926     OBJECT_ATTRIBUTES destkey, file;
1927     UNICODE_STRING subkeyW, filenameW;
1928     NTSTATUS status;
1929
1930     if (!(hkey = get_special_root_hkey(hkey))) return ERROR_INVALID_HANDLE;
1931
1932     destkey.Length = sizeof(destkey);
1933     destkey.RootDirectory = hkey;               /* root key: HKLM or HKU */
1934     destkey.ObjectName = &subkeyW;              /* name of the key */
1935     destkey.Attributes = 0;
1936     destkey.SecurityDescriptor = NULL;
1937     destkey.SecurityQualityOfService = NULL;
1938     RtlInitUnicodeString(&subkeyW, subkey);
1939
1940     file.Length = sizeof(file);
1941     file.RootDirectory = NULL;
1942     file.ObjectName = &filenameW;               /* file containing the hive */
1943     file.Attributes = OBJ_CASE_INSENSITIVE;
1944     file.SecurityDescriptor = NULL;
1945     file.SecurityQualityOfService = NULL;
1946     RtlDosPathNameToNtPathName_U(filename, &filenameW, NULL, NULL);
1947
1948     status = NtLoadKey(&destkey, &file);
1949     RtlFreeUnicodeString(&filenameW);
1950     return RtlNtStatusToDosError( status );
1951 }
1952
1953
1954 /******************************************************************************
1955  * RegLoadKeyA   [ADVAPI32.@]
1956  *
1957  * See RegLoadKeyW.
1958  */
1959 LSTATUS WINAPI RegLoadKeyA( HKEY hkey, LPCSTR subkey, LPCSTR filename )
1960 {
1961     UNICODE_STRING subkeyW, filenameW;
1962     STRING subkeyA, filenameA;
1963     NTSTATUS status;
1964     LONG ret;
1965
1966     RtlInitAnsiString(&subkeyA, subkey);
1967     RtlInitAnsiString(&filenameA, filename);
1968
1969     RtlInitUnicodeString(&subkeyW, NULL);
1970     RtlInitUnicodeString(&filenameW, NULL);
1971     if (!(status = RtlAnsiStringToUnicodeString(&subkeyW, &subkeyA, TRUE)) &&
1972         !(status = RtlAnsiStringToUnicodeString(&filenameW, &filenameA, TRUE)))
1973     {
1974         ret = RegLoadKeyW(hkey, subkeyW.Buffer, filenameW.Buffer);
1975     }
1976     else ret = RtlNtStatusToDosError(status);
1977     RtlFreeUnicodeString(&subkeyW);
1978     RtlFreeUnicodeString(&filenameW);
1979     return ret;
1980 }
1981
1982
1983 /******************************************************************************
1984  * RegSaveKeyW   [ADVAPI32.@]
1985  *
1986  * Save a key and all of its subkeys and values to a new file in the standard format.
1987  *
1988  * PARAMS
1989  *  hkey   [I] Handle of key where save begins
1990  *  lpFile [I] Address of filename to save to
1991  *  sa     [I] Address of security structure
1992  *
1993  * RETURNS
1994  *  Success: ERROR_SUCCESS
1995  *  Failure: nonzero error code from Winerror.h
1996  */
1997 LSTATUS WINAPI RegSaveKeyW( HKEY hkey, LPCWSTR file, LPSECURITY_ATTRIBUTES sa )
1998 {
1999     static const WCHAR format[] =
2000         {'r','e','g','%','0','4','x','.','t','m','p',0};
2001     WCHAR buffer[MAX_PATH];
2002     int count = 0;
2003     LPWSTR nameW;
2004     DWORD ret, err;
2005     HANDLE handle;
2006
2007     TRACE( "(%p,%s,%p)\n", hkey, debugstr_w(file), sa );
2008
2009     if (!file || !*file) return ERROR_INVALID_PARAMETER;
2010     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
2011
2012     err = GetLastError();
2013     GetFullPathNameW( file, sizeof(buffer)/sizeof(WCHAR), buffer, &nameW );
2014
2015     for (;;)
2016     {
2017         snprintfW( nameW, 16, format, count++ );
2018         handle = CreateFileW( buffer, GENERIC_WRITE, 0, NULL,
2019                             CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
2020         if (handle != INVALID_HANDLE_VALUE) break;
2021         if ((ret = GetLastError()) != ERROR_FILE_EXISTS) goto done;
2022
2023         /* Something gone haywire ? Please report if this happens abnormally */
2024         if (count >= 100)
2025             MESSAGE("Wow, we are already fiddling with a temp file %s with an ordinal as high as %d !\nYou might want to delete all corresponding temp files in that directory.\n", debugstr_w(buffer), count);
2026     }
2027
2028     ret = RtlNtStatusToDosError(NtSaveKey(hkey, handle));
2029
2030     CloseHandle( handle );
2031     if (!ret)
2032     {
2033         if (!MoveFileExW( buffer, file, MOVEFILE_REPLACE_EXISTING ))
2034         {
2035             ERR( "Failed to move %s to %s\n", debugstr_w(buffer),
2036                 debugstr_w(file) );
2037             ret = GetLastError();
2038         }
2039     }
2040     if (ret) DeleteFileW( buffer );
2041
2042 done:
2043     SetLastError( err );  /* restore last error code */
2044     return ret;
2045 }
2046
2047
2048 /******************************************************************************
2049  * RegSaveKeyA  [ADVAPI32.@]
2050  *
2051  * See RegSaveKeyW.
2052  */
2053 LSTATUS WINAPI RegSaveKeyA( HKEY hkey, LPCSTR file, LPSECURITY_ATTRIBUTES sa )
2054 {
2055     UNICODE_STRING *fileW = &NtCurrentTeb()->StaticUnicodeString;
2056     NTSTATUS status;
2057     STRING fileA;
2058
2059     RtlInitAnsiString(&fileA, file);
2060     if ((status = RtlAnsiStringToUnicodeString(fileW, &fileA, FALSE)))
2061         return RtlNtStatusToDosError( status );
2062     return RegSaveKeyW(hkey, fileW->Buffer, sa);
2063 }
2064
2065
2066 /******************************************************************************
2067  * RegRestoreKeyW [ADVAPI32.@]
2068  *
2069  * Read the registry information from a file and copy it over a key.
2070  *
2071  * PARAMS
2072  *  hkey    [I] Handle of key where restore begins
2073  *  lpFile  [I] Address of filename containing saved tree
2074  *  dwFlags [I] Optional flags
2075  *
2076  * RETURNS
2077  *  Success: ERROR_SUCCESS
2078  *  Failure: nonzero error code from Winerror.h
2079  */
2080 LSTATUS WINAPI RegRestoreKeyW( HKEY hkey, LPCWSTR lpFile, DWORD dwFlags )
2081 {
2082     TRACE("(%p,%s,%d)\n",hkey,debugstr_w(lpFile),dwFlags);
2083
2084     /* It seems to do this check before the hkey check */
2085     if (!lpFile || !*lpFile)
2086         return ERROR_INVALID_PARAMETER;
2087
2088     FIXME("(%p,%s,%d): stub\n",hkey,debugstr_w(lpFile),dwFlags);
2089
2090     /* Check for file existence */
2091
2092     return ERROR_SUCCESS;
2093 }
2094
2095
2096 /******************************************************************************
2097  * RegRestoreKeyA [ADVAPI32.@]
2098  *
2099  * See RegRestoreKeyW.
2100  */
2101 LSTATUS WINAPI RegRestoreKeyA( HKEY hkey, LPCSTR lpFile, DWORD dwFlags )
2102 {
2103     UNICODE_STRING lpFileW;
2104     LONG ret;
2105
2106     RtlCreateUnicodeStringFromAsciiz( &lpFileW, lpFile );
2107     ret = RegRestoreKeyW( hkey, lpFileW.Buffer, dwFlags );
2108     RtlFreeUnicodeString( &lpFileW );
2109     return ret;
2110 }
2111
2112
2113 /******************************************************************************
2114  * RegUnLoadKeyW [ADVAPI32.@]
2115  *
2116  * Unload a registry key and its subkeys from the registry.
2117  *
2118  * PARAMS
2119  *  hkey     [I] Handle of open key
2120  *  lpSubKey [I] Address of name of subkey to unload
2121  *
2122  * RETURNS
2123  *  Success: ERROR_SUCCESS
2124  *  Failure: nonzero error code from Winerror.h
2125  */
2126 LSTATUS WINAPI RegUnLoadKeyW( HKEY hkey, LPCWSTR lpSubKey )
2127 {
2128     DWORD ret;
2129     HKEY shkey;
2130     OBJECT_ATTRIBUTES attr;
2131     UNICODE_STRING subkey;
2132
2133     TRACE("(%p,%s)\n",hkey, debugstr_w(lpSubKey));
2134
2135     ret = RegOpenKeyW(hkey,lpSubKey,&shkey);
2136     if( ret )
2137         return ERROR_INVALID_PARAMETER;
2138
2139     RtlInitUnicodeString(&subkey, lpSubKey);
2140     InitializeObjectAttributes(&attr, &subkey, OBJ_CASE_INSENSITIVE, shkey, NULL);
2141     ret = RtlNtStatusToDosError(NtUnloadKey(&attr));
2142
2143     RegCloseKey(shkey);
2144
2145     return ret;
2146 }
2147
2148
2149 /******************************************************************************
2150  * RegUnLoadKeyA [ADVAPI32.@]
2151  *
2152  * See RegUnLoadKeyW.
2153  */
2154 LSTATUS WINAPI RegUnLoadKeyA( HKEY hkey, LPCSTR lpSubKey )
2155 {
2156     UNICODE_STRING lpSubKeyW;
2157     LONG ret;
2158
2159     RtlCreateUnicodeStringFromAsciiz( &lpSubKeyW, lpSubKey );
2160     ret = RegUnLoadKeyW( hkey, lpSubKeyW.Buffer );
2161     RtlFreeUnicodeString( &lpSubKeyW );
2162     return ret;
2163 }
2164
2165
2166 /******************************************************************************
2167  * RegReplaceKeyW [ADVAPI32.@]
2168  *
2169  * Replace the file backing a registry key and all its subkeys with another file.
2170  *
2171  * PARAMS
2172  *  hkey      [I] Handle of open key
2173  *  lpSubKey  [I] Address of name of subkey
2174  *  lpNewFile [I] Address of filename for file with new data
2175  *  lpOldFile [I] Address of filename for backup file
2176  *
2177  * RETURNS
2178  *  Success: ERROR_SUCCESS
2179  *  Failure: nonzero error code from Winerror.h
2180  */
2181 LSTATUS WINAPI RegReplaceKeyW( HKEY hkey, LPCWSTR lpSubKey, LPCWSTR lpNewFile,
2182                               LPCWSTR lpOldFile )
2183 {
2184     FIXME("(%p,%s,%s,%s): stub\n", hkey, debugstr_w(lpSubKey),
2185           debugstr_w(lpNewFile),debugstr_w(lpOldFile));
2186     return ERROR_SUCCESS;
2187 }
2188
2189
2190 /******************************************************************************
2191  * RegReplaceKeyA [ADVAPI32.@]
2192  *
2193  * See RegReplaceKeyW.
2194  */
2195 LSTATUS WINAPI RegReplaceKeyA( HKEY hkey, LPCSTR lpSubKey, LPCSTR lpNewFile,
2196                               LPCSTR lpOldFile )
2197 {
2198     UNICODE_STRING lpSubKeyW;
2199     UNICODE_STRING lpNewFileW;
2200     UNICODE_STRING lpOldFileW;
2201     LONG ret;
2202
2203     RtlCreateUnicodeStringFromAsciiz( &lpSubKeyW, lpSubKey );
2204     RtlCreateUnicodeStringFromAsciiz( &lpOldFileW, lpOldFile );
2205     RtlCreateUnicodeStringFromAsciiz( &lpNewFileW, lpNewFile );
2206     ret = RegReplaceKeyW( hkey, lpSubKeyW.Buffer, lpNewFileW.Buffer, lpOldFileW.Buffer );
2207     RtlFreeUnicodeString( &lpOldFileW );
2208     RtlFreeUnicodeString( &lpNewFileW );
2209     RtlFreeUnicodeString( &lpSubKeyW );
2210     return ret;
2211 }
2212
2213
2214 /******************************************************************************
2215  * RegSetKeySecurity [ADVAPI32.@]
2216  *
2217  * Set the security of an open registry key.
2218  *
2219  * PARAMS
2220  *  hkey          [I] Open handle of key to set
2221  *  SecurityInfo  [I] Descriptor contents
2222  *  pSecurityDesc [I] Address of descriptor for key
2223  *
2224  * RETURNS
2225  *  Success: ERROR_SUCCESS
2226  *  Failure: nonzero error code from Winerror.h
2227  */
2228 LSTATUS WINAPI RegSetKeySecurity( HKEY hkey, SECURITY_INFORMATION SecurityInfo,
2229                                PSECURITY_DESCRIPTOR pSecurityDesc )
2230 {
2231     TRACE("(%p,%d,%p)\n",hkey,SecurityInfo,pSecurityDesc);
2232
2233     /* It seems to perform this check before the hkey check */
2234     if ((SecurityInfo & OWNER_SECURITY_INFORMATION) ||
2235         (SecurityInfo & GROUP_SECURITY_INFORMATION) ||
2236         (SecurityInfo & DACL_SECURITY_INFORMATION) ||
2237         (SecurityInfo & SACL_SECURITY_INFORMATION)) {
2238         /* Param OK */
2239     } else
2240         return ERROR_INVALID_PARAMETER;
2241
2242     if (!pSecurityDesc)
2243         return ERROR_INVALID_PARAMETER;
2244
2245     FIXME(":(%p,%d,%p): stub\n",hkey,SecurityInfo,pSecurityDesc);
2246
2247     return ERROR_SUCCESS;
2248 }
2249
2250
2251 /******************************************************************************
2252  * RegGetKeySecurity [ADVAPI32.@]
2253  *
2254  * Get a copy of the security descriptor for a given registry key.
2255  *
2256  * PARAMS
2257  *  hkey                   [I]   Open handle of key to set
2258  *  SecurityInformation    [I]   Descriptor contents
2259  *  pSecurityDescriptor    [O]   Address of descriptor for key
2260  *  lpcbSecurityDescriptor [I/O] Address of size of buffer and description
2261  *
2262  * RETURNS
2263  *  Success: ERROR_SUCCESS
2264  *  Failure: Error code
2265  */
2266 LSTATUS WINAPI RegGetKeySecurity( HKEY hkey, SECURITY_INFORMATION SecurityInformation,
2267                                PSECURITY_DESCRIPTOR pSecurityDescriptor,
2268                                LPDWORD lpcbSecurityDescriptor )
2269 {
2270     TRACE("(%p,%d,%p,%d)\n",hkey,SecurityInformation,pSecurityDescriptor,
2271           *lpcbSecurityDescriptor);
2272
2273     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
2274
2275     return RtlNtStatusToDosError( NtQuerySecurityObject( hkey,
2276                 SecurityInformation, pSecurityDescriptor,
2277                 *lpcbSecurityDescriptor, lpcbSecurityDescriptor ) );
2278 }
2279
2280
2281 /******************************************************************************
2282  * RegFlushKey [ADVAPI32.@]
2283  * 
2284  * Immediately write a registry key to registry.
2285  *
2286  * PARAMS
2287  *  hkey [I] Handle of key to write
2288  *
2289  * RETURNS
2290  *  Success: ERROR_SUCCESS
2291  *  Failure: Error code
2292  */
2293 LSTATUS WINAPI RegFlushKey( HKEY hkey )
2294 {
2295     hkey = get_special_root_hkey( hkey );
2296     if (!hkey) return ERROR_INVALID_HANDLE;
2297
2298     return RtlNtStatusToDosError( NtFlushKey( hkey ) );
2299 }
2300
2301
2302 /******************************************************************************
2303  * RegConnectRegistryW [ADVAPI32.@]
2304  *
2305  * Establish a connection to a predefined registry key on another computer.
2306  *
2307  * PARAMS
2308  *  lpMachineName [I] Address of name of remote computer
2309  *  hHey          [I] Predefined registry handle
2310  *  phkResult     [I] Address of buffer for remote registry handle
2311  *
2312  * RETURNS
2313  *  Success: ERROR_SUCCESS
2314  *  Failure: nonzero error code from Winerror.h
2315  */
2316 LSTATUS WINAPI RegConnectRegistryW( LPCWSTR lpMachineName, HKEY hKey,
2317                                    PHKEY phkResult )
2318 {
2319     LONG ret;
2320
2321     TRACE("(%s,%p,%p): stub\n",debugstr_w(lpMachineName),hKey,phkResult);
2322
2323     if (!lpMachineName || !*lpMachineName) {
2324         /* Use the local machine name */
2325         ret = RegOpenKeyW( hKey, NULL, phkResult );
2326     }
2327     else {
2328         WCHAR compName[MAX_COMPUTERNAME_LENGTH + 1];
2329         DWORD len = sizeof(compName) / sizeof(WCHAR);
2330
2331         /* MSDN says lpMachineName must start with \\ : not so */
2332         if( lpMachineName[0] == '\\' &&  lpMachineName[1] == '\\')
2333             lpMachineName += 2;
2334         if (GetComputerNameW(compName, &len))
2335         {
2336             if (!strcmpiW(lpMachineName, compName))
2337                 ret = RegOpenKeyW(hKey, NULL, phkResult);
2338             else
2339             {
2340                 FIXME("Connect to %s is not supported.\n",debugstr_w(lpMachineName));
2341                 ret = ERROR_BAD_NETPATH;
2342             }
2343         }
2344         else
2345             ret = GetLastError();
2346     }
2347     return ret;
2348 }
2349
2350
2351 /******************************************************************************
2352  * RegConnectRegistryA [ADVAPI32.@]
2353  *
2354  * See RegConnectRegistryW.
2355  */
2356 LSTATUS WINAPI RegConnectRegistryA( LPCSTR machine, HKEY hkey, PHKEY reskey )
2357 {
2358     UNICODE_STRING machineW;
2359     LONG ret;
2360
2361     RtlCreateUnicodeStringFromAsciiz( &machineW, machine );
2362     ret = RegConnectRegistryW( machineW.Buffer, hkey, reskey );
2363     RtlFreeUnicodeString( &machineW );
2364     return ret;
2365 }
2366
2367
2368 /******************************************************************************
2369  * RegNotifyChangeKeyValue [ADVAPI32.@]
2370  *
2371  * Notify the caller about changes to the attributes or contents of a registry key.
2372  *
2373  * PARAMS
2374  *  hkey            [I] Handle of key to watch
2375  *  fWatchSubTree   [I] Flag for subkey notification
2376  *  fdwNotifyFilter [I] Changes to be reported
2377  *  hEvent          [I] Handle of signaled event
2378  *  fAsync          [I] Flag for asynchronous reporting
2379  *
2380  * RETURNS
2381  *  Success: ERROR_SUCCESS
2382  *  Failure: nonzero error code from Winerror.h
2383  */
2384 LSTATUS WINAPI RegNotifyChangeKeyValue( HKEY hkey, BOOL fWatchSubTree,
2385                                      DWORD fdwNotifyFilter, HANDLE hEvent,
2386                                      BOOL fAsync )
2387 {
2388     NTSTATUS status;
2389     IO_STATUS_BLOCK iosb;
2390
2391     hkey = get_special_root_hkey( hkey );
2392     if (!hkey) return ERROR_INVALID_HANDLE;
2393
2394     TRACE("(%p,%i,%d,%p,%i)\n", hkey, fWatchSubTree, fdwNotifyFilter,
2395           hEvent, fAsync);
2396
2397     status = NtNotifyChangeKey( hkey, hEvent, NULL, NULL, &iosb,
2398                                 fdwNotifyFilter, fAsync, NULL, 0,
2399                                 fWatchSubTree);
2400
2401     if (status && status != STATUS_TIMEOUT)
2402         return RtlNtStatusToDosError( status );
2403
2404     return ERROR_SUCCESS;
2405 }
2406
2407 /******************************************************************************
2408  * RegOpenUserClassesRoot [ADVAPI32.@]
2409  *
2410  * Open the HKEY_CLASSES_ROOT key for a user.
2411  *
2412  * PARAMS
2413  *  hToken     [I] Handle of token representing the user
2414  *  dwOptions  [I] Reserved, must be 0
2415  *  samDesired [I] Desired access rights
2416  *  phkResult  [O] Destination for the resulting key handle
2417  *
2418  * RETURNS
2419  *  Success: ERROR_SUCCESS
2420  *  Failure: nonzero error code from Winerror.h
2421  * 
2422  * NOTES
2423  *  On Windows 2000 and upwards the HKEY_CLASSES_ROOT key is a view of the
2424  *  "HKEY_LOCAL_MACHINE\Software\Classes" and the
2425  *  "HKEY_CURRENT_USER\Software\Classes" keys merged together.
2426  */
2427 LSTATUS WINAPI RegOpenUserClassesRoot(
2428     HANDLE hToken,
2429     DWORD dwOptions,
2430     REGSAM samDesired,
2431     PHKEY phkResult
2432 )
2433 {
2434     FIXME("(%p, 0x%x, 0x%x, %p) semi-stub\n", hToken, dwOptions, samDesired, phkResult);
2435
2436     *phkResult = HKEY_CLASSES_ROOT;
2437     return ERROR_SUCCESS;
2438 }
2439
2440 /******************************************************************************
2441  * load_string [Internal]
2442  *
2443  * This is basically a copy of user32/resource.c's LoadStringW. Necessary to
2444  * avoid importing user32, which is higher level than advapi32. Helper for
2445  * RegLoadMUIString.
2446  */
2447 static int load_string(HINSTANCE hModule, UINT resId, LPWSTR pwszBuffer, INT cMaxChars)
2448 {
2449     HGLOBAL hMemory;
2450     HRSRC hResource;
2451     WCHAR *pString;
2452     int idxString;
2453
2454     /* Negative values have to be inverted. */
2455     if (HIWORD(resId) == 0xffff)
2456         resId = (UINT)(-((INT)resId));
2457
2458     /* Load the resource into memory and get a pointer to it. */
2459     hResource = FindResourceW(hModule, MAKEINTRESOURCEW(LOWORD(resId >> 4) + 1), (LPWSTR)RT_STRING);
2460     if (!hResource) return 0;
2461     hMemory = LoadResource(hModule, hResource);
2462     if (!hMemory) return 0;
2463     pString = LockResource(hMemory);
2464
2465     /* Strings are length-prefixed. Lowest nibble of resId is an index. */
2466     idxString = resId & 0xf;
2467     while (idxString--) pString += *pString + 1;
2468
2469     /* If no buffer is given, return length of the string. */
2470     if (!pwszBuffer) return *pString;
2471
2472     /* Else copy over the string, respecting the buffer size. */
2473     cMaxChars = (*pString < cMaxChars) ? *pString : (cMaxChars - 1);
2474     if (cMaxChars >= 0) {
2475         memcpy(pwszBuffer, pString+1, cMaxChars * sizeof(WCHAR));
2476         pwszBuffer[cMaxChars] = '\0';
2477     }
2478
2479     return cMaxChars;
2480 }
2481
2482 /******************************************************************************
2483  * RegLoadMUIStringW [ADVAPI32.@]
2484  *
2485  * Load the localized version of a string resource from some PE, respective 
2486  * id and path of which are given in the registry value in the format 
2487  * @[path]\dllname,-resourceId
2488  *
2489  * PARAMS
2490  *  hKey       [I] Key, of which to load the string value from.
2491  *  pszValue   [I] The value to be loaded (Has to be of REG_EXPAND_SZ or REG_SZ type).
2492  *  pszBuffer  [O] Buffer to store the localized string in. 
2493  *  cbBuffer   [I] Size of the destination buffer in bytes.
2494  *  pcbData    [O] Number of bytes written to pszBuffer (optional, may be NULL).
2495  *  dwFlags    [I] None supported yet.
2496  *  pszBaseDir [I] Not supported yet.
2497  *
2498  * RETURNS
2499  *  Success: ERROR_SUCCESS,
2500  *  Failure: nonzero error code from winerror.h
2501  *
2502  * NOTES
2503  *  This is an API of Windows Vista, which wasn't available at the time this code
2504  *  was written. We have to check for the correct behaviour once it's available. 
2505  */
2506 LSTATUS WINAPI RegLoadMUIStringW(HKEY hKey, LPCWSTR pwszValue, LPWSTR pwszBuffer, DWORD cbBuffer,
2507     LPDWORD pcbData, DWORD dwFlags, LPCWSTR pwszBaseDir)
2508 {
2509     DWORD dwValueType, cbData;
2510     LPWSTR pwszTempBuffer = NULL, pwszExpandedBuffer = NULL;
2511     LONG result;
2512         
2513     TRACE("(hKey = %p, pwszValue = %s, pwszBuffer = %p, cbBuffer = %d, pcbData = %p, "
2514           "dwFlags = %d, pwszBaseDir = %s) stub\n", hKey, debugstr_w(pwszValue), pwszBuffer, 
2515           cbBuffer, pcbData, dwFlags, debugstr_w(pwszBaseDir));
2516
2517     /* Parameter sanity checks. */
2518     if (!hKey || !pwszBuffer)
2519         return ERROR_INVALID_PARAMETER;
2520
2521     if (pwszBaseDir && *pwszBaseDir) {
2522         FIXME("BaseDir parameter not yet supported!\n");
2523         return ERROR_INVALID_PARAMETER;
2524     }
2525
2526     /* Check for value existence and correctness of it's type, allocate a buffer and load it. */
2527     result = RegQueryValueExW(hKey, pwszValue, NULL, &dwValueType, NULL, &cbData);
2528     if (result != ERROR_SUCCESS) goto cleanup;
2529     if (!(dwValueType == REG_SZ || dwValueType == REG_EXPAND_SZ) || !cbData) {
2530         result = ERROR_FILE_NOT_FOUND;
2531         goto cleanup;
2532     }
2533     pwszTempBuffer = HeapAlloc(GetProcessHeap(), 0, cbData);
2534     if (!pwszTempBuffer) {
2535         result = ERROR_NOT_ENOUGH_MEMORY;
2536         goto cleanup;
2537     }
2538     result = RegQueryValueExW(hKey, pwszValue, NULL, &dwValueType, (LPBYTE)pwszTempBuffer, &cbData);
2539     if (result != ERROR_SUCCESS) goto cleanup;
2540
2541     /* Expand environment variables, if appropriate, or copy the original string over. */
2542     if (dwValueType == REG_EXPAND_SZ) {
2543         cbData = ExpandEnvironmentStringsW(pwszTempBuffer, NULL, 0) * sizeof(WCHAR);
2544         if (!cbData) goto cleanup;
2545         pwszExpandedBuffer = HeapAlloc(GetProcessHeap(), 0, cbData);
2546         if (!pwszExpandedBuffer) {
2547             result = ERROR_NOT_ENOUGH_MEMORY;
2548             goto cleanup;
2549         }
2550         ExpandEnvironmentStringsW(pwszTempBuffer, pwszExpandedBuffer, cbData);
2551     } else {
2552         pwszExpandedBuffer = HeapAlloc(GetProcessHeap(), 0, cbData);
2553         memcpy(pwszExpandedBuffer, pwszTempBuffer, cbData);
2554     }
2555
2556     /* If the value references a resource based string, parse the value and load the string.
2557      * Else just copy over the original value. */
2558     result = ERROR_SUCCESS;
2559     if (*pwszExpandedBuffer != '@') { /* '@' is the prefix for resource based string entries. */
2560         lstrcpynW(pwszBuffer, pwszExpandedBuffer, cbBuffer / sizeof(WCHAR));
2561     } else {
2562         WCHAR *pComma = strrchrW(pwszExpandedBuffer, ',');
2563         UINT uiStringId;
2564         HMODULE hModule;
2565
2566         /* Format of the expanded value is 'path_to_dll,-resId' */
2567         if (!pComma || pComma[1] != '-') {
2568             result = ERROR_BADKEY;
2569             goto cleanup;
2570         }
2571  
2572         uiStringId = atoiW(pComma+2);
2573         *pComma = '\0';
2574
2575         hModule = LoadLibraryW(pwszExpandedBuffer + 1);
2576         if (!hModule || !load_string(hModule, uiStringId, pwszBuffer, cbBuffer/sizeof(WCHAR)))
2577             result = ERROR_BADKEY;
2578         FreeLibrary(hModule);
2579     }
2580  
2581 cleanup:
2582     HeapFree(GetProcessHeap(), 0, pwszTempBuffer);
2583     HeapFree(GetProcessHeap(), 0, pwszExpandedBuffer);
2584     return result;
2585 }
2586
2587 /******************************************************************************
2588  * RegLoadMUIStringA [ADVAPI32.@]
2589  *
2590  * See RegLoadMUIStringW
2591  */
2592 LSTATUS WINAPI RegLoadMUIStringA(HKEY hKey, LPCSTR pszValue, LPSTR pszBuffer, DWORD cbBuffer,
2593     LPDWORD pcbData, DWORD dwFlags, LPCSTR pszBaseDir)
2594 {
2595     UNICODE_STRING valueW, baseDirW;
2596     WCHAR *pwszBuffer;
2597     DWORD cbData = cbBuffer * sizeof(WCHAR);
2598     LONG result;
2599
2600     valueW.Buffer = baseDirW.Buffer = pwszBuffer = NULL;
2601     if (!RtlCreateUnicodeStringFromAsciiz(&valueW, pszValue) ||
2602         !RtlCreateUnicodeStringFromAsciiz(&baseDirW, pszBaseDir) ||
2603         !(pwszBuffer = HeapAlloc(GetProcessHeap(), 0, cbData)))
2604     {
2605         result = ERROR_NOT_ENOUGH_MEMORY;
2606         goto cleanup;
2607     }
2608
2609     result = RegLoadMUIStringW(hKey, valueW.Buffer, pwszBuffer, cbData, NULL, dwFlags, 
2610                                baseDirW.Buffer);
2611  
2612     if (result == ERROR_SUCCESS) {
2613         cbData = WideCharToMultiByte(CP_ACP, 0, pwszBuffer, -1, pszBuffer, cbBuffer, NULL, NULL);
2614         if (pcbData)
2615             *pcbData = cbData;
2616     }
2617
2618 cleanup:
2619     HeapFree(GetProcessHeap(), 0, pwszBuffer);
2620     RtlFreeUnicodeString(&baseDirW);
2621     RtlFreeUnicodeString(&valueW);
2622  
2623     return result;
2624 }
2625
2626 /******************************************************************************
2627  * RegDisablePredefinedCache [ADVAPI32.@]
2628  *
2629  * Disables the caching of the HKEY_CLASSES_ROOT key for the process.
2630  *
2631  * PARAMS
2632  *  None.
2633  *
2634  * RETURNS
2635  *  Success: ERROR_SUCCESS
2636  *  Failure: nonzero error code from Winerror.h
2637  * 
2638  * NOTES
2639  *  This is useful for services that use impersonation.
2640  */
2641 LSTATUS WINAPI RegDisablePredefinedCache(void)
2642 {
2643     HKEY hkey_current_user;
2644     int idx = (UINT_PTR)HKEY_CURRENT_USER - (UINT_PTR)HKEY_SPECIAL_ROOT_FIRST;
2645
2646     /* prevent caching of future requests */
2647     hkcu_cache_disabled = TRUE;
2648
2649     hkey_current_user = InterlockedExchangePointer( (void **)&special_root_keys[idx], NULL );
2650
2651     if (hkey_current_user)
2652         NtClose( hkey_current_user );
2653
2654     return ERROR_SUCCESS;
2655 }
2656
2657 /******************************************************************************
2658  * RegDeleteTreeW [ADVAPI32.@]
2659  *
2660  */
2661 LSTATUS WINAPI RegDeleteTreeW(HKEY hKey, LPCWSTR lpszSubKey)
2662 {
2663     LONG ret;
2664     DWORD dwMaxSubkeyLen, dwMaxValueLen;
2665     DWORD dwMaxLen, dwSize;
2666     WCHAR szNameBuf[MAX_PATH], *lpszName = szNameBuf;
2667     HKEY hSubKey = hKey;
2668
2669     TRACE("(hkey=%p,%p %s)\n", hKey, lpszSubKey, debugstr_w(lpszSubKey));
2670
2671     if(lpszSubKey)
2672     {
2673         ret = RegOpenKeyExW(hKey, lpszSubKey, 0, KEY_READ, &hSubKey);
2674         if (ret) return ret;
2675     }
2676
2677     /* Get highest length for keys, values */
2678     ret = RegQueryInfoKeyW(hSubKey, NULL, NULL, NULL, NULL,
2679             &dwMaxSubkeyLen, NULL, NULL, &dwMaxValueLen, NULL, NULL, NULL);
2680     if (ret) goto cleanup;
2681
2682     dwMaxSubkeyLen++;
2683     dwMaxValueLen++;
2684     dwMaxLen = max(dwMaxSubkeyLen, dwMaxValueLen);
2685     if (dwMaxLen > sizeof(szNameBuf)/sizeof(WCHAR))
2686     {
2687         /* Name too big: alloc a buffer for it */
2688         if (!(lpszName = HeapAlloc( GetProcessHeap(), 0, dwMaxLen*sizeof(WCHAR))))
2689         {
2690             ret = ERROR_NOT_ENOUGH_MEMORY;
2691             goto cleanup;
2692         }
2693     }
2694
2695
2696     /* Recursively delete all the subkeys */
2697     while (TRUE)
2698     {
2699         dwSize = dwMaxLen;
2700         if (RegEnumKeyExW(hSubKey, 0, lpszName, &dwSize, NULL,
2701                           NULL, NULL, NULL)) break;
2702
2703         ret = RegDeleteTreeW(hSubKey, lpszName);
2704         if (ret) goto cleanup;
2705     }
2706
2707     if (lpszSubKey)
2708         ret = RegDeleteKeyW(hKey, lpszSubKey);
2709     else
2710         while (TRUE)
2711         {
2712             dwSize = dwMaxLen;
2713             if (RegEnumValueW(hKey, 0, lpszName, &dwSize,
2714                   NULL, NULL, NULL, NULL)) break;
2715
2716             ret = RegDeleteValueW(hKey, lpszName);
2717             if (ret) goto cleanup;
2718         }
2719
2720 cleanup:
2721     /* Free buffer if allocated */
2722     if (lpszName != szNameBuf)
2723         HeapFree( GetProcessHeap(), 0, lpszName);
2724     if(lpszSubKey)
2725         RegCloseKey(hSubKey);
2726     return ret;
2727 }
2728
2729 /******************************************************************************
2730  * RegDeleteTreeA [ADVAPI32.@]
2731  *
2732  */
2733 LSTATUS WINAPI RegDeleteTreeA(HKEY hKey, LPCSTR lpszSubKey)
2734 {
2735     LONG ret;
2736     UNICODE_STRING lpszSubKeyW;
2737
2738     if (lpszSubKey) RtlCreateUnicodeStringFromAsciiz( &lpszSubKeyW, lpszSubKey);
2739     else lpszSubKeyW.Buffer = NULL;
2740     ret = RegDeleteTreeW( hKey, lpszSubKeyW.Buffer);
2741     RtlFreeUnicodeString( &lpszSubKeyW );
2742     return ret;
2743 }