Intern all the atoms we'll need in one step to avoid multiple server
[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  * PARAMS
149  *    hkey       [I] Handle of an open key
150  *    name       [I] Address of subkey name
151  *    reserved   [I] Reserved - must be 0
152  *    class      [I] Address of class string
153  *    options    [I] Special options flag
154  *    access     [I] Desired security access
155  *    sa         [I] Address of key security structure
156  *    retkey     [O] Address of buffer for opened handle
157  *    dispos     [O] Receives REG_CREATED_NEW_KEY or REG_OPENED_EXISTING_KEY
158  *
159  * NOTES
160  *  in case of failing retkey remains untouched
161  *
162  * FIXME MAXIMUM_ALLOWED in access mask not supported by server
163  */
164 DWORD WINAPI RegCreateKeyExW( HKEY hkey, LPCWSTR name, DWORD reserved, LPCWSTR class,
165                               DWORD options, REGSAM access, SECURITY_ATTRIBUTES *sa,
166                               PHKEY retkey, LPDWORD dispos )
167 {
168     OBJECT_ATTRIBUTES attr;
169     UNICODE_STRING nameW, classW;
170
171     if (reserved) return ERROR_INVALID_PARAMETER;
172     if (!(access & KEY_ACCESS_MASK) || (access & ~KEY_ACCESS_MASK)) return ERROR_ACCESS_DENIED;
173     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
174
175     attr.Length = sizeof(attr);
176     attr.RootDirectory = hkey;
177     attr.ObjectName = &nameW;
178     attr.Attributes = 0;
179     attr.SecurityDescriptor = NULL;
180     attr.SecurityQualityOfService = NULL;
181     RtlInitUnicodeString( &nameW, name );
182     RtlInitUnicodeString( &classW, class );
183
184     return RtlNtStatusToDosError( NtCreateKey( retkey, access, &attr, 0,
185                                                &classW, options, dispos ) );
186 }
187
188
189 /******************************************************************************
190  *           RegCreateKeyExA   [ADVAPI32.@]
191  *
192  * FIXME MAXIMUM_ALLOWED in access mask not supported by server
193  */
194 DWORD WINAPI RegCreateKeyExA( HKEY hkey, LPCSTR name, DWORD reserved, LPCSTR class,
195                               DWORD options, REGSAM access, SECURITY_ATTRIBUTES *sa,
196                               PHKEY retkey, LPDWORD dispos )
197 {
198     OBJECT_ATTRIBUTES attr;
199     UNICODE_STRING classW;
200     ANSI_STRING nameA, classA;
201     NTSTATUS status;
202
203     if (reserved) return ERROR_INVALID_PARAMETER;
204     if (!is_version_nt()) access = KEY_ALL_ACCESS;  /* Win95 ignores the access mask */
205     else if (!(access & KEY_ACCESS_MASK) || (access & ~KEY_ACCESS_MASK)) return ERROR_ACCESS_DENIED;
206     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
207
208     attr.Length = sizeof(attr);
209     attr.RootDirectory = hkey;
210     attr.ObjectName = &NtCurrentTeb()->StaticUnicodeString;
211     attr.Attributes = 0;
212     attr.SecurityDescriptor = NULL;
213     attr.SecurityQualityOfService = NULL;
214     RtlInitAnsiString( &nameA, name );
215     RtlInitAnsiString( &classA, class );
216
217     if (!(status = RtlAnsiStringToUnicodeString( &NtCurrentTeb()->StaticUnicodeString,
218                                                  &nameA, FALSE )))
219     {
220         if (!(status = RtlAnsiStringToUnicodeString( &classW, &classA, TRUE )))
221         {
222             status = NtCreateKey( retkey, access, &attr, 0, &classW, options, dispos );
223             RtlFreeUnicodeString( &classW );
224         }
225     }
226     return RtlNtStatusToDosError( status );
227 }
228
229
230 /******************************************************************************
231  *           RegCreateKeyW   [ADVAPI32.@]
232  */
233 DWORD WINAPI RegCreateKeyW( HKEY hkey, LPCWSTR name, PHKEY retkey )
234 {
235     /* FIXME: previous implementation converted ERROR_INVALID_HANDLE to ERROR_BADKEY, */
236     /* but at least my version of NT (4.0 SP5) doesn't do this.  -- AJ */
237     return RegCreateKeyExW( hkey, name, 0, NULL, REG_OPTION_NON_VOLATILE,
238                             KEY_ALL_ACCESS, NULL, retkey, NULL );
239 }
240
241
242 /******************************************************************************
243  *           RegCreateKeyA   [ADVAPI32.@]
244  */
245 DWORD WINAPI RegCreateKeyA( HKEY hkey, LPCSTR name, PHKEY retkey )
246 {
247     return RegCreateKeyExA( hkey, name, 0, NULL, REG_OPTION_NON_VOLATILE,
248                             KEY_ALL_ACCESS, NULL, retkey, NULL );
249 }
250
251
252
253 /******************************************************************************
254  *           RegOpenKeyExW   [ADVAPI32.@]
255  *
256  * Opens the specified key
257  *
258  * Unlike RegCreateKeyEx, this does not create the key if it does not exist.
259  *
260  * PARAMS
261  *    hkey       [I] Handle of open key
262  *    name       [I] Name of subkey to open
263  *    reserved   [I] Reserved - must be zero
264  *    access     [I] Security access mask
265  *    retkey     [O] Handle to open key
266  *
267  * RETURNS
268  *    Success: ERROR_SUCCESS
269  *    Failure: Error code
270  *
271  * NOTES
272  *  in case of failing is retkey = 0
273  */
274 DWORD WINAPI RegOpenKeyExW( HKEY hkey, LPCWSTR name, DWORD reserved, REGSAM access, PHKEY retkey )
275 {
276     OBJECT_ATTRIBUTES attr;
277     UNICODE_STRING nameW;
278
279     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
280
281     attr.Length = sizeof(attr);
282     attr.RootDirectory = hkey;
283     attr.ObjectName = &nameW;
284     attr.Attributes = 0;
285     attr.SecurityDescriptor = NULL;
286     attr.SecurityQualityOfService = NULL;
287     RtlInitUnicodeString( &nameW, name );
288     return RtlNtStatusToDosError( NtOpenKey( retkey, access, &attr ) );
289 }
290
291
292 /******************************************************************************
293  *           RegOpenKeyExA   [ADVAPI32.@]
294  */
295 DWORD WINAPI RegOpenKeyExA( HKEY hkey, LPCSTR name, DWORD reserved, REGSAM access, PHKEY retkey )
296 {
297     OBJECT_ATTRIBUTES attr;
298     STRING nameA;
299     NTSTATUS status;
300
301     if (!is_version_nt()) access = KEY_ALL_ACCESS;  /* Win95 ignores the access mask */
302
303     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
304
305     attr.Length = sizeof(attr);
306     attr.RootDirectory = hkey;
307     attr.ObjectName = &NtCurrentTeb()->StaticUnicodeString;
308     attr.Attributes = 0;
309     attr.SecurityDescriptor = NULL;
310     attr.SecurityQualityOfService = NULL;
311
312     RtlInitAnsiString( &nameA, name );
313     if (!(status = RtlAnsiStringToUnicodeString( &NtCurrentTeb()->StaticUnicodeString,
314                                                  &nameA, FALSE )))
315     {
316         status = NtOpenKey( retkey, access, &attr );
317     }
318     return RtlNtStatusToDosError( status );
319 }
320
321
322 /******************************************************************************
323  *           RegOpenKeyW   [ADVAPI32.@]
324  *
325  * PARAMS
326  *    hkey    [I] Handle of open key
327  *    name    [I] Address of name of subkey to open
328  *    retkey  [O] Handle to open key
329  *
330  * RETURNS
331  *    Success: ERROR_SUCCESS
332  *    Failure: Error code
333  *
334  * NOTES
335  *  in case of failing is retkey = 0
336  */
337 DWORD WINAPI RegOpenKeyW( HKEY hkey, LPCWSTR name, PHKEY retkey )
338 {
339     return RegOpenKeyExW( hkey, name, 0, KEY_ALL_ACCESS, retkey );
340 }
341
342
343 /******************************************************************************
344  *           RegOpenKeyA   [ADVAPI32.@]
345  */
346 DWORD WINAPI RegOpenKeyA( HKEY hkey, LPCSTR name, PHKEY retkey )
347 {
348     return RegOpenKeyExA( hkey, name, 0, KEY_ALL_ACCESS, retkey );
349 }
350
351
352 /******************************************************************************
353  *           RegOpenCurrentUser   [ADVAPI32.@]
354  * FIXME: This function is supposed to retrieve a handle to the
355  * HKEY_CURRENT_USER for the user the current thread is impersonating.
356  * Since Wine does not currently allow threads to impersonate other users,
357  * this stub should work fine.
358  */
359 DWORD WINAPI RegOpenCurrentUser( REGSAM access, PHKEY retkey )
360 {
361     return RegOpenKeyExA( HKEY_CURRENT_USER, "", 0, access, retkey );
362 }
363
364
365
366 /******************************************************************************
367  *           RegEnumKeyExW   [ADVAPI32.@]
368  *
369  * PARAMS
370  *    hkey         [I] Handle to key to enumerate
371  *    index        [I] Index of subkey to enumerate
372  *    name         [O] Buffer for subkey name
373  *    name_len     [O] Size of subkey buffer
374  *    reserved     [I] Reserved
375  *    class        [O] Buffer for class string
376  *    class_len    [O] Size of class buffer
377  *    ft           [O] Time key last written to
378  */
379 DWORD WINAPI RegEnumKeyExW( HKEY hkey, DWORD index, LPWSTR name, LPDWORD name_len,
380                             LPDWORD reserved, LPWSTR class, LPDWORD class_len, FILETIME *ft )
381 {
382     NTSTATUS status;
383     char buffer[256], *buf_ptr = buffer;
384     KEY_NODE_INFORMATION *info = (KEY_NODE_INFORMATION *)buffer;
385     DWORD total_size;
386
387     TRACE( "(%p,%ld,%p,%p(%ld),%p,%p,%p,%p)\n", hkey, index, name, name_len,
388            name_len ? *name_len : -1, reserved, class, class_len, ft );
389
390     if (reserved) return ERROR_INVALID_PARAMETER;
391     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
392
393     status = NtEnumerateKey( hkey, index, KeyNodeInformation,
394                              buffer, sizeof(buffer), &total_size );
395
396     while (status == STATUS_BUFFER_OVERFLOW)
397     {
398         /* retry with a dynamically allocated buffer */
399         if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
400         if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
401             return ERROR_NOT_ENOUGH_MEMORY;
402         info = (KEY_NODE_INFORMATION *)buf_ptr;
403         status = NtEnumerateKey( hkey, index, KeyNodeInformation,
404                                  buf_ptr, total_size, &total_size );
405     }
406
407     if (!status)
408     {
409         DWORD len = info->NameLength / sizeof(WCHAR);
410         DWORD cls_len = info->ClassLength / sizeof(WCHAR);
411
412         if (ft) *ft = *(FILETIME *)&info->LastWriteTime;
413
414         if (len >= *name_len || (class && class_len && (cls_len >= *class_len)))
415             status = STATUS_BUFFER_OVERFLOW;
416         else
417         {
418             *name_len = len;
419             memcpy( name, info->Name, info->NameLength );
420             name[len] = 0;
421             if (class_len)
422             {
423                 *class_len = cls_len;
424                 if (class)
425                 {
426                     memcpy( class, buf_ptr + info->ClassOffset, info->ClassLength );
427                     class[cls_len] = 0;
428                 }
429             }
430         }
431     }
432
433     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
434     return RtlNtStatusToDosError( status );
435 }
436
437
438 /******************************************************************************
439  *           RegEnumKeyExA   [ADVAPI32.@]
440  */
441 DWORD WINAPI RegEnumKeyExA( HKEY hkey, DWORD index, LPSTR name, LPDWORD name_len,
442                             LPDWORD reserved, LPSTR class, LPDWORD class_len, FILETIME *ft )
443 {
444     NTSTATUS status;
445     char buffer[256], *buf_ptr = buffer;
446     KEY_NODE_INFORMATION *info = (KEY_NODE_INFORMATION *)buffer;
447     DWORD total_size;
448
449     TRACE( "(%p,%ld,%p,%p(%ld),%p,%p,%p,%p)\n", hkey, index, name, name_len,
450            name_len ? *name_len : -1, reserved, class, class_len, ft );
451
452     if (reserved) return ERROR_INVALID_PARAMETER;
453     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
454
455     status = NtEnumerateKey( hkey, index, KeyNodeInformation,
456                              buffer, sizeof(buffer), &total_size );
457
458     while (status == STATUS_BUFFER_OVERFLOW)
459     {
460         /* retry with a dynamically allocated buffer */
461         if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
462         if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
463             return ERROR_NOT_ENOUGH_MEMORY;
464         info = (KEY_NODE_INFORMATION *)buf_ptr;
465         status = NtEnumerateKey( hkey, index, KeyNodeInformation,
466                                  buf_ptr, total_size, &total_size );
467     }
468
469     if (!status)
470     {
471         DWORD len, cls_len;
472
473         RtlUnicodeToMultiByteSize( &len, info->Name, info->NameLength );
474         RtlUnicodeToMultiByteSize( &cls_len, (WCHAR *)(buf_ptr + info->ClassOffset),
475                                    info->ClassLength );
476         if (ft) *ft = *(FILETIME *)&info->LastWriteTime;
477
478         if (len >= *name_len || (class && class_len && (cls_len >= *class_len)))
479             status = STATUS_BUFFER_OVERFLOW;
480         else
481         {
482             *name_len = len;
483             RtlUnicodeToMultiByteN( name, len, NULL, info->Name, info->NameLength );
484             name[len] = 0;
485             if (class_len)
486             {
487                 *class_len = cls_len;
488                 if (class)
489                 {
490                     RtlUnicodeToMultiByteN( class, cls_len, NULL,
491                                             (WCHAR *)(buf_ptr + info->ClassOffset),
492                                             info->ClassLength );
493                     class[cls_len] = 0;
494                 }
495             }
496         }
497     }
498
499     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
500     return RtlNtStatusToDosError( status );
501 }
502
503
504 /******************************************************************************
505  *           RegEnumKeyW   [ADVAPI32.@]
506  */
507 DWORD WINAPI RegEnumKeyW( HKEY hkey, DWORD index, LPWSTR name, DWORD name_len )
508 {
509     return RegEnumKeyExW( hkey, index, name, &name_len, NULL, NULL, NULL, NULL );
510 }
511
512
513 /******************************************************************************
514  *           RegEnumKeyA   [ADVAPI32.@]
515  */
516 DWORD WINAPI RegEnumKeyA( HKEY hkey, DWORD index, LPSTR name, DWORD name_len )
517 {
518     return RegEnumKeyExA( hkey, index, name, &name_len, NULL, NULL, NULL, NULL );
519 }
520
521
522 /******************************************************************************
523  *           RegQueryInfoKeyW   [ADVAPI32.@]
524  *
525  * PARAMS
526  *    hkey       [I] Handle to key to query
527  *    class      [O] Buffer for class string
528  *    class_len  [O] Size of class string buffer
529  *    reserved   [I] Reserved
530  *    subkeys    [O] Buffer for number of subkeys
531  *    max_subkey [O] Buffer for longest subkey name length
532  *    max_class  [O] Buffer for longest class string length
533  *    values     [O] Buffer for number of value entries
534  *    max_value  [O] Buffer for longest value name length
535  *    max_data   [O] Buffer for longest value data length
536  *    security   [O] Buffer for security descriptor length
537  *    modif      [O] Modification time
538  *
539  * - win95 allows class to be valid and class_len to be NULL
540  * - winnt returns ERROR_INVALID_PARAMETER if class is valid and class_len is NULL
541  * - both allow class to be NULL and class_len to be NULL
542  * (it's hard to test validity, so test !NULL instead)
543  */
544 DWORD WINAPI RegQueryInfoKeyW( HKEY hkey, LPWSTR class, LPDWORD class_len, LPDWORD reserved,
545                                LPDWORD subkeys, LPDWORD max_subkey, LPDWORD max_class,
546                                LPDWORD values, LPDWORD max_value, LPDWORD max_data,
547                                LPDWORD security, FILETIME *modif )
548 {
549     NTSTATUS status;
550     char buffer[256], *buf_ptr = buffer;
551     KEY_FULL_INFORMATION *info = (KEY_FULL_INFORMATION *)buffer;
552     DWORD total_size;
553
554     TRACE( "(%p,%p,%ld,%p,%p,%p,%p,%p,%p,%p,%p)\n", hkey, class, class_len ? *class_len : 0,
555            reserved, subkeys, max_subkey, values, max_value, max_data, security, modif );
556
557     if (class && !class_len && is_version_nt()) return ERROR_INVALID_PARAMETER;
558     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
559
560     status = NtQueryKey( hkey, KeyFullInformation, buffer, sizeof(buffer), &total_size );
561     if (status && status != STATUS_BUFFER_OVERFLOW) goto done;
562
563     if (class)
564     {
565         /* retry with a dynamically allocated buffer */
566         while (status == STATUS_BUFFER_OVERFLOW)
567         {
568             if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
569             if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
570                 return ERROR_NOT_ENOUGH_MEMORY;
571             info = (KEY_FULL_INFORMATION *)buf_ptr;
572             status = NtQueryKey( hkey, KeyFullInformation, buf_ptr, total_size, &total_size );
573         }
574
575         if (status) goto done;
576
577         if (class_len && (info->ClassLength/sizeof(WCHAR) + 1 > *class_len))
578         {
579             status = STATUS_BUFFER_OVERFLOW;
580         }
581         else
582         {
583             memcpy( class, buf_ptr + info->ClassOffset, info->ClassLength );
584             class[info->ClassLength/sizeof(WCHAR)] = 0;
585         }
586     }
587     else status = STATUS_SUCCESS;
588
589     if (class_len) *class_len = info->ClassLength / sizeof(WCHAR);
590     if (subkeys) *subkeys = info->SubKeys;
591     if (max_subkey) *max_subkey = info->MaxNameLen;
592     if (max_class) *max_class = info->MaxClassLen;
593     if (values) *values = info->Values;
594     if (max_value) *max_value = info->MaxValueNameLen;
595     if (max_data) *max_data = info->MaxValueDataLen;
596     if (modif) *modif = *(FILETIME *)&info->LastWriteTime;
597
598  done:
599     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
600     return RtlNtStatusToDosError( status );
601 }
602
603
604 /******************************************************************************
605  *           RegQueryMultipleValuesA   [ADVAPI32.@]
606  */
607 DWORD WINAPI RegQueryMultipleValuesA(HKEY hkey, PVALENTA val_list, DWORD num_vals,
608                                      LPSTR lpValueBuf, LPDWORD ldwTotsize)
609 {
610     int i;
611     DWORD maxBytes = *ldwTotsize;
612     HRESULT status;
613     LPSTR bufptr = lpValueBuf;
614     *ldwTotsize = 0;
615
616     TRACE("(%p,%p,%ld,%p,%p=%ld)\n", hkey, val_list, num_vals, lpValueBuf, ldwTotsize, *ldwTotsize);
617
618     for(i=0; i < num_vals; ++i)
619     {
620
621         val_list[i].ve_valuelen=0;
622         status = RegQueryValueExA(hkey, val_list[i].ve_valuename, NULL, NULL, NULL, &val_list[i].ve_valuelen);
623         if(status != ERROR_SUCCESS)
624         {
625             return status;
626         }
627
628         if(lpValueBuf != NULL && *ldwTotsize + val_list[i].ve_valuelen <= maxBytes)
629         {
630             status = RegQueryValueExA(hkey, val_list[i].ve_valuename, NULL, &val_list[i].ve_type,
631                                       bufptr, &val_list[i].ve_valuelen);
632             if(status != ERROR_SUCCESS)
633             {
634                 return status;
635             }
636
637             val_list[i].ve_valueptr = (DWORD_PTR)bufptr;
638
639             bufptr += val_list[i].ve_valuelen;
640         }
641
642         *ldwTotsize += val_list[i].ve_valuelen;
643     }
644     return lpValueBuf != NULL && *ldwTotsize <= maxBytes ? ERROR_SUCCESS : ERROR_MORE_DATA;
645 }
646
647
648 /******************************************************************************
649  *           RegQueryMultipleValuesW   [ADVAPI32.@]
650  */
651 DWORD WINAPI RegQueryMultipleValuesW(HKEY hkey, PVALENTW val_list, DWORD num_vals,
652                                      LPWSTR lpValueBuf, LPDWORD ldwTotsize)
653 {
654     int i;
655     DWORD maxBytes = *ldwTotsize;
656     HRESULT status;
657     LPSTR bufptr = (LPSTR)lpValueBuf;
658     *ldwTotsize = 0;
659
660     TRACE("(%p,%p,%ld,%p,%p=%ld)\n", hkey, val_list, num_vals, lpValueBuf, ldwTotsize, *ldwTotsize);
661
662     for(i=0; i < num_vals; ++i)
663     {
664         val_list[i].ve_valuelen=0;
665         status = RegQueryValueExW(hkey, val_list[i].ve_valuename, NULL, NULL, NULL, &val_list[i].ve_valuelen);
666         if(status != ERROR_SUCCESS)
667         {
668             return status;
669         }
670
671         if(lpValueBuf != NULL && *ldwTotsize + val_list[i].ve_valuelen <= maxBytes)
672         {
673             status = RegQueryValueExW(hkey, val_list[i].ve_valuename, NULL, &val_list[i].ve_type,
674                                       bufptr, &val_list[i].ve_valuelen);
675             if(status != ERROR_SUCCESS)
676             {
677                 return status;
678             }
679
680             val_list[i].ve_valueptr = (DWORD_PTR)bufptr;
681
682             bufptr += val_list[i].ve_valuelen;
683         }
684
685         *ldwTotsize += val_list[i].ve_valuelen;
686     }
687     return lpValueBuf != NULL && *ldwTotsize <= maxBytes ? ERROR_SUCCESS : ERROR_MORE_DATA;
688 }
689
690 /******************************************************************************
691  *           RegQueryInfoKeyA   [ADVAPI32.@]
692  */
693 DWORD WINAPI RegQueryInfoKeyA( HKEY hkey, LPSTR class, LPDWORD class_len, LPDWORD reserved,
694                                LPDWORD subkeys, LPDWORD max_subkey, LPDWORD max_class,
695                                LPDWORD values, LPDWORD max_value, LPDWORD max_data,
696                                LPDWORD security, FILETIME *modif )
697 {
698     NTSTATUS status;
699     char buffer[256], *buf_ptr = buffer;
700     KEY_FULL_INFORMATION *info = (KEY_FULL_INFORMATION *)buffer;
701     DWORD total_size, len;
702
703     TRACE( "(%p,%p,%ld,%p,%p,%p,%p,%p,%p,%p,%p)\n", hkey, class, class_len ? *class_len : 0,
704            reserved, subkeys, max_subkey, values, max_value, max_data, security, modif );
705
706     if (class && !class_len && is_version_nt()) return ERROR_INVALID_PARAMETER;
707     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
708
709     status = NtQueryKey( hkey, KeyFullInformation, buffer, sizeof(buffer), &total_size );
710     if (status && status != STATUS_BUFFER_OVERFLOW) goto done;
711
712     if (class || class_len)
713     {
714         /* retry with a dynamically allocated buffer */
715         while (status == STATUS_BUFFER_OVERFLOW)
716         {
717             if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
718             if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
719                 return ERROR_NOT_ENOUGH_MEMORY;
720             info = (KEY_FULL_INFORMATION *)buf_ptr;
721             status = NtQueryKey( hkey, KeyFullInformation, buf_ptr, total_size, &total_size );
722         }
723
724         if (status) goto done;
725
726         RtlUnicodeToMultiByteSize( &len, (WCHAR *)(buf_ptr + info->ClassOffset), info->ClassLength);
727         if (class_len)
728         {
729             if (len + 1 > *class_len) status = STATUS_BUFFER_OVERFLOW;
730             *class_len = len;
731         }
732         if (class && !status)
733         {
734             RtlUnicodeToMultiByteN( class, len, NULL, (WCHAR *)(buf_ptr + info->ClassOffset),
735                                     info->ClassLength );
736             class[len] = 0;
737         }
738     }
739     else status = STATUS_SUCCESS;
740
741     if (subkeys) *subkeys = info->SubKeys;
742     if (max_subkey) *max_subkey = info->MaxNameLen;
743     if (max_class) *max_class = info->MaxClassLen;
744     if (values) *values = info->Values;
745     if (max_value) *max_value = info->MaxValueNameLen;
746     if (max_data) *max_data = info->MaxValueDataLen;
747     if (modif) *modif = *(FILETIME *)&info->LastWriteTime;
748
749  done:
750     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
751     return RtlNtStatusToDosError( status );
752 }
753
754
755 /******************************************************************************
756  *           RegCloseKey   [ADVAPI32.@]
757  *
758  * Releases the handle of the specified key
759  *
760  * PARAMS
761  *    hkey [I] Handle of key to close
762  *
763  * RETURNS
764  *    Success: ERROR_SUCCESS
765  *    Failure: Error code
766  */
767 DWORD WINAPI RegCloseKey( HKEY hkey )
768 {
769     if (!hkey || hkey >= (HKEY)0x80000000) return ERROR_SUCCESS;
770     return RtlNtStatusToDosError( NtClose( hkey ) );
771 }
772
773
774 /******************************************************************************
775  *           RegDeleteKeyW   [ADVAPI32.@]
776  *
777  * PARAMS
778  *    hkey   [I] Handle to open key
779  *    name   [I] Name of subkey to delete
780  *
781  * RETURNS
782  *    Success: ERROR_SUCCESS
783  *    Failure: Error code
784  */
785 DWORD WINAPI RegDeleteKeyW( HKEY hkey, LPCWSTR name )
786 {
787     DWORD ret;
788     HKEY tmp;
789
790     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
791
792     if (!name || !*name)
793     {
794         ret = RtlNtStatusToDosError( NtDeleteKey( hkey ) );
795     }
796     else if (!(ret = RegOpenKeyExW( hkey, name, 0, KEY_ENUMERATE_SUB_KEYS, &tmp )))
797     {
798         if (!is_version_nt()) /* win95 does recursive key deletes */
799         {
800             WCHAR name[MAX_PATH];
801
802             while(!RegEnumKeyW(tmp, 0, name, sizeof(name)))
803             {
804                 if(RegDeleteKeyW(tmp, name))  /* recurse */
805                     break;
806             }
807         }
808         ret = RtlNtStatusToDosError( NtDeleteKey( tmp ) );
809         RegCloseKey( tmp );
810     }
811     TRACE("%s ret=%08lx\n", debugstr_w(name), ret);
812     return ret;
813 }
814
815
816 /******************************************************************************
817  *           RegDeleteKeyA   [ADVAPI32.@]
818  */
819 DWORD WINAPI RegDeleteKeyA( HKEY hkey, LPCSTR name )
820 {
821     DWORD ret;
822     HKEY tmp;
823
824     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
825
826     if (!name || !*name)
827     {
828         ret = RtlNtStatusToDosError( NtDeleteKey( hkey ) );
829     }
830     else if (!(ret = RegOpenKeyExA( hkey, name, 0, KEY_ENUMERATE_SUB_KEYS, &tmp )))
831     {
832         if (!is_version_nt()) /* win95 does recursive key deletes */
833         {
834             CHAR name[MAX_PATH];
835
836             while(!RegEnumKeyA(tmp, 0, name, sizeof(name)))
837             {
838                 if(RegDeleteKeyA(tmp, name))  /* recurse */
839                     break;
840             }
841         }
842         ret = RtlNtStatusToDosError( NtDeleteKey( tmp ) );
843         RegCloseKey( tmp );
844     }
845     TRACE("%s ret=%08lx\n", debugstr_a(name), ret);
846     return ret;
847 }
848
849
850
851 /******************************************************************************
852  *           RegSetValueExW   [ADVAPI32.@]
853  *
854  * Sets the data and type of a value under a register key
855  *
856  * PARAMS
857  *    hkey       [I] Handle of key to set value for
858  *    name       [I] Name of value to set
859  *    reserved   [I] Reserved - must be zero
860  *    type       [I] Flag for value type
861  *    data       [I] Address of value data
862  *    count      [I] Size of value data
863  *
864  * RETURNS
865  *    Success: ERROR_SUCCESS
866  *    Failure: Error code
867  *
868  * NOTES
869  *   win95 does not care about count for REG_SZ and finds out the len by itself (js)
870  *   NT does definitely care (aj)
871  */
872 DWORD WINAPI RegSetValueExW( HKEY hkey, LPCWSTR name, DWORD reserved,
873                              DWORD type, CONST BYTE *data, DWORD count )
874 {
875     UNICODE_STRING nameW;
876
877     if (!is_version_nt())  /* win95 */
878     {
879         if (type == REG_SZ) count = (strlenW( (WCHAR *)data ) + 1) * sizeof(WCHAR);
880     }
881     else if (count && is_string(type))
882     {
883         LPCWSTR str = (LPCWSTR)data;
884         /* if user forgot to count terminating null, add it (yes NT does this) */
885         if (str[count / sizeof(WCHAR) - 1] && !str[count / sizeof(WCHAR)])
886             count += sizeof(WCHAR);
887     }
888     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
889
890     RtlInitUnicodeString( &nameW, name );
891     return RtlNtStatusToDosError( NtSetValueKey( hkey, &nameW, 0, type, data, count ) );
892 }
893
894
895 /******************************************************************************
896  *           RegSetValueExA   [ADVAPI32.@]
897  */
898 DWORD WINAPI RegSetValueExA( HKEY hkey, LPCSTR name, DWORD reserved, DWORD type,
899                              CONST BYTE *data, DWORD count )
900 {
901     ANSI_STRING nameA;
902     WCHAR *dataW = NULL;
903     NTSTATUS status;
904
905     if (!is_version_nt())  /* win95 */
906     {
907         if (type == REG_SZ) count = strlen(data) + 1;
908     }
909     else if (count && is_string(type))
910     {
911         /* if user forgot to count terminating null, add it (yes NT does this) */
912         if (data[count-1] && !data[count]) count++;
913     }
914
915     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
916
917     if (is_string( type )) /* need to convert to Unicode */
918     {
919         DWORD lenW;
920         RtlMultiByteToUnicodeSize( &lenW, data, count );
921         if (!(dataW = HeapAlloc( GetProcessHeap(), 0, lenW ))) return ERROR_OUTOFMEMORY;
922         RtlMultiByteToUnicodeN( dataW, lenW, NULL, data, count );
923         count = lenW;
924         data = (BYTE *)dataW;
925     }
926
927     RtlInitAnsiString( &nameA, name );
928     if (!(status = RtlAnsiStringToUnicodeString( &NtCurrentTeb()->StaticUnicodeString,
929                                                  &nameA, FALSE )))
930     {
931         status = NtSetValueKey( hkey, &NtCurrentTeb()->StaticUnicodeString, 0, type, data, count );
932     }
933     if (dataW) HeapFree( GetProcessHeap(), 0, dataW );
934     return RtlNtStatusToDosError( status );
935 }
936
937
938 /******************************************************************************
939  *           RegSetValueW   [ADVAPI32.@]
940  */
941 DWORD WINAPI RegSetValueW( HKEY hkey, LPCWSTR name, DWORD type, LPCWSTR data, DWORD count )
942 {
943     HKEY subkey = hkey;
944     DWORD ret;
945
946     TRACE("(%p,%s,%ld,%s,%ld)\n", hkey, debugstr_w(name), type, debugstr_w(data), count );
947
948     if (type != REG_SZ) return ERROR_INVALID_PARAMETER;
949
950     if (name && name[0])  /* need to create the subkey */
951     {
952         if ((ret = RegCreateKeyW( hkey, name, &subkey )) != ERROR_SUCCESS) return ret;
953     }
954
955     ret = RegSetValueExW( subkey, NULL, 0, REG_SZ, (LPBYTE)data,
956                           (strlenW( data ) + 1) * sizeof(WCHAR) );
957     if (subkey != hkey) RegCloseKey( subkey );
958     return ret;
959 }
960
961
962 /******************************************************************************
963  *           RegSetValueA   [ADVAPI32.@]
964  */
965 DWORD WINAPI RegSetValueA( HKEY hkey, LPCSTR name, DWORD type, LPCSTR data, DWORD count )
966 {
967     HKEY subkey = hkey;
968     DWORD ret;
969
970     TRACE("(%p,%s,%ld,%s,%ld)\n", hkey, debugstr_a(name), type, debugstr_a(data), count );
971
972     if (type != REG_SZ) return ERROR_INVALID_PARAMETER;
973
974     if (name && name[0])  /* need to create the subkey */
975     {
976         if ((ret = RegCreateKeyA( hkey, name, &subkey )) != ERROR_SUCCESS) return ret;
977     }
978     ret = RegSetValueExA( subkey, NULL, 0, REG_SZ, (LPBYTE)data, strlen(data)+1 );
979     if (subkey != hkey) RegCloseKey( subkey );
980     return ret;
981 }
982
983
984
985 /******************************************************************************
986  *           RegQueryValueExW   [ADVAPI32.@]
987  *
988  * Retrieves type and data for a specified name associated with an open key
989  *
990  * PARAMS
991  *    hkey      [I]   Handle of key to query
992  *    name      [I]   Name of value to query
993  *    reserved  [I]   Reserved - must be NULL
994  *    type      [O]   Address of buffer for value type.  If NULL, the type
995  *                        is not required.
996  *    data      [O]   Address of data buffer.  If NULL, the actual data is
997  *                        not required.
998  *    count     [I/O] Address of data buffer size
999  *
1000  * RETURNS
1001  *    ERROR_SUCCESS:   Success
1002  *    ERROR_MORE_DATA: !!! if the specified buffer is not big enough to hold the data
1003  *                     buffer is left untouched. The MS-documentation is wrong (js) !!!
1004  */
1005 DWORD WINAPI RegQueryValueExW( HKEY hkey, LPCWSTR name, LPDWORD reserved, LPDWORD type,
1006                                LPBYTE data, LPDWORD count )
1007 {
1008     NTSTATUS status;
1009     UNICODE_STRING name_str;
1010     DWORD total_size;
1011     char buffer[256], *buf_ptr = buffer;
1012     KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
1013     static const int info_size = offsetof( KEY_VALUE_PARTIAL_INFORMATION, Data );
1014
1015     TRACE("(%p,%s,%p,%p,%p,%p=%ld)\n",
1016           hkey, debugstr_w(name), reserved, type, data, count, count ? *count : 0 );
1017
1018     if ((data && !count) || reserved) return ERROR_INVALID_PARAMETER;
1019     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1020
1021     RtlInitUnicodeString( &name_str, name );
1022
1023     if (data) total_size = min( sizeof(buffer), *count + info_size );
1024     else total_size = info_size;
1025
1026     status = NtQueryValueKey( hkey, &name_str, KeyValuePartialInformation,
1027                               buffer, total_size, &total_size );
1028     if (status && status != STATUS_BUFFER_OVERFLOW) goto done;
1029
1030     if (data)
1031     {
1032         /* retry with a dynamically allocated buffer */
1033         while (status == STATUS_BUFFER_OVERFLOW && total_size - info_size <= *count)
1034         {
1035             if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
1036             if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
1037                 return ERROR_NOT_ENOUGH_MEMORY;
1038             info = (KEY_VALUE_PARTIAL_INFORMATION *)buf_ptr;
1039             status = NtQueryValueKey( hkey, &name_str, KeyValuePartialInformation,
1040                                       buf_ptr, total_size, &total_size );
1041         }
1042
1043         if (!status)
1044         {
1045             memcpy( data, buf_ptr + info_size, total_size - info_size );
1046             /* if the type is REG_SZ and data is not 0-terminated
1047              * and there is enough space in the buffer NT appends a \0 */
1048             if (total_size - info_size <= *count-sizeof(WCHAR) && is_string(info->Type))
1049             {
1050                 WCHAR *ptr = (WCHAR *)(data + total_size - info_size);
1051                 if (ptr > (WCHAR *)data && ptr[-1]) *ptr = 0;
1052             }
1053         }
1054         else if (status != STATUS_BUFFER_OVERFLOW) goto done;
1055     }
1056     else status = STATUS_SUCCESS;
1057
1058     if (type) *type = info->Type;
1059     if (count) *count = total_size - info_size;
1060
1061  done:
1062     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
1063     return RtlNtStatusToDosError(status);
1064 }
1065
1066
1067 /******************************************************************************
1068  *           RegQueryValueExA   [ADVAPI32.@]
1069  *
1070  * NOTES:
1071  * the documentation is wrong: if the buffer is too small it remains untouched
1072  */
1073 DWORD WINAPI RegQueryValueExA( HKEY hkey, LPCSTR name, LPDWORD reserved, LPDWORD type,
1074                                LPBYTE data, LPDWORD count )
1075 {
1076     NTSTATUS status;
1077     ANSI_STRING nameA;
1078     DWORD total_size;
1079     char buffer[256], *buf_ptr = buffer;
1080     KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
1081     static const int info_size = offsetof( KEY_VALUE_PARTIAL_INFORMATION, Data );
1082
1083     TRACE("(%p,%s,%p,%p,%p,%p=%ld)\n",
1084           hkey, debugstr_a(name), reserved, type, data, count, count ? *count : 0 );
1085
1086     if ((data && !count) || reserved) return ERROR_INVALID_PARAMETER;
1087     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1088
1089     RtlInitAnsiString( &nameA, name );
1090     if ((status = RtlAnsiStringToUnicodeString( &NtCurrentTeb()->StaticUnicodeString,
1091                                                 &nameA, FALSE )))
1092         return RtlNtStatusToDosError(status);
1093
1094     status = NtQueryValueKey( hkey, &NtCurrentTeb()->StaticUnicodeString,
1095                               KeyValuePartialInformation, buffer, sizeof(buffer), &total_size );
1096     if (status && status != STATUS_BUFFER_OVERFLOW) goto done;
1097
1098     /* we need to fetch the contents for a string type even if not requested,
1099      * because we need to compute the length of the ASCII string. */
1100     if (data || is_string(info->Type))
1101     {
1102         /* retry with a dynamically allocated buffer */
1103         while (status == STATUS_BUFFER_OVERFLOW)
1104         {
1105             if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
1106             if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
1107             {
1108                 status = STATUS_NO_MEMORY;
1109                 goto done;
1110             }
1111             info = (KEY_VALUE_PARTIAL_INFORMATION *)buf_ptr;
1112             status = NtQueryValueKey( hkey, &NtCurrentTeb()->StaticUnicodeString,
1113                                     KeyValuePartialInformation, buf_ptr, total_size, &total_size );
1114         }
1115
1116         if (status) goto done;
1117
1118         if (is_string(info->Type))
1119         {
1120             DWORD len;
1121
1122             RtlUnicodeToMultiByteSize( &len, (WCHAR *)(buf_ptr + info_size),
1123                                        total_size - info_size );
1124             if (data && len)
1125             {
1126                 if (len > *count) status = STATUS_BUFFER_OVERFLOW;
1127                 else
1128                 {
1129                     RtlUnicodeToMultiByteN( data, len, NULL, (WCHAR *)(buf_ptr + info_size),
1130                                             total_size - info_size );
1131                     /* if the type is REG_SZ and data is not 0-terminated
1132                      * and there is enough space in the buffer NT appends a \0 */
1133                     if (len < *count && data[len-1]) data[len] = 0;
1134                 }
1135             }
1136             total_size = len + info_size;
1137         }
1138         else if (data)
1139         {
1140             if (total_size - info_size > *count) status = STATUS_BUFFER_OVERFLOW;
1141             else memcpy( data, buf_ptr + info_size, total_size - info_size );
1142         }
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  *           RegQueryValueW   [ADVAPI32.@]
1157  */
1158 DWORD WINAPI RegQueryValueW( HKEY hkey, LPCWSTR name, LPWSTR data, LPLONG count )
1159 {
1160     DWORD ret;
1161     HKEY subkey = hkey;
1162
1163     TRACE("(%p,%s,%p,%ld)\n", hkey, debugstr_w(name), data, count ? *count : 0 );
1164
1165     if (name && name[0])
1166     {
1167         if ((ret = RegOpenKeyW( hkey, name, &subkey )) != ERROR_SUCCESS) return ret;
1168     }
1169     ret = RegQueryValueExW( subkey, NULL, NULL, NULL, (LPBYTE)data, count );
1170     if (subkey != hkey) RegCloseKey( subkey );
1171     if (ret == ERROR_FILE_NOT_FOUND)
1172     {
1173         /* return empty string if default value not found */
1174         if (data) *data = 0;
1175         if (count) *count = 1;
1176         ret = ERROR_SUCCESS;
1177     }
1178     return ret;
1179 }
1180
1181
1182 /******************************************************************************
1183  *           RegQueryValueA   [ADVAPI32.@]
1184  */
1185 DWORD WINAPI RegQueryValueA( HKEY hkey, LPCSTR name, LPSTR data, LPLONG count )
1186 {
1187     DWORD ret;
1188     HKEY subkey = hkey;
1189
1190     TRACE("(%p,%s,%p,%ld)\n", hkey, debugstr_a(name), data, count ? *count : 0 );
1191
1192     if (name && name[0])
1193     {
1194         if ((ret = RegOpenKeyA( hkey, name, &subkey )) != ERROR_SUCCESS) return ret;
1195     }
1196     ret = RegQueryValueExA( subkey, NULL, NULL, NULL, (LPBYTE)data, count );
1197     if (subkey != hkey) RegCloseKey( subkey );
1198     if (ret == ERROR_FILE_NOT_FOUND)
1199     {
1200         /* return empty string if default value not found */
1201         if (data) *data = 0;
1202         if (count) *count = 1;
1203         ret = ERROR_SUCCESS;
1204     }
1205     return ret;
1206 }
1207
1208
1209 /******************************************************************************
1210  *           RegEnumValueW   [ADVAPI32.@]
1211  *
1212  * PARAMS
1213  *    hkey       [I] Handle to key to query
1214  *    index      [I] Index of value to query
1215  *    value      [O] Value string
1216  *    val_count  [I/O] Size of value buffer (in wchars)
1217  *    reserved   [I] Reserved
1218  *    type       [O] Type code
1219  *    data       [O] Value data
1220  *    count      [I/O] Size of data buffer (in bytes)
1221  */
1222
1223 DWORD WINAPI RegEnumValueW( HKEY hkey, DWORD index, LPWSTR value, LPDWORD val_count,
1224                             LPDWORD reserved, LPDWORD type, LPBYTE data, LPDWORD count )
1225 {
1226     NTSTATUS status;
1227     DWORD total_size;
1228     char buffer[256], *buf_ptr = buffer;
1229     KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
1230     static const int info_size = offsetof( KEY_VALUE_FULL_INFORMATION, Name );
1231
1232     TRACE("(%p,%ld,%p,%p,%p,%p,%p,%p)\n",
1233           hkey, index, value, val_count, reserved, type, data, count );
1234
1235     /* NT only checks count, not val_count */
1236     if ((data && !count) || reserved) return ERROR_INVALID_PARAMETER;
1237     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1238
1239     total_size = info_size + (MAX_PATH + 1) * sizeof(WCHAR);
1240     if (data) total_size += *count;
1241     total_size = min( sizeof(buffer), total_size );
1242
1243     status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
1244                                   buffer, total_size, &total_size );
1245     if (status && status != STATUS_BUFFER_OVERFLOW) goto done;
1246
1247     if (value || data)
1248     {
1249         /* retry with a dynamically allocated buffer */
1250         while (status == STATUS_BUFFER_OVERFLOW)
1251         {
1252             if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
1253             if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
1254                 return ERROR_NOT_ENOUGH_MEMORY;
1255             info = (KEY_VALUE_FULL_INFORMATION *)buf_ptr;
1256             status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
1257                                           buf_ptr, total_size, &total_size );
1258         }
1259
1260         if (status) goto done;
1261
1262         if (value)
1263         {
1264             if (info->NameLength/sizeof(WCHAR) >= *val_count)
1265             {
1266                 status = STATUS_BUFFER_OVERFLOW;
1267                 goto overflow;
1268             }
1269             memcpy( value, info->Name, info->NameLength );
1270             *val_count = info->NameLength / sizeof(WCHAR);
1271             value[*val_count] = 0;
1272         }
1273
1274         if (data)
1275         {
1276             if (total_size - info->DataOffset > *count)
1277             {
1278                 status = STATUS_BUFFER_OVERFLOW;
1279                 goto overflow;
1280             }
1281             memcpy( data, buf_ptr + info->DataOffset, total_size - info->DataOffset );
1282             if (total_size - info->DataOffset <= *count-sizeof(WCHAR) && is_string(info->Type))
1283             {
1284                 /* if the type is REG_SZ and data is not 0-terminated
1285                  * and there is enough space in the buffer NT appends a \0 */
1286                 WCHAR *ptr = (WCHAR *)(data + total_size - info->DataOffset);
1287                 if (ptr > (WCHAR *)data && ptr[-1]) *ptr = 0;
1288             }
1289         }
1290     }
1291     else status = STATUS_SUCCESS;
1292
1293  overflow:
1294     if (type) *type = info->Type;
1295     if (count) *count = info->DataLength;
1296
1297  done:
1298     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
1299     return RtlNtStatusToDosError(status);
1300 }
1301
1302
1303 /******************************************************************************
1304  *           RegEnumValueA   [ADVAPI32.@]
1305  */
1306 DWORD WINAPI RegEnumValueA( HKEY hkey, DWORD index, LPSTR value, LPDWORD val_count,
1307                             LPDWORD reserved, LPDWORD type, LPBYTE data, LPDWORD count )
1308 {
1309     NTSTATUS status;
1310     DWORD total_size;
1311     char buffer[256], *buf_ptr = buffer;
1312     KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
1313     static const int info_size = offsetof( KEY_VALUE_FULL_INFORMATION, Name );
1314
1315     TRACE("(%p,%ld,%p,%p,%p,%p,%p,%p)\n",
1316           hkey, index, value, val_count, reserved, type, data, count );
1317
1318     /* NT only checks count, not val_count */
1319     if ((data && !count) || reserved) return ERROR_INVALID_PARAMETER;
1320     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1321
1322     total_size = info_size + (MAX_PATH + 1) * sizeof(WCHAR);
1323     if (data) total_size += *count;
1324     total_size = min( sizeof(buffer), total_size );
1325
1326     status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
1327                                   buffer, total_size, &total_size );
1328     if (status && status != STATUS_BUFFER_OVERFLOW) goto done;
1329
1330     /* we need to fetch the contents for a string type even if not requested,
1331      * because we need to compute the length of the ASCII string. */
1332     if (value || data || is_string(info->Type))
1333     {
1334         /* retry with a dynamically allocated buffer */
1335         while (status == STATUS_BUFFER_OVERFLOW)
1336         {
1337             if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
1338             if (!(buf_ptr = HeapAlloc( GetProcessHeap(), 0, total_size )))
1339                 return ERROR_NOT_ENOUGH_MEMORY;
1340             info = (KEY_VALUE_FULL_INFORMATION *)buf_ptr;
1341             status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
1342                                           buf_ptr, total_size, &total_size );
1343         }
1344
1345         if (status) goto done;
1346
1347         if (is_string(info->Type))
1348         {
1349             DWORD len;
1350             RtlUnicodeToMultiByteSize( &len, (WCHAR *)(buf_ptr + info->DataOffset),
1351                                        total_size - info->DataOffset );
1352             if (data && len)
1353             {
1354                 if (len > *count) status = STATUS_BUFFER_OVERFLOW;
1355                 else
1356                 {
1357                     RtlUnicodeToMultiByteN( data, len, NULL, (WCHAR *)(buf_ptr + info->DataOffset),
1358                                             total_size - info->DataOffset );
1359                     /* if the type is REG_SZ and data is not 0-terminated
1360                      * and there is enough space in the buffer NT appends a \0 */
1361                     if (len < *count && data[len-1]) data[len] = 0;
1362                 }
1363             }
1364             info->DataLength = len;
1365         }
1366         else if (data)
1367         {
1368             if (total_size - info->DataOffset > *count) status = STATUS_BUFFER_OVERFLOW;
1369             else memcpy( data, buf_ptr + info->DataOffset, total_size - info->DataOffset );
1370         }
1371
1372         if (value && !status)
1373         {
1374             DWORD len;
1375
1376             RtlUnicodeToMultiByteSize( &len, info->Name, info->NameLength );
1377             if (len >= *val_count)
1378             {
1379                 status = STATUS_BUFFER_OVERFLOW;
1380                 if (*val_count)
1381                 {
1382                     len = *val_count - 1;
1383                     RtlUnicodeToMultiByteN( value, len, NULL, info->Name, info->NameLength );
1384                     value[len] = 0;
1385                 }
1386             }
1387             else
1388             {
1389                 RtlUnicodeToMultiByteN( value, len, NULL, info->Name, info->NameLength );
1390                 value[len] = 0;
1391                 *val_count = len;
1392             }
1393         }
1394     }
1395     else status = STATUS_SUCCESS;
1396
1397     if (type) *type = info->Type;
1398     if (count) *count = info->DataLength;
1399
1400  done:
1401     if (buf_ptr != buffer) HeapFree( GetProcessHeap(), 0, buf_ptr );
1402     return RtlNtStatusToDosError(status);
1403 }
1404
1405
1406
1407 /******************************************************************************
1408  *           RegDeleteValueW   [ADVAPI32.@]
1409  *
1410  * See RegDeleteValueA.
1411  */
1412 DWORD WINAPI RegDeleteValueW( HKEY hkey, LPCWSTR name )
1413 {
1414     UNICODE_STRING nameW;
1415
1416     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1417
1418     RtlInitUnicodeString( &nameW, name );
1419     return RtlNtStatusToDosError( NtDeleteValueKey( hkey, &nameW ) );
1420 }
1421
1422
1423 /******************************************************************************
1424  *           RegDeleteValueA   [ADVAPI32.@]
1425  *
1426  * Delete a value from the registry.
1427  *
1428  * PARAMS
1429  *  hkey [I] Registry handle of the key holding the value
1430  *  name [I] Name of the value under hkey to delete
1431  *
1432  * RETURNS
1433  *  Success: 0
1434  *  Failure: A standard Windows error code.
1435  */
1436 DWORD WINAPI RegDeleteValueA( HKEY hkey, LPCSTR name )
1437 {
1438     STRING nameA;
1439     NTSTATUS status;
1440
1441     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1442
1443     RtlInitAnsiString( &nameA, name );
1444     if (!(status = RtlAnsiStringToUnicodeString( &NtCurrentTeb()->StaticUnicodeString,
1445                                                  &nameA, FALSE )))
1446         status = NtDeleteValueKey( hkey, &NtCurrentTeb()->StaticUnicodeString );
1447     return RtlNtStatusToDosError( status );
1448 }
1449
1450
1451 /******************************************************************************
1452  *           RegLoadKeyW   [ADVAPI32.@]
1453  *
1454  * PARAMS
1455  *    hkey      [I] Handle of open key
1456  *    subkey    [I] Address of name of subkey
1457  *    filename  [I] Address of filename for registry information
1458  */
1459 LONG WINAPI RegLoadKeyW( HKEY hkey, LPCWSTR subkey, LPCWSTR filename )
1460 {
1461     HANDLE file;
1462     DWORD ret, len, err = GetLastError();
1463     HKEY shkey;
1464
1465     TRACE( "(%p,%s,%s)\n", hkey, debugstr_w(subkey), debugstr_w(filename) );
1466
1467     if (!filename || !*filename) return ERROR_INVALID_PARAMETER;
1468     if (!subkey || !*subkey) return ERROR_INVALID_PARAMETER;
1469     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1470
1471     len = strlenW( subkey ) * sizeof(WCHAR);
1472     if (len > MAX_PATH*sizeof(WCHAR)) return ERROR_INVALID_PARAMETER;
1473
1474     if ((file = CreateFileW( filename, GENERIC_READ, 0, NULL, OPEN_EXISTING,
1475                              FILE_ATTRIBUTE_NORMAL, 0 )) == INVALID_HANDLE_VALUE)
1476     {
1477         ret = GetLastError();
1478         goto done;
1479     }
1480
1481     RegCreateKeyW(hkey,subkey,&shkey);
1482
1483     SERVER_START_REQ( load_registry )
1484     {
1485         req->hkey  = shkey;
1486         req->file  = file;
1487         wine_server_add_data( req, subkey, len );
1488         ret = RtlNtStatusToDosError( wine_server_call(req) );
1489     }
1490     SERVER_END_REQ;
1491     CloseHandle( file );
1492     RegCloseKey(shkey);
1493
1494  done:
1495     SetLastError( err );  /* restore the last error code */
1496     return ret;
1497 }
1498
1499
1500 /******************************************************************************
1501  *           RegLoadKeyA   [ADVAPI32.@]
1502  */
1503 LONG WINAPI RegLoadKeyA( HKEY hkey, LPCSTR subkey, LPCSTR filename )
1504 {
1505     WCHAR buffer[MAX_PATH];
1506     HANDLE file;
1507     DWORD ret, len, err = GetLastError();
1508     HKEY shkey;
1509
1510     TRACE( "(%p,%s,%s)\n", hkey, debugstr_a(subkey), debugstr_a(filename) );
1511
1512     if (!filename || !*filename) return ERROR_INVALID_PARAMETER;
1513     if (!subkey || !*subkey) return ERROR_INVALID_PARAMETER;
1514     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1515
1516     if (!(len = MultiByteToWideChar( CP_ACP, 0, subkey, strlen(subkey), buffer, MAX_PATH )))
1517         return ERROR_INVALID_PARAMETER;
1518
1519     if ((file = CreateFileA( filename, GENERIC_READ, 0, NULL, OPEN_EXISTING,
1520                              FILE_ATTRIBUTE_NORMAL, 0 )) == INVALID_HANDLE_VALUE)
1521     {
1522         ret = GetLastError();
1523         goto done;
1524     }
1525
1526     RegCreateKeyA(hkey,subkey,&shkey);
1527
1528     SERVER_START_REQ( load_registry )
1529     {
1530         req->hkey  = shkey;
1531         req->file  = file;
1532         wine_server_add_data( req, buffer, len * sizeof(WCHAR) );
1533         ret = RtlNtStatusToDosError( wine_server_call(req) );
1534     }
1535     SERVER_END_REQ;
1536     CloseHandle( file );
1537     RegCloseKey(shkey);
1538
1539  done:
1540     SetLastError( err );  /* restore the last error code */
1541     return ret;
1542 }
1543
1544
1545 /******************************************************************************
1546  *           RegSaveKeyW   [ADVAPI32.@]
1547  *
1548  * PARAMS
1549  *    hkey   [I] Handle of key where save begins
1550  *    lpFile [I] Address of filename to save to
1551  *    sa     [I] Address of security structure
1552  */
1553 LONG WINAPI RegSaveKeyW( HKEY hkey, LPCWSTR file, LPSECURITY_ATTRIBUTES sa )
1554 {
1555     static const WCHAR format[] =
1556         {'r','e','g','%','0','4','x','.','t','m','p',0};
1557     WCHAR buffer[MAX_PATH];
1558     int count = 0;
1559     LPWSTR nameW;
1560     DWORD ret, err;
1561     HANDLE handle;
1562
1563     TRACE( "(%p,%s,%p)\n", hkey, debugstr_w(file), sa );
1564
1565     if (!file || !*file) return ERROR_INVALID_PARAMETER;
1566     if (!(hkey = get_special_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
1567
1568     err = GetLastError();
1569     GetFullPathNameW( file, sizeof(buffer)/sizeof(WCHAR), buffer, &nameW );
1570
1571     for (;;)
1572     {
1573         snprintfW( nameW, 16, format, count++ );
1574         handle = CreateFileW( buffer, GENERIC_WRITE, 0, NULL,
1575                             CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
1576         if (handle != INVALID_HANDLE_VALUE) break;
1577         if ((ret = GetLastError()) != ERROR_ALREADY_EXISTS) goto done;
1578
1579         /* Something gone haywire ? Please report if this happens abnormally */
1580         if (count >= 100)
1581             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);
1582     }
1583
1584     SERVER_START_REQ( save_registry )
1585     {
1586         req->hkey = hkey;
1587         req->file = handle;
1588         ret = RtlNtStatusToDosError( wine_server_call( req ) );
1589     }
1590     SERVER_END_REQ;
1591
1592     CloseHandle( handle );
1593     if (!ret)
1594     {
1595         if (!MoveFileExW( buffer, file, MOVEFILE_REPLACE_EXISTING ))
1596         {
1597             ERR( "Failed to move %s to %s\n", debugstr_w(buffer),
1598                 debugstr_w(file) );
1599             ret = GetLastError();
1600         }
1601     }
1602     if (ret) DeleteFileW( buffer );
1603
1604 done:
1605     SetLastError( err );  /* restore last error code */
1606     return ret;
1607 }
1608
1609
1610 /******************************************************************************
1611  *           RegSaveKeyA  [ADVAPI32.@]
1612  */
1613 LONG WINAPI RegSaveKeyA( HKEY hkey, LPCSTR file, LPSECURITY_ATTRIBUTES sa )
1614 {
1615     UNICODE_STRING *fileW = &NtCurrentTeb()->StaticUnicodeString;
1616     NTSTATUS status;
1617     STRING fileA;
1618
1619     RtlInitAnsiString(&fileA, file);
1620     if ((status = RtlAnsiStringToUnicodeString(fileW, &fileA, FALSE)))
1621         return RtlNtStatusToDosError( status );
1622     return RegSaveKeyW(hkey, fileW->Buffer, sa);
1623 }
1624
1625
1626 /******************************************************************************
1627  * RegRestoreKeyW [ADVAPI32.@]
1628  *
1629  * PARAMS
1630  *    hkey    [I] Handle of key where restore begins
1631  *    lpFile  [I] Address of filename containing saved tree
1632  *    dwFlags [I] Optional flags
1633  */
1634 LONG WINAPI RegRestoreKeyW( HKEY hkey, LPCWSTR lpFile, DWORD dwFlags )
1635 {
1636     TRACE("(%p,%s,%ld)\n",hkey,debugstr_w(lpFile),dwFlags);
1637
1638     /* It seems to do this check before the hkey check */
1639     if (!lpFile || !*lpFile)
1640         return ERROR_INVALID_PARAMETER;
1641
1642     FIXME("(%p,%s,%ld): stub\n",hkey,debugstr_w(lpFile),dwFlags);
1643
1644     /* Check for file existence */
1645
1646     return ERROR_SUCCESS;
1647 }
1648
1649
1650 /******************************************************************************
1651  * RegRestoreKeyA [ADVAPI32.@]
1652  */
1653 LONG WINAPI RegRestoreKeyA( HKEY hkey, LPCSTR lpFile, DWORD dwFlags )
1654 {
1655     UNICODE_STRING lpFileW;
1656     LONG ret;
1657
1658     RtlCreateUnicodeStringFromAsciiz( &lpFileW, lpFile );
1659     ret = RegRestoreKeyW( hkey, lpFileW.Buffer, dwFlags );
1660     RtlFreeUnicodeString( &lpFileW );
1661     return ret;
1662 }
1663
1664
1665 /******************************************************************************
1666  * RegUnLoadKeyW [ADVAPI32.@]
1667  *
1668  * PARAMS
1669  *    hkey     [I] Handle of open key
1670  *    lpSubKey [I] Address of name of subkey to unload
1671  */
1672 LONG WINAPI RegUnLoadKeyW( HKEY hkey, LPCWSTR lpSubKey )
1673 {
1674     DWORD ret;
1675     HKEY shkey;
1676
1677     TRACE("(%p,%s)\n",hkey, debugstr_w(lpSubKey));
1678
1679     ret = RegOpenKeyW(hkey,lpSubKey,&shkey);
1680     if( ret )
1681         return ERROR_INVALID_PARAMETER;
1682
1683     SERVER_START_REQ( unload_registry )
1684     {
1685         req->hkey  = shkey;
1686         ret = RtlNtStatusToDosError( wine_server_call(req) );
1687     }
1688     SERVER_END_REQ;
1689     RegCloseKey(shkey);
1690
1691     return ret;
1692 }
1693
1694
1695 /******************************************************************************
1696  * RegUnLoadKeyA [ADVAPI32.@]
1697  */
1698 LONG WINAPI RegUnLoadKeyA( HKEY hkey, LPCSTR lpSubKey )
1699 {
1700     UNICODE_STRING lpSubKeyW;
1701     LONG ret;
1702
1703     RtlCreateUnicodeStringFromAsciiz( &lpSubKeyW, lpSubKey );
1704     ret = RegUnLoadKeyW( hkey, lpSubKeyW.Buffer );
1705     RtlFreeUnicodeString( &lpSubKeyW );
1706     return ret;
1707 }
1708
1709
1710 /******************************************************************************
1711  * RegReplaceKeyW [ADVAPI32.@]
1712  *
1713  * PARAMS
1714  *    hkey      [I] Handle of open key
1715  *    lpSubKey  [I] Address of name of subkey
1716  *    lpNewFile [I] Address of filename for file with new data
1717  *    lpOldFile [I] Address of filename for backup file
1718  */
1719 LONG WINAPI RegReplaceKeyW( HKEY hkey, LPCWSTR lpSubKey, LPCWSTR lpNewFile,
1720                               LPCWSTR lpOldFile )
1721 {
1722     FIXME("(%p,%s,%s,%s): stub\n", hkey, debugstr_w(lpSubKey),
1723           debugstr_w(lpNewFile),debugstr_w(lpOldFile));
1724     return ERROR_SUCCESS;
1725 }
1726
1727
1728 /******************************************************************************
1729  * RegReplaceKeyA [ADVAPI32.@]
1730  */
1731 LONG WINAPI RegReplaceKeyA( HKEY hkey, LPCSTR lpSubKey, LPCSTR lpNewFile,
1732                               LPCSTR lpOldFile )
1733 {
1734     UNICODE_STRING lpSubKeyW;
1735     UNICODE_STRING lpNewFileW;
1736     UNICODE_STRING lpOldFileW;
1737     LONG ret;
1738
1739     RtlCreateUnicodeStringFromAsciiz( &lpSubKeyW, lpSubKey );
1740     RtlCreateUnicodeStringFromAsciiz( &lpOldFileW, lpOldFile );
1741     RtlCreateUnicodeStringFromAsciiz( &lpNewFileW, lpNewFile );
1742     ret = RegReplaceKeyW( hkey, lpSubKeyW.Buffer, lpNewFileW.Buffer, lpOldFileW.Buffer );
1743     RtlFreeUnicodeString( &lpOldFileW );
1744     RtlFreeUnicodeString( &lpNewFileW );
1745     RtlFreeUnicodeString( &lpSubKeyW );
1746     return ret;
1747 }
1748
1749
1750 /******************************************************************************
1751  * RegSetKeySecurity [ADVAPI32.@]
1752  *
1753  * PARAMS
1754  *    hkey          [I] Open handle of key to set
1755  *    SecurityInfo  [I] Descriptor contents
1756  *    pSecurityDesc [I] Address of descriptor for key
1757  */
1758 LONG WINAPI RegSetKeySecurity( HKEY hkey, SECURITY_INFORMATION SecurityInfo,
1759                                PSECURITY_DESCRIPTOR pSecurityDesc )
1760 {
1761     TRACE("(%p,%ld,%p)\n",hkey,SecurityInfo,pSecurityDesc);
1762
1763     /* It seems to perform this check before the hkey check */
1764     if ((SecurityInfo & OWNER_SECURITY_INFORMATION) ||
1765         (SecurityInfo & GROUP_SECURITY_INFORMATION) ||
1766         (SecurityInfo & DACL_SECURITY_INFORMATION) ||
1767         (SecurityInfo & SACL_SECURITY_INFORMATION)) {
1768         /* Param OK */
1769     } else
1770         return ERROR_INVALID_PARAMETER;
1771
1772     if (!pSecurityDesc)
1773         return ERROR_INVALID_PARAMETER;
1774
1775     FIXME(":(%p,%ld,%p): stub\n",hkey,SecurityInfo,pSecurityDesc);
1776
1777     return ERROR_SUCCESS;
1778 }
1779
1780
1781 /******************************************************************************
1782  * RegGetKeySecurity [ADVAPI32.@]
1783  * Retrieves a copy of security descriptor protecting the registry key
1784  *
1785  * PARAMS
1786  *    hkey                   [I]   Open handle of key to set
1787  *    SecurityInformation    [I]   Descriptor contents
1788  *    pSecurityDescriptor    [O]   Address of descriptor for key
1789  *    lpcbSecurityDescriptor [I/O] Address of size of buffer and description
1790  *
1791  * RETURNS
1792  *    Success: ERROR_SUCCESS
1793  *    Failure: Error code
1794  */
1795 LONG WINAPI RegGetKeySecurity( HKEY hkey, SECURITY_INFORMATION SecurityInformation,
1796                                PSECURITY_DESCRIPTOR pSecurityDescriptor,
1797                                LPDWORD lpcbSecurityDescriptor )
1798 {
1799     TRACE("(%p,%ld,%p,%ld)\n",hkey,SecurityInformation,pSecurityDescriptor,
1800           lpcbSecurityDescriptor?*lpcbSecurityDescriptor:0);
1801
1802     /* FIXME: Check for valid SecurityInformation values */
1803
1804     if (*lpcbSecurityDescriptor < sizeof(SECURITY_DESCRIPTOR))
1805         return ERROR_INSUFFICIENT_BUFFER;
1806
1807     FIXME("(%p,%ld,%p,%ld): stub\n",hkey,SecurityInformation,
1808           pSecurityDescriptor,lpcbSecurityDescriptor?*lpcbSecurityDescriptor:0);
1809
1810     /* Do not leave security descriptor filled with garbage */
1811     RtlCreateSecurityDescriptor(pSecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
1812
1813     return ERROR_SUCCESS;
1814 }
1815
1816
1817 /******************************************************************************
1818  * RegFlushKey [ADVAPI32.@]
1819  * Immediately writes key to registry.
1820  * Only returns after data has been written to disk.
1821  *
1822  * FIXME: does it really wait until data is written ?
1823  *
1824  * PARAMS
1825  *    hkey [I] Handle of key to write
1826  *
1827  * RETURNS
1828  *    Success: ERROR_SUCCESS
1829  *    Failure: Error code
1830  */
1831 DWORD WINAPI RegFlushKey( HKEY hkey )
1832 {
1833     FIXME( "(%p): stub\n", hkey );
1834     return ERROR_SUCCESS;
1835 }
1836
1837
1838 /******************************************************************************
1839  * RegConnectRegistryW [ADVAPI32.@]
1840  *
1841  * PARAMS
1842  *    lpMachineName [I] Address of name of remote computer
1843  *    hHey          [I] Predefined registry handle
1844  *    phkResult     [I] Address of buffer for remote registry handle
1845  */
1846 LONG WINAPI RegConnectRegistryW( LPCWSTR lpMachineName, HKEY hKey,
1847                                    PHKEY phkResult )
1848 {
1849     TRACE("(%s,%p,%p): stub\n",debugstr_w(lpMachineName),hKey,phkResult);
1850
1851     if (!lpMachineName || !*lpMachineName) {
1852         /* Use the local machine name */
1853         return RegOpenKeyW( hKey, NULL, phkResult );
1854     }
1855
1856     FIXME("Cannot connect to %s\n",debugstr_w(lpMachineName));
1857     return ERROR_BAD_NETPATH;
1858 }
1859
1860
1861 /******************************************************************************
1862  * RegConnectRegistryA [ADVAPI32.@]
1863  */
1864 LONG WINAPI RegConnectRegistryA( LPCSTR machine, HKEY hkey, PHKEY reskey )
1865 {
1866     UNICODE_STRING machineW;
1867     LONG ret;
1868
1869     RtlCreateUnicodeStringFromAsciiz( &machineW, machine );
1870     ret = RegConnectRegistryW( machineW.Buffer, hkey, reskey );
1871     RtlFreeUnicodeString( &machineW );
1872     return ret;
1873 }
1874
1875
1876 /******************************************************************************
1877  * RegNotifyChangeKeyValue [ADVAPI32.@]
1878  *
1879  * PARAMS
1880  *    hkey            [I] Handle of key to watch
1881  *    fWatchSubTree   [I] Flag for subkey notification
1882  *    fdwNotifyFilter [I] Changes to be reported
1883  *    hEvent          [I] Handle of signaled event
1884  *    fAsync          [I] Flag for asynchronous reporting
1885  */
1886 LONG WINAPI RegNotifyChangeKeyValue( HKEY hkey, BOOL fWatchSubTree,
1887                                      DWORD fdwNotifyFilter, HANDLE hEvent,
1888                                      BOOL fAsync )
1889 {
1890     LONG ret;
1891
1892     TRACE("(%p,%i,%ld,%p,%i)\n",hkey,fWatchSubTree,fdwNotifyFilter,
1893           hEvent,fAsync);
1894
1895     if( !fAsync )
1896         hEvent = CreateEventA(NULL, 0, 0, NULL);
1897
1898     SERVER_START_REQ( set_registry_notification )
1899     {
1900         req->hkey    = hkey;
1901         req->event   = hEvent;
1902         req->subtree = fWatchSubTree;
1903         req->filter  = fdwNotifyFilter;
1904         ret = RtlNtStatusToDosError( wine_server_call(req) );
1905     }
1906     SERVER_END_REQ;
1907  
1908     if( !fAsync )
1909     {
1910         if( ret == ERROR_SUCCESS )
1911             WaitForSingleObject( hEvent, INFINITE );
1912         CloseHandle( hEvent );
1913     }
1914
1915     return ret;
1916 }