server: Use the prefix architecture instead of the server one to check for WoW processes.
[wine] / server / registry.c
1 /*
2  * Server-side registry management
3  *
4  * Copyright (C) 1999 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 /* To do:
22  * - symbolic links
23  */
24
25 #include "config.h"
26 #include "wine/port.h"
27
28 #include <assert.h>
29 #include <ctype.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <limits.h>
33 #include <stdio.h>
34 #include <stdarg.h>
35 #include <string.h>
36 #include <stdlib.h>
37 #include <sys/stat.h>
38 #include <unistd.h>
39
40 #include "ntstatus.h"
41 #define WIN32_NO_STATUS
42 #include "object.h"
43 #include "file.h"
44 #include "handle.h"
45 #include "request.h"
46 #include "process.h"
47 #include "unicode.h"
48 #include "security.h"
49
50 #include "winternl.h"
51 #include "wine/library.h"
52
53 struct notify
54 {
55     struct list       entry;    /* entry in list of notifications */
56     struct event     *event;    /* event to set when changing this key */
57     int               subtree;  /* true if subtree notification */
58     unsigned int      filter;   /* which events to notify on */
59     obj_handle_t      hkey;     /* hkey associated with this notification */
60     struct process   *process;  /* process in which the hkey is valid */
61 };
62
63 /* a registry key */
64 struct key
65 {
66     struct object     obj;         /* object header */
67     WCHAR            *name;        /* key name */
68     WCHAR            *class;       /* key class */
69     unsigned short    namelen;     /* length of key name */
70     unsigned short    classlen;    /* length of class name */
71     struct key       *parent;      /* parent key */
72     int               last_subkey; /* last in use subkey */
73     int               nb_subkeys;  /* count of allocated subkeys */
74     struct key      **subkeys;     /* subkeys array */
75     int               last_value;  /* last in use value */
76     int               nb_values;   /* count of allocated values in array */
77     struct key_value *values;      /* values array */
78     unsigned int      flags;       /* flags */
79     timeout_t         modif;       /* last modification time */
80     struct list       notify_list; /* list of notifications */
81 };
82
83 /* key flags */
84 #define KEY_VOLATILE 0x0001  /* key is volatile (not saved to disk) */
85 #define KEY_DELETED  0x0002  /* key has been deleted */
86 #define KEY_DIRTY    0x0004  /* key has been modified */
87 #define KEY_SYMLINK  0x0008  /* key is a symbolic link */
88 #define KEY_WOW64    0x0010  /* key contains a Wow6432Node subkey */
89 #define KEY_WOWSHARE 0x0020  /* key is a Wow64 shared key (used for Software\Classes) */
90
91 /* a key value */
92 struct key_value
93 {
94     WCHAR            *name;    /* value name */
95     unsigned short    namelen; /* length of value name */
96     unsigned short    type;    /* value type */
97     data_size_t       len;     /* value data length in bytes */
98     void             *data;    /* pointer to value data */
99 };
100
101 #define MIN_SUBKEYS  8   /* min. number of allocated subkeys per key */
102 #define MIN_VALUES   8   /* min. number of allocated values per key */
103
104 #define MAX_NAME_LEN  255    /* max. length of a key name */
105 #define MAX_VALUE_LEN 16383  /* max. length of a value name */
106
107 /* the root of the registry tree */
108 static struct key *root_key;
109
110 static const timeout_t ticks_1601_to_1970 = (timeout_t)86400 * (369 * 365 + 89) * TICKS_PER_SEC;
111 static const timeout_t save_period = 30 * -TICKS_PER_SEC;  /* delay between periodic saves */
112 static struct timeout_user *save_timeout_user;  /* saving timer */
113 static enum prefix_type { PREFIX_UNKNOWN, PREFIX_32BIT, PREFIX_64BIT } prefix_type;
114
115 static const WCHAR root_name[] = { '\\','R','e','g','i','s','t','r','y','\\' };
116 static const WCHAR wow6432node[] = {'W','o','w','6','4','3','2','N','o','d','e'};
117 static const WCHAR symlink_value[] = {'S','y','m','b','o','l','i','c','L','i','n','k','V','a','l','u','e'};
118 static const struct unicode_str symlink_str = { symlink_value, sizeof(symlink_value) };
119
120 static void set_periodic_save_timer(void);
121 static struct key_value *find_value( const struct key *key, const struct unicode_str *name, int *index );
122
123 /* information about where to save a registry branch */
124 struct save_branch_info
125 {
126     struct key  *key;
127     const char  *path;
128 };
129
130 #define MAX_SAVE_BRANCH_INFO 3
131 static int save_branch_count;
132 static struct save_branch_info save_branch_info[MAX_SAVE_BRANCH_INFO];
133
134
135 /* information about a file being loaded */
136 struct file_load_info
137 {
138     const char *filename; /* input file name */
139     FILE       *file;     /* input file */
140     char       *buffer;   /* line buffer */
141     int         len;      /* buffer length */
142     int         line;     /* current input line */
143     WCHAR      *tmp;      /* temp buffer to use while parsing input */
144     size_t      tmplen;   /* length of temp buffer */
145 };
146
147
148 static void key_dump( struct object *obj, int verbose );
149 static unsigned int key_map_access( struct object *obj, unsigned int access );
150 static int key_close_handle( struct object *obj, struct process *process, obj_handle_t handle );
151 static void key_destroy( struct object *obj );
152
153 static const struct object_ops key_ops =
154 {
155     sizeof(struct key),      /* size */
156     key_dump,                /* dump */
157     no_get_type,             /* get_type */
158     no_add_queue,            /* add_queue */
159     NULL,                    /* remove_queue */
160     NULL,                    /* signaled */
161     NULL,                    /* satisfied */
162     no_signal,               /* signal */
163     no_get_fd,               /* get_fd */
164     key_map_access,          /* map_access */
165     default_get_sd,          /* get_sd */
166     default_set_sd,          /* set_sd */
167     no_lookup_name,          /* lookup_name */
168     no_open_file,            /* open_file */
169     key_close_handle,        /* close_handle */
170     key_destroy              /* destroy */
171 };
172
173
174 static inline int is_wow6432node( const WCHAR *name, unsigned int len )
175 {
176     return (len == sizeof(wow6432node) &&
177             !memicmpW( name, wow6432node, sizeof(wow6432node)/sizeof(WCHAR) ));
178 }
179
180 /*
181  * The registry text file format v2 used by this code is similar to the one
182  * used by REGEDIT import/export functionality, with the following differences:
183  * - strings and key names can contain \x escapes for Unicode
184  * - key names use escapes too in order to support Unicode
185  * - the modification time optionally follows the key name
186  * - REG_EXPAND_SZ and REG_MULTI_SZ are saved as strings instead of hex
187  */
188
189 /* dump the full path of a key */
190 static void dump_path( const struct key *key, const struct key *base, FILE *f )
191 {
192     if (key->parent && key->parent != base)
193     {
194         dump_path( key->parent, base, f );
195         fprintf( f, "\\\\" );
196     }
197     dump_strW( key->name, key->namelen / sizeof(WCHAR), f, "[]" );
198 }
199
200 /* dump a value to a text file */
201 static void dump_value( const struct key_value *value, FILE *f )
202 {
203     unsigned int i, dw;
204     int count;
205
206     if (value->namelen)
207     {
208         fputc( '\"', f );
209         count = 1 + dump_strW( value->name, value->namelen / sizeof(WCHAR), f, "\"\"" );
210         count += fprintf( f, "\"=" );
211     }
212     else count = fprintf( f, "@=" );
213
214     switch(value->type)
215     {
216     case REG_SZ:
217     case REG_EXPAND_SZ:
218     case REG_MULTI_SZ:
219         /* only output properly terminated strings in string format */
220         if (value->len < sizeof(WCHAR)) break;
221         if (value->len % sizeof(WCHAR)) break;
222         if (((WCHAR *)value->data)[value->len / sizeof(WCHAR) - 1]) break;
223         if (value->type != REG_SZ) fprintf( f, "str(%x):", value->type );
224         fputc( '\"', f );
225         dump_strW( (WCHAR *)value->data, value->len / sizeof(WCHAR), f, "\"\"" );
226         fprintf( f, "\"\n" );
227         return;
228
229     case REG_DWORD:
230         if (value->len != sizeof(dw)) break;
231         memcpy( &dw, value->data, sizeof(dw) );
232         fprintf( f, "dword:%08x\n", dw );
233         return;
234     }
235
236     if (value->type == REG_BINARY) count += fprintf( f, "hex:" );
237     else count += fprintf( f, "hex(%x):", value->type );
238     for (i = 0; i < value->len; i++)
239     {
240         count += fprintf( f, "%02x", *((unsigned char *)value->data + i) );
241         if (i < value->len-1)
242         {
243             fputc( ',', f );
244             if (++count > 76)
245             {
246                 fprintf( f, "\\\n  " );
247                 count = 2;
248             }
249         }
250     }
251     fputc( '\n', f );
252 }
253
254 /* save a registry and all its subkeys to a text file */
255 static void save_subkeys( const struct key *key, const struct key *base, FILE *f )
256 {
257     int i;
258
259     if (key->flags & KEY_VOLATILE) return;
260     /* save key if it has either some values or no subkeys, or needs special options */
261     /* keys with no values but subkeys are saved implicitly by saving the subkeys */
262     if ((key->last_value >= 0) || (key->last_subkey == -1) || key->class || (key->flags & KEY_SYMLINK))
263     {
264         fprintf( f, "\n[" );
265         if (key != base) dump_path( key, base, f );
266         fprintf( f, "] %u\n", (unsigned int)((key->modif - ticks_1601_to_1970) / TICKS_PER_SEC) );
267         if (key->class)
268         {
269             fprintf( f, "#class=\"" );
270             dump_strW( key->class, key->classlen / sizeof(WCHAR), f, "\"\"" );
271             fprintf( f, "\"\n" );
272         }
273         if (key->flags & KEY_SYMLINK) fputs( "#link\n", f );
274         for (i = 0; i <= key->last_value; i++) dump_value( &key->values[i], f );
275     }
276     for (i = 0; i <= key->last_subkey; i++) save_subkeys( key->subkeys[i], base, f );
277 }
278
279 static void dump_operation( const struct key *key, const struct key_value *value, const char *op )
280 {
281     fprintf( stderr, "%s key ", op );
282     if (key) dump_path( key, NULL, stderr );
283     else fprintf( stderr, "ERROR" );
284     if (value)
285     {
286         fprintf( stderr, " value ");
287         dump_value( value, stderr );
288     }
289     else fprintf( stderr, "\n" );
290 }
291
292 static void key_dump( struct object *obj, int verbose )
293 {
294     struct key *key = (struct key *)obj;
295     assert( obj->ops == &key_ops );
296     fprintf( stderr, "Key flags=%x ", key->flags );
297     dump_path( key, NULL, stderr );
298     fprintf( stderr, "\n" );
299 }
300
301 /* notify waiter and maybe delete the notification */
302 static void do_notification( struct key *key, struct notify *notify, int del )
303 {
304     if (notify->event)
305     {
306         set_event( notify->event );
307         release_object( notify->event );
308         notify->event = NULL;
309     }
310     if (del)
311     {
312         list_remove( &notify->entry );
313         free( notify );
314     }
315 }
316
317 static inline struct notify *find_notify( struct key *key, struct process *process, obj_handle_t hkey )
318 {
319     struct notify *notify;
320
321     LIST_FOR_EACH_ENTRY( notify, &key->notify_list, struct notify, entry )
322     {
323         if (notify->process == process && notify->hkey == hkey) return notify;
324     }
325     return NULL;
326 }
327
328 static unsigned int key_map_access( struct object *obj, unsigned int access )
329 {
330     if (access & GENERIC_READ)    access |= KEY_READ;
331     if (access & GENERIC_WRITE)   access |= KEY_WRITE;
332     if (access & GENERIC_EXECUTE) access |= KEY_EXECUTE;
333     if (access & GENERIC_ALL)     access |= KEY_ALL_ACCESS;
334     return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
335 }
336
337 /* close the notification associated with a handle */
338 static int key_close_handle( struct object *obj, struct process *process, obj_handle_t handle )
339 {
340     struct key * key = (struct key *) obj;
341     struct notify *notify = find_notify( key, process, handle );
342     if (notify) do_notification( key, notify, 1 );
343     return 1;  /* ok to close */
344 }
345
346 static void key_destroy( struct object *obj )
347 {
348     int i;
349     struct list *ptr;
350     struct key *key = (struct key *)obj;
351     assert( obj->ops == &key_ops );
352
353     free( key->name );
354     free( key->class );
355     for (i = 0; i <= key->last_value; i++)
356     {
357         free( key->values[i].name );
358         free( key->values[i].data );
359     }
360     free( key->values );
361     for (i = 0; i <= key->last_subkey; i++)
362     {
363         key->subkeys[i]->parent = NULL;
364         release_object( key->subkeys[i] );
365     }
366     free( key->subkeys );
367     /* unconditionally notify everything waiting on this key */
368     while ((ptr = list_head( &key->notify_list )))
369     {
370         struct notify *notify = LIST_ENTRY( ptr, struct notify, entry );
371         do_notification( key, notify, 1 );
372     }
373 }
374
375 /* get the request vararg as registry path */
376 static inline void get_req_path( struct unicode_str *str, int skip_root )
377 {
378     str->str = get_req_data();
379     str->len = (get_req_data_size() / sizeof(WCHAR)) * sizeof(WCHAR);
380
381     if (skip_root && str->len >= sizeof(root_name) &&
382         !memicmpW( str->str, root_name, sizeof(root_name)/sizeof(WCHAR) ))
383     {
384         str->str += sizeof(root_name)/sizeof(WCHAR);
385         str->len -= sizeof(root_name);
386     }
387 }
388
389 /* return the next token in a given path */
390 /* token->str must point inside the path, or be NULL for the first call */
391 static struct unicode_str *get_path_token( const struct unicode_str *path, struct unicode_str *token )
392 {
393     data_size_t i = 0, len = path->len / sizeof(WCHAR);
394
395     if (!token->str)  /* first time */
396     {
397         /* path cannot start with a backslash */
398         if (len && path->str[0] == '\\')
399         {
400             set_error( STATUS_OBJECT_PATH_INVALID );
401             return NULL;
402         }
403     }
404     else
405     {
406         i = token->str - path->str;
407         i += token->len / sizeof(WCHAR);
408         while (i < len && path->str[i] == '\\') i++;
409     }
410     token->str = path->str + i;
411     while (i < len && path->str[i] != '\\') i++;
412     token->len = (path->str + i - token->str) * sizeof(WCHAR);
413     return token;
414 }
415
416 /* allocate a key object */
417 static struct key *alloc_key( const struct unicode_str *name, timeout_t modif )
418 {
419     struct key *key;
420     if ((key = alloc_object( &key_ops )))
421     {
422         key->name        = NULL;
423         key->class       = NULL;
424         key->namelen     = name->len;
425         key->classlen    = 0;
426         key->flags       = 0;
427         key->last_subkey = -1;
428         key->nb_subkeys  = 0;
429         key->subkeys     = NULL;
430         key->nb_values   = 0;
431         key->last_value  = -1;
432         key->values      = NULL;
433         key->modif       = modif;
434         key->parent      = NULL;
435         list_init( &key->notify_list );
436         if (name->len && !(key->name = memdup( name->str, name->len )))
437         {
438             release_object( key );
439             key = NULL;
440         }
441     }
442     return key;
443 }
444
445 /* mark a key and all its parents as dirty (modified) */
446 static void make_dirty( struct key *key )
447 {
448     while (key)
449     {
450         if (key->flags & (KEY_DIRTY|KEY_VOLATILE)) return;  /* nothing to do */
451         key->flags |= KEY_DIRTY;
452         key = key->parent;
453     }
454 }
455
456 /* mark a key and all its subkeys as clean (not modified) */
457 static void make_clean( struct key *key )
458 {
459     int i;
460
461     if (key->flags & KEY_VOLATILE) return;
462     if (!(key->flags & KEY_DIRTY)) return;
463     key->flags &= ~KEY_DIRTY;
464     for (i = 0; i <= key->last_subkey; i++) make_clean( key->subkeys[i] );
465 }
466
467 /* go through all the notifications and send them if necessary */
468 static void check_notify( struct key *key, unsigned int change, int not_subtree )
469 {
470     struct list *ptr, *next;
471
472     LIST_FOR_EACH_SAFE( ptr, next, &key->notify_list )
473     {
474         struct notify *n = LIST_ENTRY( ptr, struct notify, entry );
475         if ( ( not_subtree || n->subtree ) && ( change & n->filter ) )
476             do_notification( key, n, 0 );
477     }
478 }
479
480 /* update key modification time */
481 static void touch_key( struct key *key, unsigned int change )
482 {
483     struct key *k;
484
485     key->modif = current_time;
486     make_dirty( key );
487
488     /* do notifications */
489     check_notify( key, change, 1 );
490     for ( k = key->parent; k; k = k->parent )
491         check_notify( k, change & ~REG_NOTIFY_CHANGE_LAST_SET, 0 );
492 }
493
494 /* try to grow the array of subkeys; return 1 if OK, 0 on error */
495 static int grow_subkeys( struct key *key )
496 {
497     struct key **new_subkeys;
498     int nb_subkeys;
499
500     if (key->nb_subkeys)
501     {
502         nb_subkeys = key->nb_subkeys + (key->nb_subkeys / 2);  /* grow by 50% */
503         if (!(new_subkeys = realloc( key->subkeys, nb_subkeys * sizeof(*new_subkeys) )))
504         {
505             set_error( STATUS_NO_MEMORY );
506             return 0;
507         }
508     }
509     else
510     {
511         nb_subkeys = MIN_VALUES;
512         if (!(new_subkeys = mem_alloc( nb_subkeys * sizeof(*new_subkeys) ))) return 0;
513     }
514     key->subkeys    = new_subkeys;
515     key->nb_subkeys = nb_subkeys;
516     return 1;
517 }
518
519 /* allocate a subkey for a given key, and return its index */
520 static struct key *alloc_subkey( struct key *parent, const struct unicode_str *name,
521                                  int index, timeout_t modif )
522 {
523     struct key *key;
524     int i;
525
526     if (name->len > MAX_NAME_LEN * sizeof(WCHAR))
527     {
528         set_error( STATUS_NAME_TOO_LONG );
529         return NULL;
530     }
531     if (parent->last_subkey + 1 == parent->nb_subkeys)
532     {
533         /* need to grow the array */
534         if (!grow_subkeys( parent )) return NULL;
535     }
536     if ((key = alloc_key( name, modif )) != NULL)
537     {
538         key->parent = parent;
539         for (i = ++parent->last_subkey; i > index; i--)
540             parent->subkeys[i] = parent->subkeys[i-1];
541         parent->subkeys[index] = key;
542         if (is_wow6432node( key->name, key->namelen ) && !is_wow6432node( parent->name, parent->namelen ))
543             parent->flags |= KEY_WOW64;
544     }
545     return key;
546 }
547
548 /* free a subkey of a given key */
549 static void free_subkey( struct key *parent, int index )
550 {
551     struct key *key;
552     int i, nb_subkeys;
553
554     assert( index >= 0 );
555     assert( index <= parent->last_subkey );
556
557     key = parent->subkeys[index];
558     for (i = index; i < parent->last_subkey; i++) parent->subkeys[i] = parent->subkeys[i + 1];
559     parent->last_subkey--;
560     key->flags |= KEY_DELETED;
561     key->parent = NULL;
562     if (is_wow6432node( key->name, key->namelen )) parent->flags &= ~KEY_WOW64;
563     release_object( key );
564
565     /* try to shrink the array */
566     nb_subkeys = parent->nb_subkeys;
567     if (nb_subkeys > MIN_SUBKEYS && parent->last_subkey < nb_subkeys / 2)
568     {
569         struct key **new_subkeys;
570         nb_subkeys -= nb_subkeys / 3;  /* shrink by 33% */
571         if (nb_subkeys < MIN_SUBKEYS) nb_subkeys = MIN_SUBKEYS;
572         if (!(new_subkeys = realloc( parent->subkeys, nb_subkeys * sizeof(*new_subkeys) ))) return;
573         parent->subkeys = new_subkeys;
574         parent->nb_subkeys = nb_subkeys;
575     }
576 }
577
578 /* find the named child of a given key and return its index */
579 static struct key *find_subkey( const struct key *key, const struct unicode_str *name, int *index )
580 {
581     int i, min, max, res;
582     data_size_t len;
583
584     min = 0;
585     max = key->last_subkey;
586     while (min <= max)
587     {
588         i = (min + max) / 2;
589         len = min( key->subkeys[i]->namelen, name->len );
590         res = memicmpW( key->subkeys[i]->name, name->str, len / sizeof(WCHAR) );
591         if (!res) res = key->subkeys[i]->namelen - name->len;
592         if (!res)
593         {
594             *index = i;
595             return key->subkeys[i];
596         }
597         if (res > 0) max = i - 1;
598         else min = i + 1;
599     }
600     *index = min;  /* this is where we should insert it */
601     return NULL;
602 }
603
604 /* return the wow64 variant of the key, or the key itself if none */
605 static struct key *find_wow64_subkey( struct key *key, const struct unicode_str *name )
606 {
607     static const struct unicode_str wow6432node_str = { wow6432node, sizeof(wow6432node) };
608     int index;
609
610     if (!(key->flags & KEY_WOW64)) return key;
611     if (!is_wow6432node( name->str, name->len ))
612     {
613         key = find_subkey( key, &wow6432node_str, &index );
614         assert( key );  /* if KEY_WOW64 is set we must find it */
615     }
616     return key;
617 }
618
619
620 /* follow a symlink and return the resolved key */
621 static struct key *follow_symlink( struct key *key, int iteration )
622 {
623     struct unicode_str path, token;
624     struct key_value *value;
625     int index;
626
627     if (iteration > 16) return NULL;
628     if (!(key->flags & KEY_SYMLINK)) return key;
629     if (!(value = find_value( key, &symlink_str, &index ))) return NULL;
630
631     path.str = value->data;
632     path.len = (value->len / sizeof(WCHAR)) * sizeof(WCHAR);
633     if (path.len <= sizeof(root_name)) return NULL;
634     if (memicmpW( path.str, root_name, sizeof(root_name)/sizeof(WCHAR) )) return NULL;
635     path.str += sizeof(root_name) / sizeof(WCHAR);
636     path.len -= sizeof(root_name);
637
638     key = root_key;
639     token.str = NULL;
640     if (!get_path_token( &path, &token )) return NULL;
641     while (token.len)
642     {
643         if (!(key = find_subkey( key, &token, &index ))) break;
644         if (!(key = follow_symlink( key, iteration + 1 ))) break;
645         get_path_token( &path, &token );
646     }
647     return key;
648 }
649
650 /* open a key until we find an element that doesn't exist */
651 /* helper for open_key and create_key */
652 static struct key *open_key_prefix( struct key *key, const struct unicode_str *name,
653                                     unsigned int access, struct unicode_str *token, int *index )
654 {
655     token->str = NULL;
656     if (!get_path_token( name, token )) return NULL;
657     if (access & KEY_WOW64_32KEY) key = find_wow64_subkey( key, token );
658     while (token->len)
659     {
660         struct key *subkey;
661         if (!(subkey = find_subkey( key, token, index )))
662         {
663             if ((key->flags & KEY_WOWSHARE) && !(access & KEY_WOW64_64KEY))
664             {
665                 /* try in the 64-bit parent */
666                 key = key->parent;
667                 subkey = find_subkey( key, token, index );
668             }
669         }
670         if (!subkey) break;
671         key = subkey;
672         get_path_token( name, token );
673         if (!token->len) break;
674         if (!(access & KEY_WOW64_64KEY)) key = find_wow64_subkey( key, token );
675         if (!(key = follow_symlink( key, 0 )))
676         {
677             set_error( STATUS_OBJECT_NAME_NOT_FOUND );
678             return NULL;
679         }
680     }
681     return key;
682 }
683
684 /* open a subkey */
685 static struct key *open_key( struct key *key, const struct unicode_str *name, unsigned int access,
686                              unsigned int attributes )
687 {
688     int index;
689     struct unicode_str token;
690
691     if (!(key = open_key_prefix( key, name, access, &token, &index ))) return NULL;
692
693     if (token.len)
694     {
695         set_error( STATUS_OBJECT_NAME_NOT_FOUND );
696         return NULL;
697     }
698     if (!(access & KEY_WOW64_64KEY)) key = find_wow64_subkey( key, &token );
699     if (!(attributes & OBJ_OPENLINK) && !(key = follow_symlink( key, 0 )))
700     {
701         set_error( STATUS_OBJECT_NAME_NOT_FOUND );
702         return NULL;
703     }
704     if (debug_level > 1) dump_operation( key, NULL, "Open" );
705     grab_object( key );
706     return key;
707 }
708
709 /* create a subkey */
710 static struct key *create_key( struct key *key, const struct unicode_str *name,
711                                const struct unicode_str *class, unsigned int options,
712                                unsigned int access, unsigned int attributes, int *created )
713 {
714     int index;
715     struct unicode_str token, next;
716
717     *created = 0;
718     if (!(key = open_key_prefix( key, name, access, &token, &index ))) return NULL;
719
720     if (!token.len)  /* the key already exists */
721     {
722         if (!(access & KEY_WOW64_64KEY)) key = find_wow64_subkey( key, &token );
723         if (options & REG_OPTION_CREATE_LINK)
724         {
725             set_error( STATUS_OBJECT_NAME_COLLISION );
726             return NULL;
727         }
728         if (!(attributes & OBJ_OPENLINK) && !(key = follow_symlink( key, 0 )))
729         {
730             set_error( STATUS_OBJECT_NAME_NOT_FOUND );
731             return NULL;
732         }
733         if (debug_level > 1) dump_operation( key, NULL, "Open" );
734         grab_object( key );
735         return key;
736     }
737
738     /* token must be the last path component at this point */
739     next = token;
740     get_path_token( name, &next );
741     if (next.len)
742     {
743         set_error( STATUS_OBJECT_NAME_NOT_FOUND );
744         return NULL;
745     }
746
747     if ((key->flags & KEY_VOLATILE) && !(options & REG_OPTION_VOLATILE))
748     {
749         set_error( STATUS_CHILD_MUST_BE_VOLATILE );
750         return NULL;
751     }
752     *created = 1;
753     make_dirty( key );
754     if (!(key = alloc_subkey( key, &token, index, current_time ))) return NULL;
755
756     if (options & REG_OPTION_CREATE_LINK) key->flags |= KEY_SYMLINK;
757     if (options & REG_OPTION_VOLATILE) key->flags |= KEY_VOLATILE;
758     else key->flags |= KEY_DIRTY;
759
760     if (debug_level > 1) dump_operation( key, NULL, "Create" );
761     if (class && class->len)
762     {
763         key->classlen = class->len;
764         free(key->class);
765         if (!(key->class = memdup( class->str, key->classlen ))) key->classlen = 0;
766     }
767     grab_object( key );
768     return key;
769 }
770
771 /* recursively create a subkey (for internal use only) */
772 static struct key *create_key_recursive( struct key *key, const struct unicode_str *name, timeout_t modif )
773 {
774     struct key *base;
775     int index;
776     struct unicode_str token;
777
778     token.str = NULL;
779     if (!get_path_token( name, &token )) return NULL;
780     while (token.len)
781     {
782         struct key *subkey;
783         if (!(subkey = find_subkey( key, &token, &index ))) break;
784         key = subkey;
785         if (!(key = follow_symlink( key, 0 )))
786         {
787             set_error( STATUS_OBJECT_NAME_NOT_FOUND );
788             return NULL;
789         }
790         get_path_token( name, &token );
791     }
792
793     if (token.len)
794     {
795         if (!(key = alloc_subkey( key, &token, index, modif ))) return NULL;
796         base = key;
797         for (;;)
798         {
799             get_path_token( name, &token );
800             if (!token.len) break;
801             /* we know the index is always 0 in a new key */
802             if (!(key = alloc_subkey( key, &token, 0, modif )))
803             {
804                 free_subkey( base, index );
805                 return NULL;
806             }
807         }
808     }
809
810     grab_object( key );
811     return key;
812 }
813
814 /* query information about a key or a subkey */
815 static void enum_key( const struct key *key, int index, int info_class,
816                       struct enum_key_reply *reply )
817 {
818     int i;
819     data_size_t len, namelen, classlen;
820     data_size_t max_subkey = 0, max_class = 0;
821     data_size_t max_value = 0, max_data = 0;
822     char *data;
823
824     if (index != -1)  /* -1 means use the specified key directly */
825     {
826         if ((index < 0) || (index > key->last_subkey))
827         {
828             set_error( STATUS_NO_MORE_ENTRIES );
829             return;
830         }
831         key = key->subkeys[index];
832     }
833
834     namelen = key->namelen;
835     classlen = key->classlen;
836
837     switch(info_class)
838     {
839     case KeyBasicInformation:
840         classlen = 0; /* only return the name */
841         /* fall through */
842     case KeyNodeInformation:
843         reply->max_subkey = 0;
844         reply->max_class  = 0;
845         reply->max_value  = 0;
846         reply->max_data   = 0;
847         break;
848     case KeyFullInformation:
849         for (i = 0; i <= key->last_subkey; i++)
850         {
851             struct key *subkey = key->subkeys[i];
852             len = subkey->namelen / sizeof(WCHAR);
853             if (len > max_subkey) max_subkey = len;
854             len = subkey->classlen / sizeof(WCHAR);
855             if (len > max_class) max_class = len;
856         }
857         for (i = 0; i <= key->last_value; i++)
858         {
859             len = key->values[i].namelen / sizeof(WCHAR);
860             if (len > max_value) max_value = len;
861             len = key->values[i].len;
862             if (len > max_data) max_data = len;
863         }
864         reply->max_subkey = max_subkey;
865         reply->max_class  = max_class;
866         reply->max_value  = max_value;
867         reply->max_data   = max_data;
868         namelen = 0;  /* only return the class */
869         break;
870     default:
871         set_error( STATUS_INVALID_PARAMETER );
872         return;
873     }
874     reply->subkeys = key->last_subkey + 1;
875     reply->values  = key->last_value + 1;
876     reply->modif   = key->modif;
877     reply->total   = namelen + classlen;
878
879     len = min( reply->total, get_reply_max_size() );
880     if (len && (data = set_reply_data_size( len )))
881     {
882         if (len > namelen)
883         {
884             reply->namelen = namelen;
885             memcpy( data, key->name, namelen );
886             memcpy( data + namelen, key->class, len - namelen );
887         }
888         else
889         {
890             reply->namelen = len;
891             memcpy( data, key->name, len );
892         }
893     }
894     if (debug_level > 1) dump_operation( key, NULL, "Enum" );
895 }
896
897 /* delete a key and its values */
898 static int delete_key( struct key *key, int recurse )
899 {
900     int index;
901     struct key *parent = key->parent;
902
903     /* must find parent and index */
904     if (key == root_key)
905     {
906         set_error( STATUS_ACCESS_DENIED );
907         return -1;
908     }
909     assert( parent );
910
911     while (recurse && (key->last_subkey>=0))
912         if (0 > delete_key(key->subkeys[key->last_subkey], 1))
913             return -1;
914
915     for (index = 0; index <= parent->last_subkey; index++)
916         if (parent->subkeys[index] == key) break;
917     assert( index <= parent->last_subkey );
918
919     /* we can only delete a key that has no subkeys */
920     if (key->last_subkey >= 0)
921     {
922         set_error( STATUS_ACCESS_DENIED );
923         return -1;
924     }
925
926     if (debug_level > 1) dump_operation( key, NULL, "Delete" );
927     free_subkey( parent, index );
928     touch_key( parent, REG_NOTIFY_CHANGE_NAME );
929     return 0;
930 }
931
932 /* try to grow the array of values; return 1 if OK, 0 on error */
933 static int grow_values( struct key *key )
934 {
935     struct key_value *new_val;
936     int nb_values;
937
938     if (key->nb_values)
939     {
940         nb_values = key->nb_values + (key->nb_values / 2);  /* grow by 50% */
941         if (!(new_val = realloc( key->values, nb_values * sizeof(*new_val) )))
942         {
943             set_error( STATUS_NO_MEMORY );
944             return 0;
945         }
946     }
947     else
948     {
949         nb_values = MIN_VALUES;
950         if (!(new_val = mem_alloc( nb_values * sizeof(*new_val) ))) return 0;
951     }
952     key->values = new_val;
953     key->nb_values = nb_values;
954     return 1;
955 }
956
957 /* find the named value of a given key and return its index in the array */
958 static struct key_value *find_value( const struct key *key, const struct unicode_str *name, int *index )
959 {
960     int i, min, max, res;
961     data_size_t len;
962
963     min = 0;
964     max = key->last_value;
965     while (min <= max)
966     {
967         i = (min + max) / 2;
968         len = min( key->values[i].namelen, name->len );
969         res = memicmpW( key->values[i].name, name->str, len / sizeof(WCHAR) );
970         if (!res) res = key->values[i].namelen - name->len;
971         if (!res)
972         {
973             *index = i;
974             return &key->values[i];
975         }
976         if (res > 0) max = i - 1;
977         else min = i + 1;
978     }
979     *index = min;  /* this is where we should insert it */
980     return NULL;
981 }
982
983 /* insert a new value; the index must have been returned by find_value */
984 static struct key_value *insert_value( struct key *key, const struct unicode_str *name, int index )
985 {
986     struct key_value *value;
987     WCHAR *new_name = NULL;
988     int i;
989
990     if (name->len > MAX_VALUE_LEN * sizeof(WCHAR))
991     {
992         set_error( STATUS_NAME_TOO_LONG );
993         return NULL;
994     }
995     if (key->last_value + 1 == key->nb_values)
996     {
997         if (!grow_values( key )) return NULL;
998     }
999     if (name->len && !(new_name = memdup( name->str, name->len ))) return NULL;
1000     for (i = ++key->last_value; i > index; i--) key->values[i] = key->values[i - 1];
1001     value = &key->values[index];
1002     value->name    = new_name;
1003     value->namelen = name->len;
1004     value->len     = 0;
1005     value->data    = NULL;
1006     return value;
1007 }
1008
1009 /* set a key value */
1010 static void set_value( struct key *key, const struct unicode_str *name,
1011                        int type, const void *data, data_size_t len )
1012 {
1013     struct key_value *value;
1014     void *ptr = NULL;
1015     int index;
1016
1017     if ((value = find_value( key, name, &index )))
1018     {
1019         /* check if the new value is identical to the existing one */
1020         if (value->type == type && value->len == len &&
1021             value->data && !memcmp( value->data, data, len ))
1022         {
1023             if (debug_level > 1) dump_operation( key, value, "Skip setting" );
1024             return;
1025         }
1026     }
1027
1028     if (key->flags & KEY_SYMLINK)
1029     {
1030         if (type != REG_LINK || name->len != symlink_str.len ||
1031             memicmpW( name->str, symlink_str.str, name->len / sizeof(WCHAR) ))
1032         {
1033             set_error( STATUS_ACCESS_DENIED );
1034             return;
1035         }
1036     }
1037
1038     if (len && !(ptr = memdup( data, len ))) return;
1039
1040     if (!value)
1041     {
1042         if (!(value = insert_value( key, name, index )))
1043         {
1044             free( ptr );
1045             return;
1046         }
1047     }
1048     else free( value->data ); /* already existing, free previous data */
1049
1050     value->type  = type;
1051     value->len   = len;
1052     value->data  = ptr;
1053     touch_key( key, REG_NOTIFY_CHANGE_LAST_SET );
1054     if (debug_level > 1) dump_operation( key, value, "Set" );
1055 }
1056
1057 /* get a key value */
1058 static void get_value( struct key *key, const struct unicode_str *name, int *type, data_size_t *len )
1059 {
1060     struct key_value *value;
1061     int index;
1062
1063     if ((value = find_value( key, name, &index )))
1064     {
1065         *type = value->type;
1066         *len  = value->len;
1067         if (value->data) set_reply_data( value->data, min( value->len, get_reply_max_size() ));
1068         if (debug_level > 1) dump_operation( key, value, "Get" );
1069     }
1070     else
1071     {
1072         *type = -1;
1073         set_error( STATUS_OBJECT_NAME_NOT_FOUND );
1074     }
1075 }
1076
1077 /* enumerate a key value */
1078 static void enum_value( struct key *key, int i, int info_class, struct enum_key_value_reply *reply )
1079 {
1080     struct key_value *value;
1081
1082     if (i < 0 || i > key->last_value) set_error( STATUS_NO_MORE_ENTRIES );
1083     else
1084     {
1085         void *data;
1086         data_size_t namelen, maxlen;
1087
1088         value = &key->values[i];
1089         reply->type = value->type;
1090         namelen = value->namelen;
1091
1092         switch(info_class)
1093         {
1094         case KeyValueBasicInformation:
1095             reply->total = namelen;
1096             break;
1097         case KeyValueFullInformation:
1098             reply->total = namelen + value->len;
1099             break;
1100         case KeyValuePartialInformation:
1101             reply->total = value->len;
1102             namelen = 0;
1103             break;
1104         default:
1105             set_error( STATUS_INVALID_PARAMETER );
1106             return;
1107         }
1108
1109         maxlen = min( reply->total, get_reply_max_size() );
1110         if (maxlen && ((data = set_reply_data_size( maxlen ))))
1111         {
1112             if (maxlen > namelen)
1113             {
1114                 reply->namelen = namelen;
1115                 memcpy( data, value->name, namelen );
1116                 memcpy( (char *)data + namelen, value->data, maxlen - namelen );
1117             }
1118             else
1119             {
1120                 reply->namelen = maxlen;
1121                 memcpy( data, value->name, maxlen );
1122             }
1123         }
1124         if (debug_level > 1) dump_operation( key, value, "Enum" );
1125     }
1126 }
1127
1128 /* delete a value */
1129 static void delete_value( struct key *key, const struct unicode_str *name )
1130 {
1131     struct key_value *value;
1132     int i, index, nb_values;
1133
1134     if (!(value = find_value( key, name, &index )))
1135     {
1136         set_error( STATUS_OBJECT_NAME_NOT_FOUND );
1137         return;
1138     }
1139     if (debug_level > 1) dump_operation( key, value, "Delete" );
1140     free( value->name );
1141     free( value->data );
1142     for (i = index; i < key->last_value; i++) key->values[i] = key->values[i + 1];
1143     key->last_value--;
1144     touch_key( key, REG_NOTIFY_CHANGE_LAST_SET );
1145
1146     /* try to shrink the array */
1147     nb_values = key->nb_values;
1148     if (nb_values > MIN_VALUES && key->last_value < nb_values / 2)
1149     {
1150         struct key_value *new_val;
1151         nb_values -= nb_values / 3;  /* shrink by 33% */
1152         if (nb_values < MIN_VALUES) nb_values = MIN_VALUES;
1153         if (!(new_val = realloc( key->values, nb_values * sizeof(*new_val) ))) return;
1154         key->values = new_val;
1155         key->nb_values = nb_values;
1156     }
1157 }
1158
1159 /* get the registry key corresponding to an hkey handle */
1160 static struct key *get_hkey_obj( obj_handle_t hkey, unsigned int access )
1161 {
1162     struct key *key = (struct key *)get_handle_obj( current->process, hkey, access, &key_ops );
1163
1164     if (key && key->flags & KEY_DELETED)
1165     {
1166         set_error( STATUS_KEY_DELETED );
1167         release_object( key );
1168         key = NULL;
1169     }
1170     return key;
1171 }
1172
1173 /* get the registry key corresponding to a parent key handle */
1174 static inline struct key *get_parent_hkey_obj( obj_handle_t hkey )
1175 {
1176     if (!hkey) return (struct key *)grab_object( root_key );
1177     return get_hkey_obj( hkey, 0 );
1178 }
1179
1180 /* read a line from the input file */
1181 static int read_next_line( struct file_load_info *info )
1182 {
1183     char *newbuf;
1184     int newlen, pos = 0;
1185
1186     info->line++;
1187     for (;;)
1188     {
1189         if (!fgets( info->buffer + pos, info->len - pos, info->file ))
1190             return (pos != 0);  /* EOF */
1191         pos = strlen(info->buffer);
1192         if (info->buffer[pos-1] == '\n')
1193         {
1194             /* got a full line */
1195             info->buffer[--pos] = 0;
1196             if (pos > 0 && info->buffer[pos-1] == '\r') info->buffer[pos-1] = 0;
1197             return 1;
1198         }
1199         if (pos < info->len - 1) return 1;  /* EOF but something was read */
1200
1201         /* need to enlarge the buffer */
1202         newlen = info->len + info->len / 2;
1203         if (!(newbuf = realloc( info->buffer, newlen )))
1204         {
1205             set_error( STATUS_NO_MEMORY );
1206             return -1;
1207         }
1208         info->buffer = newbuf;
1209         info->len = newlen;
1210     }
1211 }
1212
1213 /* make sure the temp buffer holds enough space */
1214 static int get_file_tmp_space( struct file_load_info *info, size_t size )
1215 {
1216     WCHAR *tmp;
1217     if (info->tmplen >= size) return 1;
1218     if (!(tmp = realloc( info->tmp, size )))
1219     {
1220         set_error( STATUS_NO_MEMORY );
1221         return 0;
1222     }
1223     info->tmp = tmp;
1224     info->tmplen = size;
1225     return 1;
1226 }
1227
1228 /* report an error while loading an input file */
1229 static void file_read_error( const char *err, struct file_load_info *info )
1230 {
1231     if (info->filename)
1232         fprintf( stderr, "%s:%d: %s '%s'\n", info->filename, info->line, err, info->buffer );
1233     else
1234         fprintf( stderr, "<fd>:%d: %s '%s'\n", info->line, err, info->buffer );
1235 }
1236
1237 /* convert a data type tag to a value type */
1238 static int get_data_type( const char *buffer, int *type, int *parse_type )
1239 {
1240     struct data_type { const char *tag; int len; int type; int parse_type; };
1241
1242     static const struct data_type data_types[] =
1243     {                   /* actual type */  /* type to assume for parsing */
1244         { "\"",        1,   REG_SZ,              REG_SZ },
1245         { "str:\"",    5,   REG_SZ,              REG_SZ },
1246         { "str(2):\"", 8,   REG_EXPAND_SZ,       REG_SZ },
1247         { "str(7):\"", 8,   REG_MULTI_SZ,        REG_SZ },
1248         { "hex:",      4,   REG_BINARY,          REG_BINARY },
1249         { "dword:",    6,   REG_DWORD,           REG_DWORD },
1250         { "hex(",      4,   -1,                  REG_BINARY },
1251         { NULL,        0,    0,                  0 }
1252     };
1253
1254     const struct data_type *ptr;
1255     char *end;
1256
1257     for (ptr = data_types; ptr->tag; ptr++)
1258     {
1259         if (strncmp( ptr->tag, buffer, ptr->len )) continue;
1260         *parse_type = ptr->parse_type;
1261         if ((*type = ptr->type) != -1) return ptr->len;
1262         /* "hex(xx):" is special */
1263         *type = (int)strtoul( buffer + 4, &end, 16 );
1264         if ((end <= buffer) || strncmp( end, "):", 2 )) return 0;
1265         return end + 2 - buffer;
1266     }
1267     return 0;
1268 }
1269
1270 /* load and create a key from the input file */
1271 static struct key *load_key( struct key *base, const char *buffer,
1272                              int prefix_len, struct file_load_info *info )
1273 {
1274     WCHAR *p;
1275     struct unicode_str name;
1276     int res;
1277     unsigned int mod;
1278     timeout_t modif = current_time;
1279     data_size_t len;
1280
1281     if (!get_file_tmp_space( info, strlen(buffer) * sizeof(WCHAR) )) return NULL;
1282
1283     len = info->tmplen;
1284     if ((res = parse_strW( info->tmp, &len, buffer, ']' )) == -1)
1285     {
1286         file_read_error( "Malformed key", info );
1287         return NULL;
1288     }
1289     if (sscanf( buffer + res, " %u", &mod ) == 1)
1290         modif = (timeout_t)mod * TICKS_PER_SEC + ticks_1601_to_1970;
1291
1292     p = info->tmp;
1293     while (prefix_len && *p) { if (*p++ == '\\') prefix_len--; }
1294
1295     if (!*p)
1296     {
1297         if (prefix_len > 1)
1298         {
1299             file_read_error( "Malformed key", info );
1300             return NULL;
1301         }
1302         /* empty key name, return base key */
1303         return (struct key *)grab_object( base );
1304     }
1305     name.str = p;
1306     name.len = len - (p - info->tmp + 1) * sizeof(WCHAR);
1307     return create_key_recursive( base, &name, modif );
1308 }
1309
1310 /* load a global option from the input file */
1311 static int load_global_option( const char *buffer, struct file_load_info *info )
1312 {
1313     const char *p;
1314
1315     if (!strncmp( buffer, "#arch=", 6 ))
1316     {
1317         enum prefix_type type;
1318         p = buffer + 6;
1319         if (!strcmp( p, "win32" )) type = PREFIX_32BIT;
1320         else if (!strcmp( p, "win64" )) type = PREFIX_64BIT;
1321         else
1322         {
1323             file_read_error( "Unknown architecture", info );
1324             set_error( STATUS_NOT_REGISTRY_FILE );
1325             return 0;
1326         }
1327         if (prefix_type == PREFIX_UNKNOWN) prefix_type = type;
1328         else if (type != prefix_type)
1329         {
1330             file_read_error( "Mismatched architecture", info );
1331             set_error( STATUS_NOT_REGISTRY_FILE );
1332             return 0;
1333         }
1334     }
1335     /* ignore unknown options */
1336     return 1;
1337 }
1338
1339 /* load a key option from the input file */
1340 static int load_key_option( struct key *key, const char *buffer, struct file_load_info *info )
1341 {
1342     const char *p;
1343     data_size_t len;
1344
1345     if (!strncmp( buffer, "#class=", 7 ))
1346     {
1347         p = buffer + 7;
1348         if (*p++ != '"') return 0;
1349         if (!get_file_tmp_space( info, strlen(p) * sizeof(WCHAR) )) return 0;
1350         len = info->tmplen;
1351         if (parse_strW( info->tmp, &len, p, '\"' ) == -1) return 0;
1352         free( key->class );
1353         if (!(key->class = memdup( info->tmp, len ))) len = 0;
1354         key->classlen = len;
1355     }
1356     if (!strncmp( buffer, "#link", 5 )) key->flags |= KEY_SYMLINK;
1357     /* ignore unknown options */
1358     return 1;
1359 }
1360
1361 /* parse a comma-separated list of hex digits */
1362 static int parse_hex( unsigned char *dest, data_size_t *len, const char *buffer )
1363 {
1364     const char *p = buffer;
1365     data_size_t count = 0;
1366     char *end;
1367
1368     while (isxdigit(*p))
1369     {
1370         unsigned int val = strtoul( p, &end, 16 );
1371         if (end == p || val > 0xff) return -1;
1372         if (count++ >= *len) return -1;  /* dest buffer overflow */
1373         *dest++ = val;
1374         p = end;
1375         while (isspace(*p)) p++;
1376         if (*p == ',') p++;
1377         while (isspace(*p)) p++;
1378     }
1379     *len = count;
1380     return p - buffer;
1381 }
1382
1383 /* parse a value name and create the corresponding value */
1384 static struct key_value *parse_value_name( struct key *key, const char *buffer, data_size_t *len,
1385                                            struct file_load_info *info )
1386 {
1387     struct key_value *value;
1388     struct unicode_str name;
1389     int index;
1390
1391     if (!get_file_tmp_space( info, strlen(buffer) * sizeof(WCHAR) )) return NULL;
1392     name.str = info->tmp;
1393     name.len = info->tmplen;
1394     if (buffer[0] == '@')
1395     {
1396         name.len = 0;
1397         *len = 1;
1398     }
1399     else
1400     {
1401         int r = parse_strW( info->tmp, &name.len, buffer + 1, '\"' );
1402         if (r == -1) goto error;
1403         *len = r + 1; /* for initial quote */
1404         name.len -= sizeof(WCHAR);  /* terminating null */
1405     }
1406     while (isspace(buffer[*len])) (*len)++;
1407     if (buffer[*len] != '=') goto error;
1408     (*len)++;
1409     while (isspace(buffer[*len])) (*len)++;
1410     if (!(value = find_value( key, &name, &index ))) value = insert_value( key, &name, index );
1411     return value;
1412
1413  error:
1414     file_read_error( "Malformed value name", info );
1415     return NULL;
1416 }
1417
1418 /* load a value from the input file */
1419 static int load_value( struct key *key, const char *buffer, struct file_load_info *info )
1420 {
1421     DWORD dw;
1422     void *ptr, *newptr;
1423     int res, type, parse_type;
1424     data_size_t maxlen, len;
1425     struct key_value *value;
1426
1427     if (!(value = parse_value_name( key, buffer, &len, info ))) return 0;
1428     if (!(res = get_data_type( buffer + len, &type, &parse_type ))) goto error;
1429     buffer += len + res;
1430
1431     switch(parse_type)
1432     {
1433     case REG_SZ:
1434         if (!get_file_tmp_space( info, strlen(buffer) * sizeof(WCHAR) )) return 0;
1435         len = info->tmplen;
1436         if ((res = parse_strW( info->tmp, &len, buffer, '\"' )) == -1) goto error;
1437         ptr = info->tmp;
1438         break;
1439     case REG_DWORD:
1440         dw = strtoul( buffer, NULL, 16 );
1441         ptr = &dw;
1442         len = sizeof(dw);
1443         break;
1444     case REG_BINARY:  /* hex digits */
1445         len = 0;
1446         for (;;)
1447         {
1448             maxlen = 1 + strlen(buffer) / 2;  /* at least 2 chars for one hex byte */
1449             if (!get_file_tmp_space( info, len + maxlen )) return 0;
1450             if ((res = parse_hex( (unsigned char *)info->tmp + len, &maxlen, buffer )) == -1) goto error;
1451             len += maxlen;
1452             buffer += res;
1453             while (isspace(*buffer)) buffer++;
1454             if (!*buffer) break;
1455             if (*buffer != '\\') goto error;
1456             if (read_next_line( info) != 1) goto error;
1457             buffer = info->buffer;
1458             while (isspace(*buffer)) buffer++;
1459         }
1460         ptr = info->tmp;
1461         break;
1462     default:
1463         assert(0);
1464         ptr = NULL;  /* keep compiler quiet */
1465         break;
1466     }
1467
1468     if (!len) newptr = NULL;
1469     else if (!(newptr = memdup( ptr, len ))) return 0;
1470
1471     free( value->data );
1472     value->data = newptr;
1473     value->len  = len;
1474     value->type = type;
1475     return 1;
1476
1477  error:
1478     file_read_error( "Malformed value", info );
1479     free( value->data );
1480     value->data = NULL;
1481     value->len  = 0;
1482     value->type = REG_NONE;
1483     return 0;
1484 }
1485
1486 /* return the length (in path elements) of name that is part of the key name */
1487 /* for instance if key is USER\foo\bar and name is foo\bar\baz, return 2 */
1488 static int get_prefix_len( struct key *key, const char *name, struct file_load_info *info )
1489 {
1490     WCHAR *p;
1491     int res;
1492     data_size_t len;
1493
1494     if (!get_file_tmp_space( info, strlen(name) * sizeof(WCHAR) )) return 0;
1495
1496     len = info->tmplen;
1497     if ((res = parse_strW( info->tmp, &len, name, ']' )) == -1)
1498     {
1499         file_read_error( "Malformed key", info );
1500         return 0;
1501     }
1502     for (p = info->tmp; *p; p++) if (*p == '\\') break;
1503     len = (p - info->tmp) * sizeof(WCHAR);
1504     for (res = 1; key != root_key; res++)
1505     {
1506         if (len == key->namelen && !memicmpW( info->tmp, key->name, len / sizeof(WCHAR) )) break;
1507         key = key->parent;
1508     }
1509     if (key == root_key) res = 0;  /* no matching name */
1510     return res;
1511 }
1512
1513 /* load all the keys from the input file */
1514 /* prefix_len is the number of key name prefixes to skip, or -1 for autodetection */
1515 static void load_keys( struct key *key, const char *filename, FILE *f, int prefix_len )
1516 {
1517     struct key *subkey = NULL;
1518     struct file_load_info info;
1519     char *p;
1520
1521     info.filename = filename;
1522     info.file   = f;
1523     info.len    = 4;
1524     info.tmplen = 4;
1525     info.line   = 0;
1526     if (!(info.buffer = mem_alloc( info.len ))) return;
1527     if (!(info.tmp = mem_alloc( info.tmplen )))
1528     {
1529         free( info.buffer );
1530         return;
1531     }
1532
1533     if ((read_next_line( &info ) != 1) ||
1534         strcmp( info.buffer, "WINE REGISTRY Version 2" ))
1535     {
1536         set_error( STATUS_NOT_REGISTRY_FILE );
1537         goto done;
1538     }
1539
1540     while (read_next_line( &info ) == 1)
1541     {
1542         p = info.buffer;
1543         while (*p && isspace(*p)) p++;
1544         switch(*p)
1545         {
1546         case '[':   /* new key */
1547             if (subkey) release_object( subkey );
1548             if (prefix_len == -1) prefix_len = get_prefix_len( key, p + 1, &info );
1549             if (!(subkey = load_key( key, p + 1, prefix_len, &info )))
1550                 file_read_error( "Error creating key", &info );
1551             break;
1552         case '@':   /* default value */
1553         case '\"':  /* value */
1554             if (subkey) load_value( subkey, p, &info );
1555             else file_read_error( "Value without key", &info );
1556             break;
1557         case '#':   /* option */
1558             if (subkey) load_key_option( subkey, p, &info );
1559             else if (!load_global_option( p, &info )) goto done;
1560             break;
1561         case ';':   /* comment */
1562         case 0:     /* empty line */
1563             break;
1564         default:
1565             file_read_error( "Unrecognized input", &info );
1566             break;
1567         }
1568     }
1569
1570  done:
1571     if (subkey) release_object( subkey );
1572     free( info.buffer );
1573     free( info.tmp );
1574 }
1575
1576 /* load a part of the registry from a file */
1577 static void load_registry( struct key *key, obj_handle_t handle )
1578 {
1579     struct file *file;
1580     int fd;
1581
1582     if (!(file = get_file_obj( current->process, handle, FILE_READ_DATA ))) return;
1583     fd = dup( get_file_unix_fd( file ) );
1584     release_object( file );
1585     if (fd != -1)
1586     {
1587         FILE *f = fdopen( fd, "r" );
1588         if (f)
1589         {
1590             load_keys( key, NULL, f, -1 );
1591             fclose( f );
1592         }
1593         else file_set_error();
1594     }
1595 }
1596
1597 /* load one of the initial registry files */
1598 static int load_init_registry_from_file( const char *filename, struct key *key )
1599 {
1600     FILE *f;
1601
1602     if ((f = fopen( filename, "r" )))
1603     {
1604         load_keys( key, filename, f, 0 );
1605         fclose( f );
1606         if (get_error() == STATUS_NOT_REGISTRY_FILE)
1607         {
1608             fprintf( stderr, "%s is not a valid registry file\n", filename );
1609             return 1;
1610         }
1611     }
1612
1613     assert( save_branch_count < MAX_SAVE_BRANCH_INFO );
1614
1615     save_branch_info[save_branch_count].path = filename;
1616     save_branch_info[save_branch_count++].key = (struct key *)grab_object( key );
1617     make_object_static( &key->obj );
1618     return (f != NULL);
1619 }
1620
1621 static WCHAR *format_user_registry_path( const SID *sid, struct unicode_str *path )
1622 {
1623     static const WCHAR prefixW[] = {'U','s','e','r','\\','S',0};
1624     static const WCHAR formatW[] = {'-','%','u',0};
1625     WCHAR buffer[7 + 10 + 10 + 10 * SID_MAX_SUB_AUTHORITIES];
1626     WCHAR *p = buffer;
1627     unsigned int i;
1628
1629     strcpyW( p, prefixW );
1630     p += strlenW( prefixW );
1631     p += sprintfW( p, formatW, sid->Revision );
1632     p += sprintfW( p, formatW, MAKELONG( MAKEWORD( sid->IdentifierAuthority.Value[5],
1633                                                    sid->IdentifierAuthority.Value[4] ),
1634                                          MAKEWORD( sid->IdentifierAuthority.Value[3],
1635                                                    sid->IdentifierAuthority.Value[2] )));
1636     for (i = 0; i < sid->SubAuthorityCount; i++)
1637         p += sprintfW( p, formatW, sid->SubAuthority[i] );
1638
1639     path->len = (p - buffer) * sizeof(WCHAR);
1640     path->str = p = memdup( buffer, path->len );
1641     return p;
1642 }
1643
1644 /* registry initialisation */
1645 void init_registry(void)
1646 {
1647     static const WCHAR HKLM[] = { 'M','a','c','h','i','n','e' };
1648     static const WCHAR HKU_default[] = { 'U','s','e','r','\\','.','D','e','f','a','u','l','t' };
1649     static const WCHAR classes[] = {'S','o','f','t','w','a','r','e','\\',
1650                                     'C','l','a','s','s','e','s','\\',
1651                                     'W','o','w','6','4','3','2','N','o','d','e'};
1652     static const struct unicode_str root_name = { NULL, 0 };
1653     static const struct unicode_str HKLM_name = { HKLM, sizeof(HKLM) };
1654     static const struct unicode_str HKU_name = { HKU_default, sizeof(HKU_default) };
1655     static const struct unicode_str classes_name = { classes, sizeof(classes) };
1656
1657     WCHAR *current_user_path;
1658     struct unicode_str current_user_str;
1659     struct key *key, *hklm, *hkcu;
1660
1661     /* switch to the config dir */
1662
1663     if (fchdir( config_dir_fd ) == -1) fatal_perror( "chdir to config dir" );
1664
1665     /* create the root key */
1666     root_key = alloc_key( &root_name, current_time );
1667     assert( root_key );
1668     make_object_static( &root_key->obj );
1669
1670     /* load system.reg into Registry\Machine */
1671
1672     if (!(hklm = create_key_recursive( root_key, &HKLM_name, current_time )))
1673         fatal_error( "could not create Machine registry key\n" );
1674
1675     if (!load_init_registry_from_file( "system.reg", hklm ))
1676         prefix_type = sizeof(void *) > sizeof(int) ? PREFIX_64BIT : PREFIX_32BIT;
1677     else if (prefix_type == PREFIX_UNKNOWN)
1678         prefix_type = PREFIX_32BIT;
1679
1680     /* load userdef.reg into Registry\User\.Default */
1681
1682     if (!(key = create_key_recursive( root_key, &HKU_name, current_time )))
1683         fatal_error( "could not create User\\.Default registry key\n" );
1684
1685     load_init_registry_from_file( "userdef.reg", key );
1686     release_object( key );
1687
1688     /* load user.reg into HKEY_CURRENT_USER */
1689
1690     /* FIXME: match default user in token.c. should get from process token instead */
1691     current_user_path = format_user_registry_path( security_interactive_sid, &current_user_str );
1692     if (!current_user_path ||
1693         !(hkcu = create_key_recursive( root_key, &current_user_str, current_time )))
1694         fatal_error( "could not create HKEY_CURRENT_USER registry key\n" );
1695     free( current_user_path );
1696     load_init_registry_from_file( "user.reg", hkcu );
1697
1698     /* set the shared flag on Software\Classes\Wow6432Node */
1699     if (prefix_type == PREFIX_64BIT)
1700     {
1701         if ((key = create_key_recursive( hklm, &classes_name, current_time )))
1702         {
1703             key->flags |= KEY_WOWSHARE;
1704             release_object( key );
1705         }
1706         /* FIXME: handle HKCU too */
1707     }
1708
1709     release_object( hklm );
1710     release_object( hkcu );
1711
1712     /* start the periodic save timer */
1713     set_periodic_save_timer();
1714
1715     /* go back to the server dir */
1716     if (fchdir( server_dir_fd ) == -1) fatal_perror( "chdir to server dir" );
1717 }
1718
1719 /* save a registry branch to a file */
1720 static void save_all_subkeys( struct key *key, FILE *f )
1721 {
1722     fprintf( f, "WINE REGISTRY Version 2\n" );
1723     fprintf( f, ";; All keys relative to " );
1724     dump_path( key, NULL, f );
1725     fprintf( f, "\n" );
1726     switch (prefix_type)
1727     {
1728     case PREFIX_32BIT:
1729         fprintf( f, "\n#arch=win32\n" );
1730         break;
1731     case PREFIX_64BIT:
1732         fprintf( f, "\n#arch=win64\n" );
1733         break;
1734     default:
1735         break;
1736     }
1737     save_subkeys( key, key, f );
1738 }
1739
1740 /* save a registry branch to a file handle */
1741 static void save_registry( struct key *key, obj_handle_t handle )
1742 {
1743     struct file *file;
1744     int fd;
1745
1746     if (!(file = get_file_obj( current->process, handle, FILE_WRITE_DATA ))) return;
1747     fd = dup( get_file_unix_fd( file ) );
1748     release_object( file );
1749     if (fd != -1)
1750     {
1751         FILE *f = fdopen( fd, "w" );
1752         if (f)
1753         {
1754             save_all_subkeys( key, f );
1755             if (fclose( f )) file_set_error();
1756         }
1757         else
1758         {
1759             file_set_error();
1760             close( fd );
1761         }
1762     }
1763 }
1764
1765 /* save a registry branch to a file */
1766 static int save_branch( struct key *key, const char *path )
1767 {
1768     struct stat st;
1769     char *p, *tmp = NULL;
1770     int fd, count = 0, ret = 0;
1771     FILE *f;
1772
1773     if (!(key->flags & KEY_DIRTY))
1774     {
1775         if (debug_level > 1) dump_operation( key, NULL, "Not saving clean" );
1776         return 1;
1777     }
1778
1779     /* test the file type */
1780
1781     if ((fd = open( path, O_WRONLY )) != -1)
1782     {
1783         /* if file is not a regular file or has multiple links or is accessed
1784          * via symbolic links, write directly into it; otherwise use a temp file */
1785         if (!lstat( path, &st ) && (!S_ISREG(st.st_mode) || st.st_nlink > 1))
1786         {
1787             ftruncate( fd, 0 );
1788             goto save;
1789         }
1790         close( fd );
1791     }
1792
1793     /* create a temp file in the same directory */
1794
1795     if (!(tmp = malloc( strlen(path) + 20 ))) goto done;
1796     strcpy( tmp, path );
1797     if ((p = strrchr( tmp, '/' ))) p++;
1798     else p = tmp;
1799     for (;;)
1800     {
1801         sprintf( p, "reg%lx%04x.tmp", (long) getpid(), count++ );
1802         if ((fd = open( tmp, O_CREAT | O_EXCL | O_WRONLY, 0666 )) != -1) break;
1803         if (errno != EEXIST) goto done;
1804         close( fd );
1805     }
1806
1807     /* now save to it */
1808
1809  save:
1810     if (!(f = fdopen( fd, "w" )))
1811     {
1812         if (tmp) unlink( tmp );
1813         close( fd );
1814         goto done;
1815     }
1816
1817     if (debug_level > 1)
1818     {
1819         fprintf( stderr, "%s: ", path );
1820         dump_operation( key, NULL, "saving" );
1821     }
1822
1823     save_all_subkeys( key, f );
1824     ret = !fclose(f);
1825
1826     if (tmp)
1827     {
1828         /* if successfully written, rename to final name */
1829         if (ret) ret = !rename( tmp, path );
1830         if (!ret) unlink( tmp );
1831     }
1832
1833 done:
1834     free( tmp );
1835     if (ret) make_clean( key );
1836     return ret;
1837 }
1838
1839 /* periodic saving of the registry */
1840 static void periodic_save( void *arg )
1841 {
1842     int i;
1843
1844     if (fchdir( config_dir_fd ) == -1) return;
1845     save_timeout_user = NULL;
1846     for (i = 0; i < save_branch_count; i++)
1847         save_branch( save_branch_info[i].key, save_branch_info[i].path );
1848     if (fchdir( server_dir_fd ) == -1) fatal_perror( "chdir to server dir" );
1849     set_periodic_save_timer();
1850 }
1851
1852 /* start the periodic save timer */
1853 static void set_periodic_save_timer(void)
1854 {
1855     if (save_timeout_user) remove_timeout_user( save_timeout_user );
1856     save_timeout_user = add_timeout_user( save_period, periodic_save, NULL );
1857 }
1858
1859 /* save the modified registry branches to disk */
1860 void flush_registry(void)
1861 {
1862     int i;
1863
1864     if (fchdir( config_dir_fd ) == -1) return;
1865     for (i = 0; i < save_branch_count; i++)
1866     {
1867         if (!save_branch( save_branch_info[i].key, save_branch_info[i].path ))
1868         {
1869             fprintf( stderr, "wineserver: could not save registry branch to %s",
1870                      save_branch_info[i].path );
1871             perror( " " );
1872         }
1873     }
1874     if (fchdir( server_dir_fd ) == -1) fatal_perror( "chdir to server dir" );
1875 }
1876
1877 /* determine if the thread is wow64 (32-bit client running on 64-bit prefix) */
1878 static int is_wow64_thread( struct thread *thread )
1879 {
1880     return (prefix_type == PREFIX_64BIT && !(CPU_FLAG(thread->process->cpu) & CPU_64BIT_MASK));
1881 }
1882
1883
1884 /* create a registry key */
1885 DECL_HANDLER(create_key)
1886 {
1887     struct key *key = NULL, *parent;
1888     struct unicode_str name, class;
1889     unsigned int access = req->access;
1890
1891     if (!is_wow64_thread( current )) access = (access & ~KEY_WOW64_32KEY) | KEY_WOW64_64KEY;
1892
1893     reply->hkey = 0;
1894
1895     if (req->namelen > get_req_data_size())
1896     {
1897         set_error( STATUS_INVALID_PARAMETER );
1898         return;
1899     }
1900     class.str = (const WCHAR *)get_req_data() + req->namelen / sizeof(WCHAR);
1901     class.len = ((get_req_data_size() - req->namelen) / sizeof(WCHAR)) * sizeof(WCHAR);
1902     get_req_path( &name, !req->parent );
1903     if (name.str > class.str)
1904     {
1905         set_error( STATUS_INVALID_PARAMETER );
1906         return;
1907     }
1908     name.len = (class.str - name.str) * sizeof(WCHAR);
1909
1910     /* NOTE: no access rights are required from the parent handle to create a key */
1911     if ((parent = get_parent_hkey_obj( req->parent )))
1912     {
1913         if ((key = create_key( parent, &name, &class, req->options, access,
1914                                req->attributes, &reply->created )))
1915         {
1916             reply->hkey = alloc_handle( current->process, key, access, req->attributes );
1917             release_object( key );
1918         }
1919         release_object( parent );
1920     }
1921 }
1922
1923 /* open a registry key */
1924 DECL_HANDLER(open_key)
1925 {
1926     struct key *key, *parent;
1927     struct unicode_str name;
1928     unsigned int access = req->access;
1929
1930     if (!is_wow64_thread( current )) access = (access & ~KEY_WOW64_32KEY) | KEY_WOW64_64KEY;
1931
1932     reply->hkey = 0;
1933     /* NOTE: no access rights are required to open the parent key, only the child key */
1934     if ((parent = get_parent_hkey_obj( req->parent )))
1935     {
1936         get_req_path( &name, !req->parent );
1937         if ((key = open_key( parent, &name, access, req->attributes )))
1938         {
1939             reply->hkey = alloc_handle( current->process, key, access, req->attributes );
1940             release_object( key );
1941         }
1942         release_object( parent );
1943     }
1944 }
1945
1946 /* delete a registry key */
1947 DECL_HANDLER(delete_key)
1948 {
1949     struct key *key;
1950
1951     if ((key = get_hkey_obj( req->hkey, DELETE )))
1952     {
1953         delete_key( key, 0);
1954         release_object( key );
1955     }
1956 }
1957
1958 /* flush a registry key */
1959 DECL_HANDLER(flush_key)
1960 {
1961     struct key *key = get_hkey_obj( req->hkey, 0 );
1962     if (key)
1963     {
1964         /* we don't need to do anything here with the current implementation */
1965         release_object( key );
1966     }
1967 }
1968
1969 /* enumerate registry subkeys */
1970 DECL_HANDLER(enum_key)
1971 {
1972     struct key *key;
1973
1974     if ((key = get_hkey_obj( req->hkey,
1975                              req->index == -1 ? KEY_QUERY_VALUE : KEY_ENUMERATE_SUB_KEYS )))
1976     {
1977         enum_key( key, req->index, req->info_class, reply );
1978         release_object( key );
1979     }
1980 }
1981
1982 /* set a value of a registry key */
1983 DECL_HANDLER(set_key_value)
1984 {
1985     struct key *key;
1986     struct unicode_str name;
1987
1988     if (req->namelen > get_req_data_size())
1989     {
1990         set_error( STATUS_INVALID_PARAMETER );
1991         return;
1992     }
1993     name.str = get_req_data();
1994     name.len = (req->namelen / sizeof(WCHAR)) * sizeof(WCHAR);
1995
1996     if ((key = get_hkey_obj( req->hkey, KEY_SET_VALUE )))
1997     {
1998         data_size_t datalen = get_req_data_size() - req->namelen;
1999         const char *data = (const char *)get_req_data() + req->namelen;
2000
2001         set_value( key, &name, req->type, data, datalen );
2002         release_object( key );
2003     }
2004 }
2005
2006 /* retrieve the value of a registry key */
2007 DECL_HANDLER(get_key_value)
2008 {
2009     struct key *key;
2010     struct unicode_str name;
2011
2012     reply->total = 0;
2013     if ((key = get_hkey_obj( req->hkey, KEY_QUERY_VALUE )))
2014     {
2015         get_req_unicode_str( &name );
2016         get_value( key, &name, &reply->type, &reply->total );
2017         release_object( key );
2018     }
2019 }
2020
2021 /* enumerate the value of a registry key */
2022 DECL_HANDLER(enum_key_value)
2023 {
2024     struct key *key;
2025
2026     if ((key = get_hkey_obj( req->hkey, KEY_QUERY_VALUE )))
2027     {
2028         enum_value( key, req->index, req->info_class, reply );
2029         release_object( key );
2030     }
2031 }
2032
2033 /* delete a value of a registry key */
2034 DECL_HANDLER(delete_key_value)
2035 {
2036     struct key *key;
2037     struct unicode_str name;
2038
2039     if ((key = get_hkey_obj( req->hkey, KEY_SET_VALUE )))
2040     {
2041         get_req_unicode_str( &name );
2042         delete_value( key, &name );
2043         release_object( key );
2044     }
2045 }
2046
2047 /* load a registry branch from a file */
2048 DECL_HANDLER(load_registry)
2049 {
2050     struct key *key, *parent;
2051     struct token *token = thread_get_impersonation_token( current );
2052     struct unicode_str name;
2053
2054     const LUID_AND_ATTRIBUTES privs[] =
2055     {
2056         { SeBackupPrivilege,  0 },
2057         { SeRestorePrivilege, 0 },
2058     };
2059
2060     if (!token || !token_check_privileges( token, TRUE, privs,
2061                                            sizeof(privs)/sizeof(privs[0]), NULL ))
2062     {
2063         set_error( STATUS_PRIVILEGE_NOT_HELD );
2064         return;
2065     }
2066
2067     if ((parent = get_parent_hkey_obj( req->hkey )))
2068     {
2069         int dummy;
2070         get_req_path( &name, !req->hkey );
2071         if ((key = create_key( parent, &name, NULL, 0, KEY_WOW64_64KEY, 0, &dummy )))
2072         {
2073             load_registry( key, req->file );
2074             release_object( key );
2075         }
2076         release_object( parent );
2077     }
2078 }
2079
2080 DECL_HANDLER(unload_registry)
2081 {
2082     struct key *key;
2083     struct token *token = thread_get_impersonation_token( current );
2084
2085     const LUID_AND_ATTRIBUTES privs[] =
2086     {
2087         { SeBackupPrivilege,  0 },
2088         { SeRestorePrivilege, 0 },
2089     };
2090
2091     if (!token || !token_check_privileges( token, TRUE, privs,
2092                                            sizeof(privs)/sizeof(privs[0]), NULL ))
2093     {
2094         set_error( STATUS_PRIVILEGE_NOT_HELD );
2095         return;
2096     }
2097
2098     if ((key = get_hkey_obj( req->hkey, 0 )))
2099     {
2100         delete_key( key, 1 );     /* FIXME */
2101         release_object( key );
2102     }
2103 }
2104
2105 /* save a registry branch to a file */
2106 DECL_HANDLER(save_registry)
2107 {
2108     struct key *key;
2109
2110     if (!thread_single_check_privilege( current, &SeBackupPrivilege ))
2111     {
2112         set_error( STATUS_PRIVILEGE_NOT_HELD );
2113         return;
2114     }
2115
2116     if ((key = get_hkey_obj( req->hkey, 0 )))
2117     {
2118         save_registry( key, req->file );
2119         release_object( key );
2120     }
2121 }
2122
2123 /* add a registry key change notification */
2124 DECL_HANDLER(set_registry_notification)
2125 {
2126     struct key *key;
2127     struct event *event;
2128     struct notify *notify;
2129
2130     key = get_hkey_obj( req->hkey, KEY_NOTIFY );
2131     if (key)
2132     {
2133         event = get_event_obj( current->process, req->event, SYNCHRONIZE );
2134         if (event)
2135         {
2136             notify = find_notify( key, current->process, req->hkey );
2137             if (notify)
2138             {
2139                 if (notify->event)
2140                     release_object( notify->event );
2141                 grab_object( event );
2142                 notify->event = event;
2143             }
2144             else
2145             {
2146                 notify = mem_alloc( sizeof(*notify) );
2147                 if (notify)
2148                 {
2149                     grab_object( event );
2150                     notify->event   = event;
2151                     notify->subtree = req->subtree;
2152                     notify->filter  = req->filter;
2153                     notify->hkey    = req->hkey;
2154                     notify->process = current->process;
2155                     list_add_head( &key->notify_list, &notify->entry );
2156                 }
2157             }
2158             release_object( event );
2159         }
2160         release_object( key );
2161     }
2162 }