Handle wParam in WM_PAINT properly: if non-null, it is the hdc we are
[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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27  */
28
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32
33 #include "windef.h"
34 #include "winbase.h"
35 #include "winreg.h"
36 #include "winerror.h"
37 #include "ntstatus.h"
38 #include "wine/unicode.h"
39 #include "wine/server.h"
40 #include "wine/debug.h"
41 #include "winternl.h"
42
43 WINE_DEFAULT_DEBUG_CHANNEL(reg);
44
45 /* allowed bits for access mask */
46 #define KEY_ACCESS_MASK (KEY_ALL_ACCESS | MAXIMUM_ALLOWED)
47
48 #define HKEY_SPECIAL_ROOT_FIRST   HKEY_CLASSES_ROOT
49 #define HKEY_SPECIAL_ROOT_LAST    HKEY_DYN_DATA
50 #define NB_SPECIAL_ROOT_KEYS      ((UINT)HKEY_SPECIAL_ROOT_LAST - (UINT)HKEY_SPECIAL_ROOT_FIRST + 1)
51
52 static HKEY special_root_keys[NB_SPECIAL_ROOT_KEYS];
53
54 static const WCHAR name_CLASSES_ROOT[] =
55     {'M','a','c','h','i','n','e','\\',
56      'S','o','f','t','w','a','r','e','\\',
57      'C','l','a','s','s','e','s',0};
58 static const WCHAR name_LOCAL_MACHINE[] =
59     {'M','a','c','h','i','n','e',0};
60 static const WCHAR name_USERS[] =
61     {'U','s','e','r',0};
62 static const WCHAR name_PERFORMANCE_DATA[] =
63     {'P','e','r','f','D','a','t','a',0};
64 static const WCHAR name_CURRENT_CONFIG[] =
65     {'M','a','c','h','i','n','e','\\',
66      'S','y','s','t','e','m','\\',
67      'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
68      'H','a','r','d','w','a','r','e',' ','P','r','o','f','i','l','e','s','\\',
69      'C','u','r','r','e','n','t',0};
70 static const WCHAR name_DYN_DATA[] =
71     {'D','y','n','D','a','t','a',0};
72
73 #define DECL_STR(key) { sizeof(name_##key)-sizeof(WCHAR), sizeof(name_##key), (LPWSTR)name_##key }
74 static UNICODE_STRING root_key_names[NB_SPECIAL_ROOT_KEYS] =
75 {
76     DECL_STR(CLASSES_ROOT),
77     { 0, 0, NULL },         /* HKEY_CURRENT_USER is determined dynamically */
78     DECL_STR(LOCAL_MACHINE),
79     DECL_STR(USERS),
80     DECL_STR(PERFORMANCE_DATA),
81     DECL_STR(CURRENT_CONFIG),
82     DECL_STR(DYN_DATA)
83 };
84 #undef DECL_STR
85
86
87 /* check if value type needs string conversion (Ansi<->Unicode) */
88 inline static int is_string( DWORD type )
89 {
90     return (type == REG_SZ) || (type == REG_EXPAND_SZ) || (type == REG_MULTI_SZ);
91 }
92
93 /* check if current version is NT or Win95 */
94 inline static int is_version_nt(void)
95 {
96     return !(GetVersion() & 0x80000000);
97 }
98
99 /* create one of the HKEY_* special root keys */
100 static HKEY create_special_root_hkey( HKEY hkey, DWORD access )
101 {
102     HKEY ret = 0;
103     int idx = (UINT)hkey - (UINT)HKEY_SPECIAL_ROOT_FIRST;
104
105     if (hkey == HKEY_CURRENT_USER)
106     {
107         if (RtlOpenCurrentUser( access, &hkey )) return 0;
108         TRACE( "HKEY_CURRENT_USER -> %p\n", hkey );
109     }
110     else
111     {
112         OBJECT_ATTRIBUTES attr;
113
114         attr.Length = sizeof(attr);
115         attr.RootDirectory = 0;
116         attr.ObjectName = &root_key_names[idx];
117         attr.Attributes = 0;
118         attr.SecurityDescriptor = NULL;
119         attr.SecurityQualityOfService = NULL;
120         if (NtCreateKey( &hkey, access, &attr, 0, NULL, 0, NULL )) return 0;
121         TRACE( "%s -> %p\n", debugstr_w(attr.ObjectName->Buffer), hkey );
122     }
123
124     if (!(ret = InterlockedCompareExchangePointer( (void **)&special_root_keys[idx], hkey, 0 )))
125         ret = hkey;
126     else
127         NtClose( hkey );  /* somebody beat us to it */
128     return ret;
129 }
130
131 /* map the hkey from special root to normal key if necessary */
132 inline static HKEY get_special_root_hkey( HKEY hkey )
133 {
134     HKEY ret = hkey;
135
136     if ((hkey >= HKEY_SPECIAL_ROOT_FIRST) && (hkey <= HKEY_SPECIAL_ROOT_LAST))
137     {
138         if (!(ret = special_root_keys[(UINT)hkey - (UINT)HKEY_SPECIAL_ROOT_FIRST]))
139             ret = create_special_root_hkey( hkey, KEY_ALL_ACCESS );
140     }
141     return ret;
142 }
143
144
145 /******************************************************************************
146  * RegCreateKeyExW   [ADVAPI32.@]
147  *
148  * See RegCreateKeyExA.
149  */
150 DWORD WINAPI RegCreateKeyExW( HKEY hkey, LPCWSTR name, DWORD reserved, LPCWSTR class,
151                               DWORD options, REGSAM access, SECURITY_ATTRIBUTES *sa,
152                               PHKEY retkey, LPDWORD dispos )
153 {
154     OBJECT_ATTRIBUTES attr;
155     UNICODE_STRING nameW, classW;
156
157     if (reserved) return ERROR_INVALID_PARAMETER;
158     if (!(access & KEY_ACCESS_MASK) || (access & ~KEY_ACCESS_MASK)) return ERROR_ACCESS_DENIED;
159     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
160
161     attr.Length = sizeof(attr);
162     attr.RootDirectory = hkey;
163     attr.ObjectName = &nameW;
164     attr.Attributes = 0;
165     attr.SecurityDescriptor = NULL;
166     attr.SecurityQualityOfService = NULL;
167     RtlInitUnicodeString( &nameW, name );
168     RtlInitUnicodeString( &classW, class );
169
170     return RtlNtStatusToDosError( NtCreateKey( retkey, access, &attr, 0,
171                                                &classW, options, dispos ) );
172 }
173
174
175 /******************************************************************************
176  * RegCreateKeyExA   [ADVAPI32.@]
177  *
178  * Open a registry key, creating it if it doesn't exist.
179  *
180  * PARAMS
181  *  hkey       [I] Handle of the parent registry key
182  *  name       [I] Name of the new key to open or create
183  *  reserved   [I] Reserved, pass 0
184  *  class      [I] The object type of the new key
185  *  options    [I] Flags controlling the key creation (REG_OPTION_* flags from "winnt.h")
186  *  access     [I] Access level desired
187  *  sa         [I] Security attributes for the key
188  *  retkey     [O] Destination for the resulting handle
189  *  dispos     [O] Receives REG_CREATED_NEW_KEY or REG_OPENED_EXISTING_KEY
190  *
191  * RETURNS
192  *  Success: ERROR_SUCCESS.
193  *  Failure: A standard Win32 error code. retkey remains untouched.
194  *
195  * FIXME
196  *  MAXIMUM_ALLOWED in access mask not supported by server
197  */
198 DWORD WINAPI RegCreateKeyExA( HKEY hkey, LPCSTR name, DWORD reserved, LPCSTR class,
199                               DWORD options, REGSAM access, SECURITY_ATTRIBUTES *sa,
200                               PHKEY retkey, LPDWORD dispos )
201 {
202     OBJECT_ATTRIBUTES attr;
203     UNICODE_STRING classW;
204     ANSI_STRING nameA, classA;
205     NTSTATUS status;
206
207     if (reserved) return ERROR_INVALID_PARAMETER;
208     if (!is_version_nt()) access = KEY_ALL_ACCESS;  /* Win95 ignores the access mask */
209     else if (!(access & KEY_ACCESS_MASK) || (access & ~KEY_ACCESS_MASK)) return ERROR_ACCESS_DENIED;
210     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
211
212     attr.Length = sizeof(attr);
213     attr.RootDirectory = hkey;
214     attr.ObjectName = &NtCurrentTeb()->StaticUnicodeString;
215     attr.Attributes = 0;
216     attr.SecurityDescriptor = NULL;
217     attr.SecurityQualityOfService = NULL;
218     RtlInitAnsiString( &nameA, name );
219     RtlInitAnsiString( &classA, class );
220
221     if (!(status = RtlAnsiStringToUnicodeString( &NtCurrentTeb()->StaticUnicodeString,
222                                                  &nameA, FALSE )))
223     {
224         if (!(status = RtlAnsiStringToUnicodeString( &classW, &classA, TRUE )))
225         {
226             status = NtCreateKey( retkey, access, &attr, 0, &classW, options, dispos );
227             RtlFreeUnicodeString( &classW );
228         }
229     }
230     return RtlNtStatusToDosError( status );
231 }
232
233
234 /******************************************************************************
235  * RegCreateKeyW   [ADVAPI32.@]
236  *
237  * Creates the specified reg key.
238  *
239  * PARAMS
240  *  hKey      [I] Handle to an open key.
241  *  lpSubKey  [I] Name of a key that will be opened or created.
242  *  phkResult [O] Receives a handle to the opened or created key.
243  *
244  * RETURNS
245  *  Success: ERROR_SUCCESS
246  *  Failure: nonzero error code defined in Winerror.h
247  */
248 DWORD WINAPI RegCreateKeyW( HKEY hkey, LPCWSTR lpSubKey, PHKEY phkResult )
249 {
250     /* FIXME: previous implementation converted ERROR_INVALID_HANDLE to ERROR_BADKEY, */
251     /* but at least my version of NT (4.0 SP5) doesn't do this.  -- AJ */
252     return RegCreateKeyExW( hkey, lpSubKey, 0, NULL, REG_OPTION_NON_VOLATILE,
253                             KEY_ALL_ACCESS, NULL, phkResult, NULL );
254 }
255
256
257 /******************************************************************************
258  * RegCreateKeyA   [ADVAPI32.@]
259  *
260  * see RegCreateKeyW
261  */
262 DWORD WINAPI RegCreateKeyA( HKEY hkey, LPCSTR lpSubKey, PHKEY phkResult )
263 {
264     return RegCreateKeyExA( hkey, lpSubKey, 0, NULL, REG_OPTION_NON_VOLATILE,
265                             KEY_ALL_ACCESS, NULL, phkResult, NULL );
266 }
267
268
269
270 /******************************************************************************
271  * RegOpenKeyExW   [ADVAPI32.@]
272  * 
273  * See RegOpenKeyExA.
274  */
275 DWORD WINAPI RegOpenKeyExW( HKEY hkey, LPCWSTR name, DWORD reserved, REGSAM access, PHKEY retkey )
276 {
277     OBJECT_ATTRIBUTES attr;
278     UNICODE_STRING nameW;
279
280     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
281
282     attr.Length = sizeof(attr);
283     attr.RootDirectory = hkey;
284     attr.ObjectName = &nameW;
285     attr.Attributes = 0;
286     attr.SecurityDescriptor = NULL;
287     attr.SecurityQualityOfService = NULL;
288     RtlInitUnicodeString( &nameW, name );
289     return RtlNtStatusToDosError( NtOpenKey( retkey, access, &attr ) );
290 }
291
292
293 /******************************************************************************
294  * RegOpenKeyExA   [ADVAPI32.@]
295  *
296  * Open a registry key.
297  *
298  * PARAMS
299  *  hkey       [I] Handle of open key
300  *  name       [I] Name of subkey to open
301  *  reserved   [I] Reserved - must be zero
302  *  access     [I] Security access mask
303  *  retkey     [O] Handle to open key
304  *
305  * RETURNS
306  *  Success: ERROR_SUCCESS
307  *  Failure: A standard Win32 error code. retkey is set to 0.
308  *
309  * NOTES
310  *  Unlike RegCreateKeyExA(), this function will not create the key if it
311  *  does not exist.
312  */
313 DWORD WINAPI RegOpenKeyExA( HKEY hkey, LPCSTR name, DWORD reserved, REGSAM access, PHKEY retkey )
314 {
315     OBJECT_ATTRIBUTES attr;
316     STRING nameA;
317     NTSTATUS status;
318
319     if (!is_version_nt()) access = KEY_ALL_ACCESS;  /* Win95 ignores the access mask */
320
321     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
322
323     attr.Length = sizeof(attr);
324     attr.RootDirectory = hkey;
325     attr.ObjectName = &NtCurrentTeb()->StaticUnicodeString;
326     attr.Attributes = 0;
327     attr.SecurityDescriptor = NULL;
328     attr.SecurityQualityOfService = NULL;
329
330     RtlInitAnsiString( &nameA, name );
331     if (!(status = RtlAnsiStringToUnicodeString( &NtCurrentTeb()->StaticUnicodeString,
332                                                  &nameA, FALSE )))
333     {
334         status = NtOpenKey( retkey, access, &attr );
335     }
336     return RtlNtStatusToDosError( status );
337 }
338
339
340 /******************************************************************************
341  * RegOpenKeyW   [ADVAPI32.@]
342  *
343  * See RegOpenKeyA.
344  */
345 DWORD WINAPI RegOpenKeyW( HKEY hkey, LPCWSTR name, PHKEY retkey )
346 {
347     if (!name || !*name)
348     {
349         *retkey = hkey;
350         return ERROR_SUCCESS;
351     }
352     return RegOpenKeyExW( hkey, name, 0, KEY_ALL_ACCESS, retkey );
353 }
354
355
356 /******************************************************************************
357  * RegOpenKeyA   [ADVAPI32.@]
358  *           
359  * Open a registry key.
360  *
361  * PARAMS
362  *  hkey    [I] Handle of parent key to open the new key under
363  *  name    [I] Name of the key under hkey to open
364  *  retkey  [O] Destination for the resulting Handle
365  *
366  * RETURNS
367  *  Success: ERROR_SUCCESS
368  *  Failure: A standard Win32 error code. retkey is set to 0.
369  */
370 DWORD WINAPI RegOpenKeyA( HKEY hkey, LPCSTR name, PHKEY retkey )
371 {
372     if (!name || !*name)
373     {
374         *retkey = hkey;
375         return ERROR_SUCCESS;
376     }
377     return RegOpenKeyExA( hkey, name, 0, KEY_ALL_ACCESS, retkey );
378 }
379
380
381 /******************************************************************************
382  * RegOpenCurrentUser   [ADVAPI32.@]
383  * 
384  * FIXME: This function is supposed to retrieve a handle to the
385  * HKEY_CURRENT_USER for the user the current thread is impersonating.
386  * Since Wine does not currently allow threads to impersonate other users,
387  * this stub should work fine.
388  */
389 DWORD WINAPI RegOpenCurrentUser( REGSAM access, PHKEY retkey )
390 {
391     return RegOpenKeyExA( HKEY_CURRENT_USER, "", 0, access, retkey );
392 }
393
394
395
396 /******************************************************************************
397  * RegEnumKeyExW   [ADVAPI32.@]
398  *
399  * PARAMS
400  *  hkey         [I] Handle to key to enumerate
401  *  index        [I] Index of subkey to enumerate
402  *  name         [O] Buffer for subkey name
403  *  name_len     [O] Size of subkey buffer
404  *  reserved     [I] Reserved
405  *  class        [O] Buffer for class string
406  *  class_len    [O] Size of class buffer
407  *  ft           [O] Time key last written to
408  *
409  * RETURNS
410  *  Success: ERROR_SUCCESS
411  *  Failure: System error code. If there are no more subkeys available, the
412  *           function returns ERROR_NO_MORE_ITEMS.
413  */
414 DWORD WINAPI RegEnumKeyExW( HKEY hkey, DWORD index, LPWSTR name, LPDWORD name_len,
415                             LPDWORD reserved, LPWSTR class, LPDWORD class_len, FILETIME *ft )
416 {
417     NTSTATUS status;
418     char buffer[256], *buf_ptr = buffer;
419     KEY_NODE_INFORMATION *info = (KEY_NODE_INFORMATION *)buffer;
420     DWORD total_size;
421
422     TRACE( "(%p,%ld,%p,%p(%ld),%p,%p,%p,%p)\n", hkey, index, name, name_len,
423            name_len ? *name_len : -1, reserved, class, class_len, ft );
424
425     if (reserved) return ERROR_INVALID_PARAMETER;
426     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
427
428     status = NtEnumerateKey( hkey, index, KeyNodeInformation,
429                              buffer, sizeof(buffer), &total_size );
430
431     while (status == STATUS_BUFFER_OVERFLOW)
432     {
433         /* retry with a dynamically allocated buffer */
434         if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
435         if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
436             return ERROR_NOT_ENOUGH_MEMORY;
437         info = (KEY_NODE_INFORMATION *)buf_ptr;
438         status = NtEnumerateKey( hkey, index, KeyNodeInformation,
439                                  buf_ptr, total_size, &total_size );
440     }
441
442     if (!status)
443     {
444         DWORD len = info->NameLength / sizeof(WCHAR);
445         DWORD cls_len = info->ClassLength / sizeof(WCHAR);
446
447         if (ft) *ft = *(FILETIME *)&info->LastWriteTime;
448
449         if (len >= *name_len || (class && class_len && (cls_len >= *class_len)))
450             status = STATUS_BUFFER_OVERFLOW;
451         else
452         {
453             *name_len = len;
454             memcpy( name, info->Name, info->NameLength );
455             name[len] = 0;
456             if (class_len)
457             {
458                 *class_len = cls_len;
459                 if (class)
460                 {
461                     memcpy( class, buf_ptr + info->ClassOffset, info->ClassLength );
462                     class[cls_len] = 0;
463                 }
464             }
465         }
466     }
467
468     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
469     return RtlNtStatusToDosError( status );
470 }
471
472
473 /******************************************************************************
474  * RegEnumKeyExA   [ADVAPI32.@]
475  *
476  * see RegEnumKeyExW
477  */
478 DWORD WINAPI RegEnumKeyExA( HKEY hkey, DWORD index, LPSTR name, LPDWORD name_len,
479                             LPDWORD reserved, LPSTR class, LPDWORD class_len, FILETIME *ft )
480 {
481     NTSTATUS status;
482     char buffer[256], *buf_ptr = buffer;
483     KEY_NODE_INFORMATION *info = (KEY_NODE_INFORMATION *)buffer;
484     DWORD total_size;
485
486     TRACE( "(%p,%ld,%p,%p(%ld),%p,%p,%p,%p)\n", hkey, index, name, name_len,
487            name_len ? *name_len : -1, reserved, class, class_len, ft );
488
489     if (reserved) return ERROR_INVALID_PARAMETER;
490     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
491
492     status = NtEnumerateKey( hkey, index, KeyNodeInformation,
493                              buffer, sizeof(buffer), &total_size );
494
495     while (status == STATUS_BUFFER_OVERFLOW)
496     {
497         /* retry with a dynamically allocated buffer */
498         if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
499         if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
500             return ERROR_NOT_ENOUGH_MEMORY;
501         info = (KEY_NODE_INFORMATION *)buf_ptr;
502         status = NtEnumerateKey( hkey, index, KeyNodeInformation,
503                                  buf_ptr, total_size, &total_size );
504     }
505
506     if (!status)
507     {
508         DWORD len, cls_len;
509
510         RtlUnicodeToMultiByteSize( &len, info->Name, info->NameLength );
511         RtlUnicodeToMultiByteSize( &cls_len, (WCHAR *)(buf_ptr + info->ClassOffset),
512                                    info->ClassLength );
513         if (ft) *ft = *(FILETIME *)&info->LastWriteTime;
514
515         if (len >= *name_len || (class && class_len && (cls_len >= *class_len)))
516             status = STATUS_BUFFER_OVERFLOW;
517         else
518         {
519             *name_len = len;
520             RtlUnicodeToMultiByteN( name, len, NULL, info->Name, info->NameLength );
521             name[len] = 0;
522             if (class_len)
523             {
524                 *class_len = cls_len;
525                 if (class)
526                 {
527                     RtlUnicodeToMultiByteN( class, cls_len, NULL,
528                                             (WCHAR *)(buf_ptr + info->ClassOffset),
529                                             info->ClassLength );
530                     class[cls_len] = 0;
531                 }
532             }
533         }
534     }
535
536     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
537     return RtlNtStatusToDosError( status );
538 }
539
540
541 /******************************************************************************
542  * RegEnumKeyW   [ADVAPI32.@]
543  *
544  * Enumerates subkyes of the specified open reg key.
545  *
546  * PARAMS
547  *  hKey    [I] Handle to an open key.
548  *  dwIndex [I] Index of the subkey of hKey to retrieve.
549  *  lpName  [O] Name of the subkey.
550  *  cchName [I] Size of lpName in TCHARS.
551  *
552  * RETURNS
553  *  Success: ERROR_SUCCESS
554  *  Failure: system error code. If there are no more subkeys available, the
555  *           function returns ERROR_NO_MORE_ITEMS.
556  */
557 DWORD WINAPI RegEnumKeyW( HKEY hkey, DWORD index, LPWSTR name, DWORD name_len )
558 {
559     return RegEnumKeyExW( hkey, index, name, &name_len, NULL, NULL, NULL, NULL );
560 }
561
562
563 /******************************************************************************
564  * RegEnumKeyA   [ADVAPI32.@]
565  *
566  * see RegEnumKeyW
567  */
568 DWORD WINAPI RegEnumKeyA( HKEY hkey, DWORD index, LPSTR name, DWORD name_len )
569 {
570     return RegEnumKeyExA( hkey, index, name, &name_len, NULL, NULL, NULL, NULL );
571 }
572
573
574 /******************************************************************************
575  * RegQueryInfoKeyW   [ADVAPI32.@]
576  *
577  * PARAMS
578  *    hkey       [I] Handle to key to query
579  *    class      [O] Buffer for class string
580  *    class_len  [O] Size of class string buffer
581  *    reserved   [I] Reserved
582  *    subkeys    [O] Buffer for number of subkeys
583  *    max_subkey [O] Buffer for longest subkey name length
584  *    max_class  [O] Buffer for longest class string length
585  *    values     [O] Buffer for number of value entries
586  *    max_value  [O] Buffer for longest value name length
587  *    max_data   [O] Buffer for longest value data length
588  *    security   [O] Buffer for security descriptor length
589  *    modif      [O] Modification time
590  *
591  * - win95 allows class to be valid and class_len to be NULL
592  * - winnt returns ERROR_INVALID_PARAMETER if class is valid and class_len is NULL
593  * - both allow class to be NULL and class_len to be NULL
594  * (it's hard to test validity, so test !NULL instead)
595  */
596 DWORD WINAPI RegQueryInfoKeyW( HKEY hkey, LPWSTR class, LPDWORD class_len, LPDWORD reserved,
597                                LPDWORD subkeys, LPDWORD max_subkey, LPDWORD max_class,
598                                LPDWORD values, LPDWORD max_value, LPDWORD max_data,
599                                LPDWORD security, FILETIME *modif )
600 {
601     NTSTATUS status;
602     char buffer[256], *buf_ptr = buffer;
603     KEY_FULL_INFORMATION *info = (KEY_FULL_INFORMATION *)buffer;
604     DWORD total_size;
605
606     TRACE( "(%p,%p,%ld,%p,%p,%p,%p,%p,%p,%p,%p)\n", hkey, class, class_len ? *class_len : 0,
607            reserved, subkeys, max_subkey, values, max_value, max_data, security, modif );
608
609     if (class && !class_len && is_version_nt()) return ERROR_INVALID_PARAMETER;
610     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
611
612     status = NtQueryKey( hkey, KeyFullInformation, buffer, sizeof(buffer), &total_size );
613     if (status && status != STATUS_BUFFER_OVERFLOW) goto done;
614
615     if (class)
616     {
617         /* retry with a dynamically allocated buffer */
618         while (status == STATUS_BUFFER_OVERFLOW)
619         {
620             if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
621             if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
622                 return ERROR_NOT_ENOUGH_MEMORY;
623             info = (KEY_FULL_INFORMATION *)buf_ptr;
624             status = NtQueryKey( hkey, KeyFullInformation, buf_ptr, total_size, &total_size );
625         }
626
627         if (status) goto done;
628
629         if (class_len && (info->ClassLength/sizeof(WCHAR) + 1 > *class_len))
630         {
631             status = STATUS_BUFFER_OVERFLOW;
632         }
633         else
634         {
635             memcpy( class, buf_ptr + info->ClassOffset, info->ClassLength );
636             class[info->ClassLength/sizeof(WCHAR)] = 0;
637         }
638     }
639     else status = STATUS_SUCCESS;
640
641     if (class_len) *class_len = info->ClassLength / sizeof(WCHAR);
642     if (subkeys) *subkeys = info->SubKeys;
643     if (max_subkey) *max_subkey = info->MaxNameLen;
644     if (max_class) *max_class = info->MaxClassLen;
645     if (values) *values = info->Values;
646     if (max_value) *max_value = info->MaxValueNameLen;
647     if (max_data) *max_data = info->MaxValueDataLen;
648     if (modif) *modif = *(FILETIME *)&info->LastWriteTime;
649
650  done:
651     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
652     return RtlNtStatusToDosError( status );
653 }
654
655
656 /******************************************************************************
657  * RegQueryMultipleValuesA   [ADVAPI32.@]
658  *
659  * Retrieves the type and data for a list of value names associated with a key.
660  *
661  * PARAMS
662  *  hKey       [I] Handle to an open key.
663  *  val_list   [O] Array of VALENT structures that describes the entries.
664  *  num_vals   [I] Number of elements in val_list.
665  *  lpValueBuf [O] Pointer to a buffer that receives the data for each value.
666  *  ldwTotsize [I/O] Size of lpValueBuf.
667  *
668  * RETURNS
669  *  Success: ERROR_SUCCESS. ldwTotsize contains num bytes copied.
670  *  Failure: nonzero error code from Winerror.h ldwTotsize contains num needed
671  *           bytes.
672  */
673 DWORD WINAPI RegQueryMultipleValuesA(HKEY hkey, PVALENTA val_list, DWORD num_vals,
674                                      LPSTR lpValueBuf, LPDWORD ldwTotsize)
675 {
676     unsigned int i;
677     DWORD maxBytes = *ldwTotsize;
678     HRESULT status;
679     LPSTR bufptr = lpValueBuf;
680     *ldwTotsize = 0;
681
682     TRACE("(%p,%p,%ld,%p,%p=%ld)\n", hkey, val_list, num_vals, lpValueBuf, ldwTotsize, *ldwTotsize);
683
684     for(i=0; i < num_vals; ++i)
685     {
686
687         val_list[i].ve_valuelen=0;
688         status = RegQueryValueExA(hkey, val_list[i].ve_valuename, NULL, NULL, NULL, &val_list[i].ve_valuelen);
689         if(status != ERROR_SUCCESS)
690         {
691             return status;
692         }
693
694         if(lpValueBuf != NULL && *ldwTotsize + val_list[i].ve_valuelen <= maxBytes)
695         {
696             status = RegQueryValueExA(hkey, val_list[i].ve_valuename, NULL, &val_list[i].ve_type,
697                                       bufptr, &val_list[i].ve_valuelen);
698             if(status != ERROR_SUCCESS)
699             {
700                 return status;
701             }
702
703             val_list[i].ve_valueptr = (DWORD_PTR)bufptr;
704
705             bufptr += val_list[i].ve_valuelen;
706         }
707
708         *ldwTotsize += val_list[i].ve_valuelen;
709     }
710     return lpValueBuf != NULL && *ldwTotsize <= maxBytes ? ERROR_SUCCESS : ERROR_MORE_DATA;
711 }
712
713
714 /******************************************************************************
715  * RegQueryMultipleValuesW   [ADVAPI32.@]
716  *
717  * see RegQueryMultipleValuesA
718  */
719 DWORD WINAPI RegQueryMultipleValuesW(HKEY hkey, PVALENTW val_list, DWORD num_vals,
720                                      LPWSTR lpValueBuf, LPDWORD ldwTotsize)
721 {
722     unsigned int i;
723     DWORD maxBytes = *ldwTotsize;
724     HRESULT status;
725     LPSTR bufptr = (LPSTR)lpValueBuf;
726     *ldwTotsize = 0;
727
728     TRACE("(%p,%p,%ld,%p,%p=%ld)\n", hkey, val_list, num_vals, lpValueBuf, ldwTotsize, *ldwTotsize);
729
730     for(i=0; i < num_vals; ++i)
731     {
732         val_list[i].ve_valuelen=0;
733         status = RegQueryValueExW(hkey, val_list[i].ve_valuename, NULL, NULL, NULL, &val_list[i].ve_valuelen);
734         if(status != ERROR_SUCCESS)
735         {
736             return status;
737         }
738
739         if(lpValueBuf != NULL && *ldwTotsize + val_list[i].ve_valuelen <= maxBytes)
740         {
741             status = RegQueryValueExW(hkey, val_list[i].ve_valuename, NULL, &val_list[i].ve_type,
742                                       bufptr, &val_list[i].ve_valuelen);
743             if(status != ERROR_SUCCESS)
744             {
745                 return status;
746             }
747
748             val_list[i].ve_valueptr = (DWORD_PTR)bufptr;
749
750             bufptr += val_list[i].ve_valuelen;
751         }
752
753         *ldwTotsize += val_list[i].ve_valuelen;
754     }
755     return lpValueBuf != NULL && *ldwTotsize <= maxBytes ? ERROR_SUCCESS : ERROR_MORE_DATA;
756 }
757
758 /******************************************************************************
759  * RegQueryInfoKeyA   [ADVAPI32.@]
760  *
761  * Retrieves information about a registry key.
762  *
763  * PARAMS
764  *  hKey                   [I] Handle to an open key.
765  *  lpClass                [O] Class string of the key.
766  *  lpcClass               [I/O] size of lpClass.
767  *  lpReserved             [I] Reserved; must be NULL.
768  *  lpcSubKeys             [O] Number of subkeys contained by the key.
769  *  lpcMaxSubKeyLen        [O] Size of the key's subkey with the longest name.
770  *  lpcMaxClassLen         [O] Size of the longest string specifying a subkey
771  *                             class in TCHARS.
772  *  lpcValues              [O] Number of values associated with the key.
773  *  lpcMaxValueNameLen     [O] Size of the key's longest value name in TCHARS.
774  *  lpcMaxValueLen         [O] Longest data component among the key's values
775  *  lpcbSecurityDescriptor [O] Size of the key's security descriptor.
776  *  lpftLastWriteTime      [O] FILETIME strucutre that is the last write time.
777  *
778  *  RETURNS
779  *   Success: ERROR_SUCCESS
780  *   Failure: nonzero error code from Winerror.h
781  */
782 DWORD WINAPI RegQueryInfoKeyA( HKEY hkey, LPSTR class, LPDWORD class_len, LPDWORD reserved,
783                                LPDWORD subkeys, LPDWORD max_subkey, LPDWORD max_class,
784                                LPDWORD values, LPDWORD max_value, LPDWORD max_data,
785                                LPDWORD security, FILETIME *modif )
786 {
787     NTSTATUS status;
788     char buffer[256], *buf_ptr = buffer;
789     KEY_FULL_INFORMATION *info = (KEY_FULL_INFORMATION *)buffer;
790     DWORD total_size, len;
791
792     TRACE( "(%p,%p,%ld,%p,%p,%p,%p,%p,%p,%p,%p)\n", hkey, class, class_len ? *class_len : 0,
793            reserved, subkeys, max_subkey, values, max_value, max_data, security, modif );
794
795     if (class && !class_len && is_version_nt()) return ERROR_INVALID_PARAMETER;
796     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
797
798     status = NtQueryKey( hkey, KeyFullInformation, buffer, sizeof(buffer), &total_size );
799     if (status && status != STATUS_BUFFER_OVERFLOW) goto done;
800
801     if (class || class_len)
802     {
803         /* retry with a dynamically allocated buffer */
804         while (status == STATUS_BUFFER_OVERFLOW)
805         {
806             if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
807             if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
808                 return ERROR_NOT_ENOUGH_MEMORY;
809             info = (KEY_FULL_INFORMATION *)buf_ptr;
810             status = NtQueryKey( hkey, KeyFullInformation, buf_ptr, total_size, &total_size );
811         }
812
813         if (status) goto done;
814
815         RtlUnicodeToMultiByteSize( &len, (WCHAR *)(buf_ptr + info->ClassOffset), info->ClassLength);
816         if (class_len)
817         {
818             if (len + 1 > *class_len) status = STATUS_BUFFER_OVERFLOW;
819             *class_len = len;
820         }
821         if (class && !status)
822         {
823             RtlUnicodeToMultiByteN( class, len, NULL, (WCHAR *)(buf_ptr + info->ClassOffset),
824                                     info->ClassLength );
825             class[len] = 0;
826         }
827     }
828     else status = STATUS_SUCCESS;
829
830     if (subkeys) *subkeys = info->SubKeys;
831     if (max_subkey) *max_subkey = info->MaxNameLen;
832     if (max_class) *max_class = info->MaxClassLen;
833     if (values) *values = info->Values;
834     if (max_value) *max_value = info->MaxValueNameLen;
835     if (max_data) *max_data = info->MaxValueDataLen;
836     if (modif) *modif = *(FILETIME *)&info->LastWriteTime;
837
838  done:
839     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
840     return RtlNtStatusToDosError( status );
841 }
842
843
844 /******************************************************************************
845  * RegCloseKey   [ADVAPI32.@]
846  *
847  * Close an open registry key.
848  *
849  * PARAMS
850  *  hkey [I] Handle of key to close
851  *
852  * RETURNS
853  *  Success: ERROR_SUCCESS
854  *  Failure: Error code
855  */
856 DWORD WINAPI RegCloseKey( HKEY hkey )
857 {
858     if (!hkey) return ERROR_INVALID_HANDLE;
859     if (hkey >= (HKEY)0x80000000) return ERROR_SUCCESS;
860     return RtlNtStatusToDosError( NtClose( hkey ) );
861 }
862
863
864 /******************************************************************************
865  * RegDeleteKeyW   [ADVAPI32.@]
866  *
867  * See RegDeleteKeyA.
868  */
869 DWORD WINAPI RegDeleteKeyW( HKEY hkey, LPCWSTR name )
870 {
871     DWORD ret;
872     HKEY tmp;
873
874     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
875
876     if (!name || !*name)
877     {
878         ret = RtlNtStatusToDosError( NtDeleteKey( hkey ) );
879     }
880     else if (!(ret = RegOpenKeyExW( hkey, name, 0, KEY_ENUMERATE_SUB_KEYS, &tmp )))
881     {
882         ret = RtlNtStatusToDosError( NtDeleteKey( tmp ) );
883         RegCloseKey( tmp );
884     }
885     TRACE("%s ret=%08lx\n", debugstr_w(name), ret);
886     return ret;
887 }
888
889
890 /******************************************************************************
891  * RegDeleteKeyA   [ADVAPI32.@]
892  *
893  * Delete a registry key.
894  *
895  * PARAMS
896  *  hkey   [I] Handle to parent key containing the key to delete
897  *  name   [I] Name of the key user hkey to delete
898  *
899  * RETURNS
900  *  Success: ERROR_SUCCESS
901  *  Failure: Error code
902  */
903 DWORD WINAPI RegDeleteKeyA( HKEY hkey, LPCSTR name )
904 {
905     DWORD ret;
906     HKEY tmp;
907
908     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
909
910     if (!name || !*name)
911     {
912         ret = RtlNtStatusToDosError( NtDeleteKey( hkey ) );
913     }
914     else if (!(ret = RegOpenKeyExA( hkey, name, 0, KEY_ENUMERATE_SUB_KEYS, &tmp )))
915     {
916         if (!is_version_nt()) /* win95 does recursive key deletes */
917         {
918             CHAR name[MAX_PATH];
919
920             while(!RegEnumKeyA(tmp, 0, name, sizeof(name)))
921             {
922                 if(RegDeleteKeyA(tmp, name))  /* recurse */
923                     break;
924             }
925         }
926         ret = RtlNtStatusToDosError( NtDeleteKey( tmp ) );
927         RegCloseKey( tmp );
928     }
929     TRACE("%s ret=%08lx\n", debugstr_a(name), ret);
930     return ret;
931 }
932
933
934
935 /******************************************************************************
936  * RegSetValueExW   [ADVAPI32.@]
937  *
938  * Set the data and contents of a registry value.
939  *
940  * PARAMS
941  *  hkey       [I] Handle of key to set value for
942  *  name       [I] Name of value to set
943  *  reserved   [I] Reserved, must be zero
944  *  type       [I] Type of the value being set
945  *  data       [I] The new contents of the value to set
946  *  count      [I] Size of data
947  *
948  * RETURNS
949  *  Success: ERROR_SUCCESS
950  *  Failure: Error code
951  */
952 DWORD WINAPI RegSetValueExW( HKEY hkey, LPCWSTR name, DWORD reserved,
953                              DWORD type, CONST BYTE *data, DWORD count )
954 {
955     UNICODE_STRING nameW;
956
957     /* no need for version check, not implemented on win9x anyway */
958     if (count && is_string(type))
959     {
960         LPCWSTR str = (LPCWSTR)data;
961         /* if user forgot to count terminating null, add it (yes NT does this) */
962         if (str[count / sizeof(WCHAR) - 1] && !str[count / sizeof(WCHAR)])
963             count += sizeof(WCHAR);
964     }
965     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
966
967     RtlInitUnicodeString( &nameW, name );
968     return RtlNtStatusToDosError( NtSetValueKey( hkey, &nameW, 0, type, data, count ) );
969 }
970
971
972 /******************************************************************************
973  * RegSetValueExA   [ADVAPI32.@]
974  *
975  * see RegSetValueExW
976  *
977  * NOTES
978  *  win95 does not care about count for REG_SZ and finds out the len by itself (js)
979  *  NT does definitely care (aj)
980  */
981 DWORD WINAPI RegSetValueExA( HKEY hkey, LPCSTR name, DWORD reserved, DWORD type,
982                              CONST BYTE *data, DWORD count )
983 {
984     ANSI_STRING nameA;
985     WCHAR *dataW = NULL;
986     NTSTATUS status;
987
988     if (!is_version_nt())  /* win95 */
989     {
990         if (type == REG_SZ)
991         {
992             if (!data) return ERROR_INVALID_PARAMETER;
993             count = strlen(data) + 1;
994         }
995     }
996     else if (count && is_string(type))
997     {
998         /* if user forgot to count terminating null, add it (yes NT does this) */
999         if (data[count-1] && !data[count]) count++;
1000     }
1001
1002     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1003
1004     if (is_string( type )) /* need to convert to Unicode */
1005     {
1006         DWORD lenW;
1007         RtlMultiByteToUnicodeSize( &lenW, data, count );
1008         if (!(dataW = HeapAlloc( GetProcessHeap(), 0, lenW ))) return ERROR_OUTOFMEMORY;
1009         RtlMultiByteToUnicodeN( dataW, lenW, NULL, data, count );
1010         count = lenW;
1011         data = (BYTE *)dataW;
1012     }
1013
1014     RtlInitAnsiString( &nameA, name );
1015     if (!(status = RtlAnsiStringToUnicodeString( &NtCurrentTeb()->StaticUnicodeString,
1016                                                  &nameA, FALSE )))
1017     {
1018         status = NtSetValueKey( hkey, &NtCurrentTeb()->StaticUnicodeString, 0, type, data, count );
1019     }
1020     HeapFree( GetProcessHeap(), 0, dataW );
1021     return RtlNtStatusToDosError( status );
1022 }
1023
1024
1025 /******************************************************************************
1026  * RegSetValueW   [ADVAPI32.@]
1027  *
1028  * Sets the data for the default or unnamed value of a reg key.
1029  *
1030  * PARAMS
1031  *  hKey     [I] Handle to an open key.
1032  *  lpSubKey [I] Name of a subkey of hKey.
1033  *  dwType   [I] Type of information to store.
1034  *  lpData   [I] String that contains the data to set for the default value.
1035  *  cbData   [I] Size of lpData.
1036  *
1037  * RETURNS
1038  *  Success: ERROR_SUCCESS
1039  *  Failure: nonzero error code from Winerror.h
1040  */
1041 DWORD WINAPI RegSetValueW( HKEY hkey, LPCWSTR name, DWORD type, LPCWSTR data, DWORD count )
1042 {
1043     HKEY subkey = hkey;
1044     DWORD ret;
1045
1046     TRACE("(%p,%s,%ld,%s,%ld)\n", hkey, debugstr_w(name), type, debugstr_w(data), count );
1047
1048     if (type != REG_SZ) return ERROR_INVALID_PARAMETER;
1049
1050     if (name && name[0])  /* need to create the subkey */
1051     {
1052         if ((ret = RegCreateKeyW( hkey, name, &subkey )) != ERROR_SUCCESS) return ret;
1053     }
1054
1055     ret = RegSetValueExW( subkey, NULL, 0, REG_SZ, (const BYTE*)data,
1056                           (strlenW( data ) + 1) * sizeof(WCHAR) );
1057     if (subkey != hkey) RegCloseKey( subkey );
1058     return ret;
1059 }
1060
1061
1062 /******************************************************************************
1063  * RegSetValueA   [ADVAPI32.@]
1064  *
1065  * see RegSetValueW
1066  */
1067 DWORD WINAPI RegSetValueA( HKEY hkey, LPCSTR name, DWORD type, LPCSTR data, DWORD count )
1068 {
1069     HKEY subkey = hkey;
1070     DWORD ret;
1071
1072     TRACE("(%p,%s,%ld,%s,%ld)\n", hkey, debugstr_a(name), type, debugstr_a(data), count );
1073
1074     if (type != REG_SZ) return ERROR_INVALID_PARAMETER;
1075
1076     if (name && name[0])  /* need to create the subkey */
1077     {
1078         if ((ret = RegCreateKeyA( hkey, name, &subkey )) != ERROR_SUCCESS) return ret;
1079     }
1080     ret = RegSetValueExA( subkey, NULL, 0, REG_SZ, (const BYTE*)data, strlen(data)+1 );
1081     if (subkey != hkey) RegCloseKey( subkey );
1082     return ret;
1083 }
1084
1085
1086
1087 /******************************************************************************
1088  * RegQueryValueExW   [ADVAPI32.@]
1089  *
1090  * See RegQueryValueExA.
1091  */
1092 DWORD WINAPI RegQueryValueExW( HKEY hkey, LPCWSTR name, LPDWORD reserved, LPDWORD type,
1093                                LPBYTE data, LPDWORD count )
1094 {
1095     NTSTATUS status;
1096     UNICODE_STRING name_str;
1097     DWORD total_size;
1098     char buffer[256], *buf_ptr = buffer;
1099     KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
1100     static const int info_size = offsetof( KEY_VALUE_PARTIAL_INFORMATION, Data );
1101
1102     TRACE("(%p,%s,%p,%p,%p,%p=%ld)\n",
1103           hkey, debugstr_w(name), reserved, type, data, count,
1104           (count && data) ? *count : 0 );
1105
1106     if ((data && !count) || reserved) return ERROR_INVALID_PARAMETER;
1107     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1108
1109     RtlInitUnicodeString( &name_str, name );
1110
1111     if (data) total_size = min( sizeof(buffer), *count + info_size );
1112     else total_size = info_size;
1113
1114     status = NtQueryValueKey( hkey, &name_str, KeyValuePartialInformation,
1115                               buffer, total_size, &total_size );
1116     if (status && status != STATUS_BUFFER_OVERFLOW) goto done;
1117
1118     if (data)
1119     {
1120         /* retry with a dynamically allocated buffer */
1121         while (status == STATUS_BUFFER_OVERFLOW && total_size - info_size <= *count)
1122         {
1123             if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
1124             if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
1125                 return ERROR_NOT_ENOUGH_MEMORY;
1126             info = (KEY_VALUE_PARTIAL_INFORMATION *)buf_ptr;
1127             status = NtQueryValueKey( hkey, &name_str, KeyValuePartialInformation,
1128                                       buf_ptr, total_size, &total_size );
1129         }
1130
1131         if (!status)
1132         {
1133             memcpy( data, buf_ptr + info_size, total_size - info_size );
1134             /* if the type is REG_SZ and data is not 0-terminated
1135              * and there is enough space in the buffer NT appends a \0 */
1136             if (total_size - info_size <= *count-sizeof(WCHAR) && is_string(info->Type))
1137             {
1138                 WCHAR *ptr = (WCHAR *)(data + total_size - info_size);
1139                 if (ptr > (WCHAR *)data && ptr[-1]) *ptr = 0;
1140             }
1141         }
1142         else if (status != STATUS_BUFFER_OVERFLOW) goto done;
1143     }
1144     else status = STATUS_SUCCESS;
1145
1146     if (type) *type = info->Type;
1147     if (count) *count = total_size - info_size;
1148
1149  done:
1150     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
1151     return RtlNtStatusToDosError(status);
1152 }
1153
1154
1155 /******************************************************************************
1156  * RegQueryValueExA   [ADVAPI32.@]
1157  *
1158  * Get the type and contents of a specified value under with a key.
1159  *
1160  * PARAMS
1161  *  hkey      [I]   Handle of the key to query
1162  *  name      [I]   Name of value under hkey to query
1163  *  reserved  [I]   Reserved - must be NULL
1164  *  type      [O]   Destination for the value type, or NULL if not required
1165  *  data      [O]   Destination for the values contents, or NULL if not required
1166  *  count     [I/O] Size of data, updated with the number of bytes returned
1167  *
1168  * RETURNS
1169  *  Success: ERROR_SUCCESS. *count is updated with the number of bytes copied to data.
1170  *  Failure: ERROR_INVALID_HANDLE, if hkey is invalid.
1171  *           ERROR_INVALID_PARAMETER, if any other parameter is invalid.
1172  *           ERROR_MORE_DATA, if on input *count is too small to hold the contents.
1173  *                     
1174  * NOTES
1175  *   MSDN states that if data is too small it is partially filled. In reality 
1176  *   it remains untouched.
1177  */
1178 DWORD WINAPI RegQueryValueExA( HKEY hkey, LPCSTR name, LPDWORD reserved, LPDWORD type,
1179                                LPBYTE data, LPDWORD count )
1180 {
1181     NTSTATUS status;
1182     ANSI_STRING nameA;
1183     DWORD total_size;
1184     char buffer[256], *buf_ptr = buffer;
1185     KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
1186     static const int info_size = offsetof( KEY_VALUE_PARTIAL_INFORMATION, Data );
1187
1188     TRACE("(%p,%s,%p,%p,%p,%p=%ld)\n",
1189           hkey, debugstr_a(name), reserved, type, data, count, count ? *count : 0 );
1190
1191     if ((data && !count) || reserved) return ERROR_INVALID_PARAMETER;
1192     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1193
1194     RtlInitAnsiString( &nameA, name );
1195     if ((status = RtlAnsiStringToUnicodeString( &NtCurrentTeb()->StaticUnicodeString,
1196                                                 &nameA, FALSE )))
1197         return RtlNtStatusToDosError(status);
1198
1199     status = NtQueryValueKey( hkey, &NtCurrentTeb()->StaticUnicodeString,
1200                               KeyValuePartialInformation, buffer, sizeof(buffer), &total_size );
1201     if (status && status != STATUS_BUFFER_OVERFLOW) goto done;
1202
1203     /* we need to fetch the contents for a string type even if not requested,
1204      * because we need to compute the length of the ASCII string. */
1205     if (data || is_string(info->Type))
1206     {
1207         /* retry with a dynamically allocated buffer */
1208         while (status == STATUS_BUFFER_OVERFLOW)
1209         {
1210             if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
1211             if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
1212             {
1213                 status = STATUS_NO_MEMORY;
1214                 goto done;
1215             }
1216             info = (KEY_VALUE_PARTIAL_INFORMATION *)buf_ptr;
1217             status = NtQueryValueKey( hkey, &NtCurrentTeb()->StaticUnicodeString,
1218                                     KeyValuePartialInformation, buf_ptr, total_size, &total_size );
1219         }
1220
1221         if (status) goto done;
1222
1223         if (is_string(info->Type))
1224         {
1225             DWORD len;
1226
1227             RtlUnicodeToMultiByteSize( &len, (WCHAR *)(buf_ptr + info_size),
1228                                        total_size - info_size );
1229             if (data && len)
1230             {
1231                 if (len > *count) status = STATUS_BUFFER_OVERFLOW;
1232                 else
1233                 {
1234                     RtlUnicodeToMultiByteN( data, len, NULL, (WCHAR *)(buf_ptr + info_size),
1235                                             total_size - info_size );
1236                     /* if the type is REG_SZ and data is not 0-terminated
1237                      * and there is enough space in the buffer NT appends a \0 */
1238                     if (len < *count && data[len-1]) data[len] = 0;
1239                 }
1240             }
1241             total_size = len + info_size;
1242         }
1243         else if (data)
1244         {
1245             if (total_size - info_size > *count) status = STATUS_BUFFER_OVERFLOW;
1246             else memcpy( data, buf_ptr + info_size, total_size - info_size );
1247         }
1248     }
1249     else status = STATUS_SUCCESS;
1250
1251     if (type) *type = info->Type;
1252     if (count) *count = total_size - info_size;
1253
1254  done:
1255     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
1256     return RtlNtStatusToDosError(status);
1257 }
1258
1259
1260 /******************************************************************************
1261  * RegQueryValueW   [ADVAPI32.@]
1262  *
1263  * Retrieves the data associated with the default or unnamed value of a key.
1264  *
1265  * PARAMS
1266  *  hkey      [I] Handle to an open key.
1267  *  name      [I] Name of the subkey of hKey.
1268  *  data      [O] Receives the string associated with the default value
1269  *                of the key.
1270  *  count     [I/O] Size of lpValue in bytes.
1271  *
1272  *  RETURNS
1273  *   Success: ERROR_SUCCESS
1274  *   Failure: nonzero error code from Winerror.h
1275  */
1276 DWORD WINAPI RegQueryValueW( HKEY hkey, LPCWSTR name, LPWSTR data, LPLONG count )
1277 {
1278     DWORD ret;
1279     HKEY subkey = hkey;
1280
1281     TRACE("(%p,%s,%p,%ld)\n", hkey, debugstr_w(name), data, count ? *count : 0 );
1282
1283     if (name && name[0])
1284     {
1285         if ((ret = RegOpenKeyW( hkey, name, &subkey )) != ERROR_SUCCESS) return ret;
1286     }
1287     ret = RegQueryValueExW( subkey, NULL, NULL, NULL, (LPBYTE)data, count );
1288     if (subkey != hkey) RegCloseKey( subkey );
1289     if (ret == ERROR_FILE_NOT_FOUND)
1290     {
1291         /* return empty string if default value not found */
1292         if (data) *data = 0;
1293         if (count) *count = sizeof(WCHAR);
1294         ret = ERROR_SUCCESS;
1295     }
1296     return ret;
1297 }
1298
1299
1300 /******************************************************************************
1301  * RegQueryValueA   [ADVAPI32.@]
1302  *
1303  * see RegQueryValueW
1304  */
1305 DWORD WINAPI RegQueryValueA( HKEY hkey, LPCSTR name, LPSTR data, LPLONG count )
1306 {
1307     DWORD ret;
1308     HKEY subkey = hkey;
1309
1310     TRACE("(%p,%s,%p,%ld)\n", hkey, debugstr_a(name), data, count ? *count : 0 );
1311
1312     if (name && name[0])
1313     {
1314         if ((ret = RegOpenKeyA( hkey, name, &subkey )) != ERROR_SUCCESS) return ret;
1315     }
1316     ret = RegQueryValueExA( subkey, NULL, NULL, NULL, (LPBYTE)data, count );
1317     if (subkey != hkey) RegCloseKey( subkey );
1318     if (ret == ERROR_FILE_NOT_FOUND)
1319     {
1320         /* return empty string if default value not found */
1321         if (data) *data = 0;
1322         if (count) *count = 1;
1323         ret = ERROR_SUCCESS;
1324     }
1325     return ret;
1326 }
1327
1328
1329 /******************************************************************************
1330  * RegEnumValueW   [ADVAPI32.@]
1331  *
1332  * PARAMS
1333  *  hkey       [I] Handle to key to query
1334  *  index      [I] Index of value to query
1335  *  value      [O] Value string
1336  *  val_count  [I/O] Size of value buffer (in wchars)
1337  *  reserved   [I] Reserved
1338  *  type       [O] Type code
1339  *  data       [O] Value data
1340  *  count      [I/O] Size of data buffer (in bytes)
1341  *
1342  * RETURNS
1343  *  Success: ERROR_SUCCESS
1344  *  Failure: nonzero error code from Winerror.h
1345  */
1346
1347 DWORD WINAPI RegEnumValueW( HKEY hkey, DWORD index, LPWSTR value, LPDWORD val_count,
1348                             LPDWORD reserved, LPDWORD type, LPBYTE data, LPDWORD count )
1349 {
1350     NTSTATUS status;
1351     DWORD total_size;
1352     char buffer[256], *buf_ptr = buffer;
1353     KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
1354     static const int info_size = offsetof( KEY_VALUE_FULL_INFORMATION, Name );
1355
1356     TRACE("(%p,%ld,%p,%p,%p,%p,%p,%p)\n",
1357           hkey, index, value, val_count, reserved, type, data, count );
1358
1359     /* NT only checks count, not val_count */
1360     if ((data && !count) || reserved) return ERROR_INVALID_PARAMETER;
1361     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1362
1363     total_size = info_size + (MAX_PATH + 1) * sizeof(WCHAR);
1364     if (data) total_size += *count;
1365     total_size = min( sizeof(buffer), total_size );
1366
1367     status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
1368                                   buffer, total_size, &total_size );
1369     if (status && status != STATUS_BUFFER_OVERFLOW) goto done;
1370
1371     if (value || data)
1372     {
1373         /* retry with a dynamically allocated buffer */
1374         while (status == STATUS_BUFFER_OVERFLOW)
1375         {
1376             if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
1377             if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
1378                 return ERROR_NOT_ENOUGH_MEMORY;
1379             info = (KEY_VALUE_FULL_INFORMATION *)buf_ptr;
1380             status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
1381                                           buf_ptr, total_size, &total_size );
1382         }
1383
1384         if (status) goto done;
1385
1386         if (value)
1387         {
1388             if (info->NameLength/sizeof(WCHAR) >= *val_count)
1389             {
1390                 status = STATUS_BUFFER_OVERFLOW;
1391                 goto overflow;
1392             }
1393             memcpy( value, info->Name, info->NameLength );
1394             *val_count = info->NameLength / sizeof(WCHAR);
1395             value[*val_count] = 0;
1396         }
1397
1398         if (data)
1399         {
1400             if (total_size - info->DataOffset > *count)
1401             {
1402                 status = STATUS_BUFFER_OVERFLOW;
1403                 goto overflow;
1404             }
1405             memcpy( data, buf_ptr + info->DataOffset, total_size - info->DataOffset );
1406             if (total_size - info->DataOffset <= *count-sizeof(WCHAR) && is_string(info->Type))
1407             {
1408                 /* if the type is REG_SZ and data is not 0-terminated
1409                  * and there is enough space in the buffer NT appends a \0 */
1410                 WCHAR *ptr = (WCHAR *)(data + total_size - info->DataOffset);
1411                 if (ptr > (WCHAR *)data && ptr[-1]) *ptr = 0;
1412             }
1413         }
1414     }
1415     else status = STATUS_SUCCESS;
1416
1417  overflow:
1418     if (type) *type = info->Type;
1419     if (count) *count = info->DataLength;
1420
1421  done:
1422     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
1423     return RtlNtStatusToDosError(status);
1424 }
1425
1426
1427 /******************************************************************************
1428  * RegEnumValueA   [ADVAPI32.@]
1429  *
1430  * see RegEnumValueW
1431  */
1432 DWORD WINAPI RegEnumValueA( HKEY hkey, DWORD index, LPSTR value, LPDWORD val_count,
1433                             LPDWORD reserved, LPDWORD type, LPBYTE data, LPDWORD count )
1434 {
1435     NTSTATUS status;
1436     DWORD total_size;
1437     char buffer[256], *buf_ptr = buffer;
1438     KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
1439     static const int info_size = offsetof( KEY_VALUE_FULL_INFORMATION, Name );
1440
1441     TRACE("(%p,%ld,%p,%p,%p,%p,%p,%p)\n",
1442           hkey, index, value, val_count, reserved, type, data, count );
1443
1444     /* NT only checks count, not val_count */
1445     if ((data && !count) || reserved) return ERROR_INVALID_PARAMETER;
1446     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1447
1448     total_size = info_size + (MAX_PATH + 1) * sizeof(WCHAR);
1449     if (data) total_size += *count;
1450     total_size = min( sizeof(buffer), total_size );
1451
1452     status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
1453                                   buffer, total_size, &total_size );
1454     if (status && status != STATUS_BUFFER_OVERFLOW) goto done;
1455
1456     /* we need to fetch the contents for a string type even if not requested,
1457      * because we need to compute the length of the ASCII string. */
1458     if (value || data || is_string(info->Type))
1459     {
1460         /* retry with a dynamically allocated buffer */
1461         while (status == STATUS_BUFFER_OVERFLOW)
1462         {
1463             if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
1464             if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
1465                 return ERROR_NOT_ENOUGH_MEMORY;
1466             info = (KEY_VALUE_FULL_INFORMATION *)buf_ptr;
1467             status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
1468                                           buf_ptr, total_size, &total_size );
1469         }
1470
1471         if (status) goto done;
1472
1473         if (is_string(info->Type))
1474         {
1475             DWORD len;
1476             RtlUnicodeToMultiByteSize( &len, (WCHAR *)(buf_ptr + info->DataOffset),
1477                                        total_size - info->DataOffset );
1478             if (data && len)
1479             {
1480                 if (len > *count) status = STATUS_BUFFER_OVERFLOW;
1481                 else
1482                 {
1483                     RtlUnicodeToMultiByteN( data, len, NULL, (WCHAR *)(buf_ptr + info->DataOffset),
1484                                             total_size - info->DataOffset );
1485                     /* if the type is REG_SZ and data is not 0-terminated
1486                      * and there is enough space in the buffer NT appends a \0 */
1487                     if (len < *count && data[len-1]) data[len] = 0;
1488                 }
1489             }
1490             info->DataLength = len;
1491         }
1492         else if (data)
1493         {
1494             if (total_size - info->DataOffset > *count) status = STATUS_BUFFER_OVERFLOW;
1495             else memcpy( data, buf_ptr + info->DataOffset, total_size - info->DataOffset );
1496         }
1497
1498         if (value && !status)
1499         {
1500             DWORD len;
1501
1502             RtlUnicodeToMultiByteSize( &len, info->Name, info->NameLength );
1503             if (len >= *val_count)
1504             {
1505                 status = STATUS_BUFFER_OVERFLOW;
1506                 if (*val_count)
1507                 {
1508                     len = *val_count - 1;
1509                     RtlUnicodeToMultiByteN( value, len, NULL, info->Name, info->NameLength );
1510                     value[len] = 0;
1511                 }
1512             }
1513             else
1514             {
1515                 RtlUnicodeToMultiByteN( value, len, NULL, info->Name, info->NameLength );
1516                 value[len] = 0;
1517                 *val_count = len;
1518             }
1519         }
1520     }
1521     else status = STATUS_SUCCESS;
1522
1523     if (type) *type = info->Type;
1524     if (count) *count = info->DataLength;
1525
1526  done:
1527     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
1528     return RtlNtStatusToDosError(status);
1529 }
1530
1531
1532
1533 /******************************************************************************
1534  * RegDeleteValueW   [ADVAPI32.@]
1535  *
1536  * See RegDeleteValueA.
1537  */
1538 DWORD WINAPI RegDeleteValueW( HKEY hkey, LPCWSTR name )
1539 {
1540     UNICODE_STRING nameW;
1541
1542     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1543
1544     RtlInitUnicodeString( &nameW, name );
1545     return RtlNtStatusToDosError( NtDeleteValueKey( hkey, &nameW ) );
1546 }
1547
1548
1549 /******************************************************************************
1550  * RegDeleteValueA   [ADVAPI32.@]
1551  *
1552  * Delete a value from the registry.
1553  *
1554  * PARAMS
1555  *  hkey [I] Registry handle of the key holding the value
1556  *  name [I] Name of the value under hkey to delete
1557  *
1558  * RETURNS
1559  *  Success: ERROR_SUCCESS
1560  *  Failure: nonzero error code from Winerror.h
1561  */
1562 DWORD WINAPI RegDeleteValueA( HKEY hkey, LPCSTR name )
1563 {
1564     STRING nameA;
1565     NTSTATUS status;
1566
1567     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1568
1569     RtlInitAnsiString( &nameA, name );
1570     if (!(status = RtlAnsiStringToUnicodeString( &NtCurrentTeb()->StaticUnicodeString,
1571                                                  &nameA, FALSE )))
1572         status = NtDeleteValueKey( hkey, &NtCurrentTeb()->StaticUnicodeString );
1573     return RtlNtStatusToDosError( status );
1574 }
1575
1576
1577 /******************************************************************************
1578  * RegLoadKeyW   [ADVAPI32.@]
1579  *
1580  * PARAMS
1581  *  hkey      [I] Handle of open key
1582  *  subkey    [I] Address of name of subkey
1583  *  filename  [I] Address of filename for registry information
1584  *
1585  * RETURNS
1586  *  Success: ERROR_SUCCES
1587  *  Failure: nonzero error code from Winerror.h
1588  */
1589 LONG WINAPI RegLoadKeyW( HKEY hkey, LPCWSTR subkey, LPCWSTR filename )
1590 {
1591     HANDLE file;
1592     DWORD ret, len, err = GetLastError();
1593     HKEY shkey;
1594
1595     TRACE( "(%p,%s,%s)\n", hkey, debugstr_w(subkey), debugstr_w(filename) );
1596
1597     if (!filename || !*filename) return ERROR_INVALID_PARAMETER;
1598     if (!subkey || !*subkey) return ERROR_INVALID_PARAMETER;
1599     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1600
1601     len = strlenW( subkey ) * sizeof(WCHAR);
1602     if (len > MAX_PATH*sizeof(WCHAR)) return ERROR_INVALID_PARAMETER;
1603
1604     if ((file = CreateFileW( filename, GENERIC_READ, 0, NULL, OPEN_EXISTING,
1605                              FILE_ATTRIBUTE_NORMAL, 0 )) == INVALID_HANDLE_VALUE)
1606     {
1607         ret = GetLastError();
1608         goto done;
1609     }
1610
1611     RegCreateKeyW(hkey,subkey,&shkey);
1612
1613     SERVER_START_REQ( load_registry )
1614     {
1615         req->hkey  = shkey;
1616         req->file  = file;
1617         wine_server_add_data( req, subkey, len );
1618         ret = RtlNtStatusToDosError( wine_server_call(req) );
1619     }
1620     SERVER_END_REQ;
1621     CloseHandle( file );
1622     RegCloseKey(shkey);
1623
1624  done:
1625     SetLastError( err );  /* restore the last error code */
1626     return ret;
1627 }
1628
1629
1630 /******************************************************************************
1631  * RegLoadKeyA   [ADVAPI32.@]
1632  *
1633  * see RegLoadKeyW
1634  */
1635 LONG WINAPI RegLoadKeyA( HKEY hkey, LPCSTR subkey, LPCSTR filename )
1636 {
1637     WCHAR buffer[MAX_PATH];
1638     HANDLE file;
1639     DWORD ret, len, err = GetLastError();
1640     HKEY shkey;
1641
1642     TRACE( "(%p,%s,%s)\n", hkey, debugstr_a(subkey), debugstr_a(filename) );
1643
1644     if (!filename || !*filename) return ERROR_INVALID_PARAMETER;
1645     if (!subkey || !*subkey) return ERROR_INVALID_PARAMETER;
1646     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1647
1648     if (!(len = MultiByteToWideChar( CP_ACP, 0, subkey, strlen(subkey), buffer, MAX_PATH )))
1649         return ERROR_INVALID_PARAMETER;
1650
1651     if ((file = CreateFileA( filename, GENERIC_READ, 0, NULL, OPEN_EXISTING,
1652                              FILE_ATTRIBUTE_NORMAL, 0 )) == INVALID_HANDLE_VALUE)
1653     {
1654         ret = GetLastError();
1655         goto done;
1656     }
1657
1658     RegCreateKeyA(hkey,subkey,&shkey);
1659
1660     SERVER_START_REQ( load_registry )
1661     {
1662         req->hkey  = shkey;
1663         req->file  = file;
1664         wine_server_add_data( req, buffer, len * sizeof(WCHAR) );
1665         ret = RtlNtStatusToDosError( wine_server_call(req) );
1666     }
1667     SERVER_END_REQ;
1668     CloseHandle( file );
1669     RegCloseKey(shkey);
1670
1671  done:
1672     SetLastError( err );  /* restore the last error code */
1673     return ret;
1674 }
1675
1676
1677 /******************************************************************************
1678  * RegSaveKeyW   [ADVAPI32.@]
1679  *
1680  * PARAMS
1681  *  hkey   [I] Handle of key where save begins
1682  *  lpFile [I] Address of filename to save to
1683  *  sa     [I] Address of security structure
1684  *
1685  * RETURNS
1686  *  Success: ERROR_SUCCESS
1687  *  Failure: nonzero error code from Winerror.h
1688  */
1689 LONG WINAPI RegSaveKeyW( HKEY hkey, LPCWSTR file, LPSECURITY_ATTRIBUTES sa )
1690 {
1691     static const WCHAR format[] =
1692         {'r','e','g','%','0','4','x','.','t','m','p',0};
1693     WCHAR buffer[MAX_PATH];
1694     int count = 0;
1695     LPWSTR nameW;
1696     DWORD ret, err;
1697     HANDLE handle;
1698
1699     TRACE( "(%p,%s,%p)\n", hkey, debugstr_w(file), sa );
1700
1701     if (!file || !*file) return ERROR_INVALID_PARAMETER;
1702     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1703
1704     err = GetLastError();
1705     GetFullPathNameW( file, sizeof(buffer)/sizeof(WCHAR), buffer, &nameW );
1706
1707     for (;;)
1708     {
1709         snprintfW( nameW, 16, format, count++ );
1710         handle = CreateFileW( buffer, GENERIC_WRITE, 0, NULL,
1711                             CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
1712         if (handle != INVALID_HANDLE_VALUE) break;
1713         if ((ret = GetLastError()) != ERROR_ALREADY_EXISTS) goto done;
1714
1715         /* Something gone haywire ? Please report if this happens abnormally */
1716         if (count >= 100)
1717             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);
1718     }
1719
1720     SERVER_START_REQ( save_registry )
1721     {
1722         req->hkey = hkey;
1723         req->file = handle;
1724         ret = RtlNtStatusToDosError( wine_server_call( req ) );
1725     }
1726     SERVER_END_REQ;
1727
1728     CloseHandle( handle );
1729     if (!ret)
1730     {
1731         if (!MoveFileExW( buffer, file, MOVEFILE_REPLACE_EXISTING ))
1732         {
1733             ERR( "Failed to move %s to %s\n", debugstr_w(buffer),
1734                 debugstr_w(file) );
1735             ret = GetLastError();
1736         }
1737     }
1738     if (ret) DeleteFileW( buffer );
1739
1740 done:
1741     SetLastError( err );  /* restore last error code */
1742     return ret;
1743 }
1744
1745
1746 /******************************************************************************
1747  * RegSaveKeyA  [ADVAPI32.@]
1748  *
1749  * see RegSaveKeyW
1750  */
1751 LONG WINAPI RegSaveKeyA( HKEY hkey, LPCSTR file, LPSECURITY_ATTRIBUTES sa )
1752 {
1753     UNICODE_STRING *fileW = &NtCurrentTeb()->StaticUnicodeString;
1754     NTSTATUS status;
1755     STRING fileA;
1756
1757     RtlInitAnsiString(&fileA, file);
1758     if ((status = RtlAnsiStringToUnicodeString(fileW, &fileA, FALSE)))
1759         return RtlNtStatusToDosError( status );
1760     return RegSaveKeyW(hkey, fileW->Buffer, sa);
1761 }
1762
1763
1764 /******************************************************************************
1765  * RegRestoreKeyW [ADVAPI32.@]
1766  *
1767  * PARAMS
1768  *  hkey    [I] Handle of key where restore begins
1769  *  lpFile  [I] Address of filename containing saved tree
1770  *  dwFlags [I] Optional flags
1771  *
1772  * RETURNS
1773  *  Success: ERROR_SUCCESS
1774  *  Failure: nonzero error code from Winerror.h
1775  */
1776 LONG WINAPI RegRestoreKeyW( HKEY hkey, LPCWSTR lpFile, DWORD dwFlags )
1777 {
1778     TRACE("(%p,%s,%ld)\n",hkey,debugstr_w(lpFile),dwFlags);
1779
1780     /* It seems to do this check before the hkey check */
1781     if (!lpFile || !*lpFile)
1782         return ERROR_INVALID_PARAMETER;
1783
1784     FIXME("(%p,%s,%ld): stub\n",hkey,debugstr_w(lpFile),dwFlags);
1785
1786     /* Check for file existence */
1787
1788     return ERROR_SUCCESS;
1789 }
1790
1791
1792 /******************************************************************************
1793  * RegRestoreKeyA [ADVAPI32.@]
1794  *
1795  * see RegRestoreKeyW
1796  */
1797 LONG WINAPI RegRestoreKeyA( HKEY hkey, LPCSTR lpFile, DWORD dwFlags )
1798 {
1799     UNICODE_STRING lpFileW;
1800     LONG ret;
1801
1802     RtlCreateUnicodeStringFromAsciiz( &lpFileW, lpFile );
1803     ret = RegRestoreKeyW( hkey, lpFileW.Buffer, dwFlags );
1804     RtlFreeUnicodeString( &lpFileW );
1805     return ret;
1806 }
1807
1808
1809 /******************************************************************************
1810  * RegUnLoadKeyW [ADVAPI32.@]
1811  *
1812  * PARAMS
1813  *  hkey     [I] Handle of open key
1814  *  lpSubKey [I] Address of name of subkey to unload
1815  *
1816  * RETURNS
1817  *  Success: ERROR_SUCCESS
1818  *  Failure: nonzero error code from Winerror.h
1819  */
1820 LONG WINAPI RegUnLoadKeyW( HKEY hkey, LPCWSTR lpSubKey )
1821 {
1822     DWORD ret;
1823     HKEY shkey;
1824
1825     TRACE("(%p,%s)\n",hkey, debugstr_w(lpSubKey));
1826
1827     ret = RegOpenKeyW(hkey,lpSubKey,&shkey);
1828     if( ret )
1829         return ERROR_INVALID_PARAMETER;
1830
1831     SERVER_START_REQ( unload_registry )
1832     {
1833         req->hkey  = shkey;
1834         ret = RtlNtStatusToDosError( wine_server_call(req) );
1835     }
1836     SERVER_END_REQ;
1837     RegCloseKey(shkey);
1838
1839     return ret;
1840 }
1841
1842
1843 /******************************************************************************
1844  * RegUnLoadKeyA [ADVAPI32.@]
1845  *
1846  * see RegUnLoadKeyW
1847  */
1848 LONG WINAPI RegUnLoadKeyA( HKEY hkey, LPCSTR lpSubKey )
1849 {
1850     UNICODE_STRING lpSubKeyW;
1851     LONG ret;
1852
1853     RtlCreateUnicodeStringFromAsciiz( &lpSubKeyW, lpSubKey );
1854     ret = RegUnLoadKeyW( hkey, lpSubKeyW.Buffer );
1855     RtlFreeUnicodeString( &lpSubKeyW );
1856     return ret;
1857 }
1858
1859
1860 /******************************************************************************
1861  * RegReplaceKeyW [ADVAPI32.@]
1862  *
1863  * PARAMS
1864  *  hkey      [I] Handle of open key
1865  *  lpSubKey  [I] Address of name of subkey
1866  *  lpNewFile [I] Address of filename for file with new data
1867  *  lpOldFile [I] Address of filename for backup file
1868  *
1869  * RETURNS
1870  *  Success: ERROR_SUCCESS
1871  *  Failure: nonzero error code from Winerror.h
1872  */
1873 LONG WINAPI RegReplaceKeyW( HKEY hkey, LPCWSTR lpSubKey, LPCWSTR lpNewFile,
1874                               LPCWSTR lpOldFile )
1875 {
1876     FIXME("(%p,%s,%s,%s): stub\n", hkey, debugstr_w(lpSubKey),
1877           debugstr_w(lpNewFile),debugstr_w(lpOldFile));
1878     return ERROR_SUCCESS;
1879 }
1880
1881
1882 /******************************************************************************
1883  * RegReplaceKeyA [ADVAPI32.@]
1884  *
1885  * see RegReplaceKeyW
1886  */
1887 LONG WINAPI RegReplaceKeyA( HKEY hkey, LPCSTR lpSubKey, LPCSTR lpNewFile,
1888                               LPCSTR lpOldFile )
1889 {
1890     UNICODE_STRING lpSubKeyW;
1891     UNICODE_STRING lpNewFileW;
1892     UNICODE_STRING lpOldFileW;
1893     LONG ret;
1894
1895     RtlCreateUnicodeStringFromAsciiz( &lpSubKeyW, lpSubKey );
1896     RtlCreateUnicodeStringFromAsciiz( &lpOldFileW, lpOldFile );
1897     RtlCreateUnicodeStringFromAsciiz( &lpNewFileW, lpNewFile );
1898     ret = RegReplaceKeyW( hkey, lpSubKeyW.Buffer, lpNewFileW.Buffer, lpOldFileW.Buffer );
1899     RtlFreeUnicodeString( &lpOldFileW );
1900     RtlFreeUnicodeString( &lpNewFileW );
1901     RtlFreeUnicodeString( &lpSubKeyW );
1902     return ret;
1903 }
1904
1905
1906 /******************************************************************************
1907  * RegSetKeySecurity [ADVAPI32.@]
1908  *
1909  * PARAMS
1910  *  hkey          [I] Open handle of key to set
1911  *  SecurityInfo  [I] Descriptor contents
1912  *  pSecurityDesc [I] Address of descriptor for key
1913  *
1914  * RETURNS
1915  *  Success: ERROR_SUCCESS
1916  *  Failure: nonzero error code from Winerror.h
1917  */
1918 LONG WINAPI RegSetKeySecurity( HKEY hkey, SECURITY_INFORMATION SecurityInfo,
1919                                PSECURITY_DESCRIPTOR pSecurityDesc )
1920 {
1921     TRACE("(%p,%ld,%p)\n",hkey,SecurityInfo,pSecurityDesc);
1922
1923     /* It seems to perform this check before the hkey check */
1924     if ((SecurityInfo & OWNER_SECURITY_INFORMATION) ||
1925         (SecurityInfo & GROUP_SECURITY_INFORMATION) ||
1926         (SecurityInfo & DACL_SECURITY_INFORMATION) ||
1927         (SecurityInfo & SACL_SECURITY_INFORMATION)) {
1928         /* Param OK */
1929     } else
1930         return ERROR_INVALID_PARAMETER;
1931
1932     if (!pSecurityDesc)
1933         return ERROR_INVALID_PARAMETER;
1934
1935     FIXME(":(%p,%ld,%p): stub\n",hkey,SecurityInfo,pSecurityDesc);
1936
1937     return ERROR_SUCCESS;
1938 }
1939
1940
1941 /******************************************************************************
1942  * RegGetKeySecurity [ADVAPI32.@]
1943  *
1944  * Get a copy of the security descriptor for a given registry key.
1945  *
1946  * PARAMS
1947  *  hkey                   [I]   Open handle of key to set
1948  *  SecurityInformation    [I]   Descriptor contents
1949  *  pSecurityDescriptor    [O]   Address of descriptor for key
1950  *  lpcbSecurityDescriptor [I/O] Address of size of buffer and description
1951  *
1952  * RETURNS
1953  *  Success: ERROR_SUCCESS
1954  *  Failure: Error code
1955  */
1956 LONG WINAPI RegGetKeySecurity( HKEY hkey, SECURITY_INFORMATION SecurityInformation,
1957                                PSECURITY_DESCRIPTOR pSecurityDescriptor,
1958                                LPDWORD lpcbSecurityDescriptor )
1959 {
1960     TRACE("(%p,%ld,%p,%ld)\n",hkey,SecurityInformation,pSecurityDescriptor,
1961           lpcbSecurityDescriptor?*lpcbSecurityDescriptor:0);
1962
1963     /* FIXME: Check for valid SecurityInformation values */
1964
1965     if (*lpcbSecurityDescriptor < sizeof(SECURITY_DESCRIPTOR))
1966         return ERROR_INSUFFICIENT_BUFFER;
1967
1968     FIXME("(%p,%ld,%p,%ld): stub\n",hkey,SecurityInformation,
1969           pSecurityDescriptor,lpcbSecurityDescriptor?*lpcbSecurityDescriptor:0);
1970
1971     /* Do not leave security descriptor filled with garbage */
1972     RtlCreateSecurityDescriptor(pSecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
1973
1974     return ERROR_SUCCESS;
1975 }
1976
1977
1978 /******************************************************************************
1979  * RegFlushKey [ADVAPI32.@]
1980  * 
1981  * Immediately write a registry key to registry.
1982  *
1983  * PARAMS
1984  *  hkey [I] Handle of key to write
1985  *
1986  * RETURNS
1987  *  Success: ERROR_SUCCESS
1988  *  Failure: Error code
1989  */
1990 DWORD WINAPI RegFlushKey( HKEY hkey )
1991 {
1992     hkey = get_special_root_hkey( hkey );
1993     if (!hkey) return ERROR_INVALID_HANDLE;
1994
1995     return RtlNtStatusToDosError( NtFlushKey( hkey ) );
1996 }
1997
1998
1999 /******************************************************************************
2000  * RegConnectRegistryW [ADVAPI32.@]
2001  *
2002  * PARAMS
2003  *  lpMachineName [I] Address of name of remote computer
2004  *  hHey          [I] Predefined registry handle
2005  *  phkResult     [I] Address of buffer for remote registry handle
2006  *
2007  * RETURNS
2008  *  Success: ERROR_SUCCESS
2009  *  Failure: nonzero error code from Winerror.h
2010  */
2011 LONG WINAPI RegConnectRegistryW( LPCWSTR lpMachineName, HKEY hKey,
2012                                    PHKEY phkResult )
2013 {
2014     LONG ret;
2015
2016     TRACE("(%s,%p,%p): stub\n",debugstr_w(lpMachineName),hKey,phkResult);
2017
2018     if (!lpMachineName || !*lpMachineName) {
2019         /* Use the local machine name */
2020         ret = RegOpenKeyW( hKey, NULL, phkResult );
2021     }
2022     else if (lpMachineName[0] != '\\' || lpMachineName[1] != '\\')
2023         ret = ERROR_BAD_NETPATH;
2024     else
2025     {
2026         WCHAR compName[MAX_COMPUTERNAME_LENGTH + 1];
2027         DWORD len = sizeof(compName) / sizeof(WCHAR);
2028
2029         if (GetComputerNameW(compName, &len))
2030         {
2031             if (!strcmpiW(lpMachineName + 2, compName))
2032                 ret = RegOpenKeyW(hKey, NULL, phkResult);
2033             else
2034             {
2035                 FIXME("Cannot connect to %s\n",debugstr_w(lpMachineName));
2036                 ret = ERROR_BAD_NETPATH;
2037             }
2038         }
2039         else
2040             ret = GetLastError();
2041     }
2042     return ret;
2043 }
2044
2045
2046 /******************************************************************************
2047  * RegConnectRegistryA [ADVAPI32.@]
2048  *
2049  * see RegConnectRegistryW
2050  */
2051 LONG WINAPI RegConnectRegistryA( LPCSTR machine, HKEY hkey, PHKEY reskey )
2052 {
2053     UNICODE_STRING machineW;
2054     LONG ret;
2055
2056     RtlCreateUnicodeStringFromAsciiz( &machineW, machine );
2057     ret = RegConnectRegistryW( machineW.Buffer, hkey, reskey );
2058     RtlFreeUnicodeString( &machineW );
2059     return ret;
2060 }
2061
2062
2063 /******************************************************************************
2064  * RegNotifyChangeKeyValue [ADVAPI32.@]
2065  *
2066  * PARAMS
2067  *  hkey            [I] Handle of key to watch
2068  *  fWatchSubTree   [I] Flag for subkey notification
2069  *  fdwNotifyFilter [I] Changes to be reported
2070  *  hEvent          [I] Handle of signaled event
2071  *  fAsync          [I] Flag for asynchronous reporting
2072  *
2073  * RETURNS
2074  *  Success: ERROR_SUCCESS
2075  *  Failure: nonzero error code from Winerror.h
2076  */
2077 LONG WINAPI RegNotifyChangeKeyValue( HKEY hkey, BOOL fWatchSubTree,
2078                                      DWORD fdwNotifyFilter, HANDLE hEvent,
2079                                      BOOL fAsync )
2080 {
2081     LONG ret;
2082
2083     TRACE("(%p,%i,%ld,%p,%i)\n",hkey,fWatchSubTree,fdwNotifyFilter,
2084           hEvent,fAsync);
2085
2086     if( !fAsync )
2087         hEvent = CreateEventW(NULL, 0, 0, NULL);
2088
2089     SERVER_START_REQ( set_registry_notification )
2090     {
2091         req->hkey    = hkey;
2092         req->event   = hEvent;
2093         req->subtree = fWatchSubTree;
2094         req->filter  = fdwNotifyFilter;
2095         ret = RtlNtStatusToDosError( wine_server_call(req) );
2096     }
2097     SERVER_END_REQ;
2098  
2099     if( !fAsync )
2100     {
2101         if( ret == ERROR_SUCCESS )
2102             WaitForSingleObject( hEvent, INFINITE );
2103         CloseHandle( hEvent );
2104     }
2105
2106     return ret;
2107 }
2108
2109 /******************************************************************************
2110  * RegOpenUserClassesRoot [ADVAPI32.@]
2111  *
2112  * Open the HKEY_CLASSES_ROOT key for a user.
2113  *
2114  * PARAMS
2115  *  hToken     [I] Handle of token representing the user
2116  *  dwOptions  [I] Reserved, nust be 0
2117  *  samDesired [I] Desired access rights
2118  *  phkResult  [O] Destination for the resulting key handle
2119  *
2120  * RETURNS
2121  *  Success: ERROR_SUCCESS
2122  *  Failure: nonzero error code from Winerror.h
2123  * 
2124  * NOTES
2125  *  On Windows 2000 and upwards the HKEY_CLASSES_ROOT key is a view of the
2126  *  "HKEY_LOCAL_MACHINE\Software\Classes" and the
2127  *  "HKEY_CURRENT_USER\Software\Classes" keys merged together.
2128  */
2129 LONG WINAPI RegOpenUserClassesRoot(
2130     HANDLE hToken,
2131     DWORD dwOptions,
2132     REGSAM samDesired,
2133     PHKEY phkResult
2134 )
2135 {
2136     FIXME("(%p, 0x%lx, 0x%lx, %p) semi-stub\n", hToken, dwOptions, samDesired, phkResult);
2137
2138     *phkResult = HKEY_CLASSES_ROOT;
2139     return ERROR_SUCCESS;
2140 }