dwrite: Implement GetWeight() for IDWriteFont.
[wine] / programs / regedit / regproc.c
1 /*
2  * Registry processing routines. Routines, common for registry
3  * processing frontends.
4  *
5  * Copyright 1999 Sylvain St-Germain
6  * Copyright 2002 Andriy Palamarchuk
7  * Copyright 2008 Alexander N. Sørnes <alex@thehandofagony.com>
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23
24 #include <limits.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <fcntl.h>
28 #include <io.h>
29 #include <windows.h>
30 #include <winnt.h>
31 #include <winreg.h>
32 #include <assert.h>
33 #include <wine/unicode.h>
34 #include "regproc.h"
35
36 #define REG_VAL_BUF_SIZE        4096
37
38 /* maximal number of characters in hexadecimal data line,
39  * including the indentation, but not including the '\' character
40  */
41 #define REG_FILE_HEX_LINE_LEN   (2 + 25 * 3)
42
43 extern const WCHAR* reg_class_namesW[];
44
45 static HKEY reg_class_keys[] = {
46             HKEY_LOCAL_MACHINE, HKEY_USERS, HKEY_CLASSES_ROOT,
47             HKEY_CURRENT_CONFIG, HKEY_CURRENT_USER, HKEY_DYN_DATA
48         };
49
50 #define REG_CLASS_NUMBER (sizeof(reg_class_keys) / sizeof(reg_class_keys[0]))
51
52 /* return values */
53 #define NOT_ENOUGH_MEMORY     1
54 #define IO_ERROR              2
55
56 /* processing macros */
57
58 /* common check of memory allocation results */
59 #define CHECK_ENOUGH_MEMORY(p) \
60 if (!(p)) \
61 { \
62     fprintf(stderr,"%s: file %s, line %d: Not enough memory\n", \
63             getAppName(), __FILE__, __LINE__); \
64     exit(NOT_ENOUGH_MEMORY); \
65 }
66
67 /******************************************************************************
68  * Allocates memory and converts input from multibyte to wide chars
69  * Returned string must be freed by the caller
70  */
71 WCHAR* GetWideString(const char* strA)
72 {
73     if(strA)
74     {
75         WCHAR* strW;
76         int len = MultiByteToWideChar(CP_ACP, 0, strA, -1, NULL, 0);
77
78         strW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
79         CHECK_ENOUGH_MEMORY(strW);
80         MultiByteToWideChar(CP_ACP, 0, strA, -1, strW, len);
81         return strW;
82     }
83     return NULL;
84 }
85
86 /******************************************************************************
87  * Allocates memory and converts input from multibyte to wide chars
88  * Returned string must be freed by the caller
89  */
90 static WCHAR* GetWideStringN(const char* strA, int chars, DWORD *len)
91 {
92     if(strA)
93     {
94         WCHAR* strW;
95         *len = MultiByteToWideChar(CP_ACP, 0, strA, chars, NULL, 0);
96
97         strW = HeapAlloc(GetProcessHeap(), 0, *len * sizeof(WCHAR));
98         CHECK_ENOUGH_MEMORY(strW);
99         MultiByteToWideChar(CP_ACP, 0, strA, chars, strW, *len);
100         return strW;
101     }
102     *len = 0;
103     return NULL;
104 }
105
106 /******************************************************************************
107  * Allocates memory and converts input from wide chars to multibyte
108  * Returned string must be freed by the caller
109  */
110 char* GetMultiByteString(const WCHAR* strW)
111 {
112     if(strW)
113     {
114         char* strA;
115         int len = WideCharToMultiByte(CP_ACP, 0, strW, -1, NULL, 0, NULL, NULL);
116
117         strA = HeapAlloc(GetProcessHeap(), 0, len);
118         CHECK_ENOUGH_MEMORY(strA);
119         WideCharToMultiByte(CP_ACP, 0, strW, -1, strA, len, NULL, NULL);
120         return strA;
121     }
122     return NULL;
123 }
124
125 /******************************************************************************
126  * Allocates memory and converts input from wide chars to multibyte
127  * Returned string must be freed by the caller
128  */
129 static char* GetMultiByteStringN(const WCHAR* strW, int chars, DWORD* len)
130 {
131     if(strW)
132     {
133         char* strA;
134         *len = WideCharToMultiByte(CP_ACP, 0, strW, chars, NULL, 0, NULL, NULL);
135
136         strA = HeapAlloc(GetProcessHeap(), 0, *len);
137         CHECK_ENOUGH_MEMORY(strA);
138         WideCharToMultiByte(CP_ACP, 0, strW, chars, strA, *len, NULL, NULL);
139         return strA;
140     }
141     *len = 0;
142     return NULL;
143 }
144
145 /******************************************************************************
146  * Converts a hex representation of a DWORD into a DWORD.
147  */
148 static BOOL convertHexToDWord(WCHAR* str, DWORD *dw)
149 {
150     char buf[9];
151     char dummy;
152
153     WideCharToMultiByte(CP_ACP, 0, str, -1, buf, 9, NULL, NULL);
154     if (lstrlenW(str) > 8 || sscanf(buf, "%x%c", dw, &dummy) != 1) {
155         fprintf(stderr,"%s: ERROR, invalid hex value\n", getAppName());
156         return FALSE;
157     }
158     return TRUE;
159 }
160
161 /******************************************************************************
162  * Converts a hex comma separated values list into a binary string.
163  */
164 static BYTE* convertHexCSVToHex(WCHAR *str, DWORD *size)
165 {
166     WCHAR *s;
167     BYTE *d, *data;
168
169     /* The worst case is 1 digit + 1 comma per byte */
170     *size=(lstrlenW(str)+1)/2;
171     data=HeapAlloc(GetProcessHeap(), 0, *size);
172     CHECK_ENOUGH_MEMORY(data);
173
174     s = str;
175     d = data;
176     *size=0;
177     while (*s != '\0') {
178         UINT wc;
179         WCHAR *end;
180
181         wc = strtoulW(s,&end,16);
182         if (end == s || wc > 0xff || (*end && *end != ',')) {
183             char* strA = GetMultiByteString(s);
184             fprintf(stderr,"%s: ERROR converting CSV hex stream. Invalid value at '%s'\n",
185                     getAppName(), strA);
186             HeapFree(GetProcessHeap(), 0, data);
187             HeapFree(GetProcessHeap(), 0, strA);
188             return NULL;
189         }
190         *d++ =(BYTE)wc;
191         (*size)++;
192         if (*end) end++;
193         s = end;
194     }
195
196     return data;
197 }
198
199 /******************************************************************************
200  * This function returns the HKEY associated with the data type encoded in the
201  * value.  It modifies the input parameter (key value) in order to skip this
202  * "now useless" data type information.
203  *
204  * Note: Updated based on the algorithm used in 'server/registry.c'
205  */
206 static DWORD getDataType(LPWSTR *lpValue, DWORD* parse_type)
207 {
208     struct data_type { const WCHAR *tag; int len; int type; int parse_type; };
209
210     static const WCHAR quote[] = {'"'};
211     static const WCHAR str[] = {'s','t','r',':','"'};
212     static const WCHAR str2[] = {'s','t','r','(','2',')',':','"'};
213     static const WCHAR hex[] = {'h','e','x',':'};
214     static const WCHAR dword[] = {'d','w','o','r','d',':'};
215     static const WCHAR hexp[] = {'h','e','x','('};
216
217     static const struct data_type data_types[] = {                   /* actual type */  /* type to assume for parsing */
218                 { quote,       1,   REG_SZ,              REG_SZ },
219                 { str,         5,   REG_SZ,              REG_SZ },
220                 { str2,        8,   REG_EXPAND_SZ,       REG_SZ },
221                 { hex,         4,   REG_BINARY,          REG_BINARY },
222                 { dword,       6,   REG_DWORD,           REG_DWORD },
223                 { hexp,        4,   -1,                  REG_BINARY },
224                 { NULL,        0,    0,                  0 }
225             };
226
227     const struct data_type *ptr;
228     int type;
229
230     for (ptr = data_types; ptr->tag; ptr++) {
231         if (strncmpW( ptr->tag, *lpValue, ptr->len ))
232             continue;
233
234         /* Found! */
235         *parse_type = ptr->parse_type;
236         type=ptr->type;
237         *lpValue+=ptr->len;
238         if (type == -1) {
239             WCHAR* end;
240
241             /* "hex(xx):" is special */
242             type = (int)strtoulW( *lpValue , &end, 16 );
243             if (**lpValue=='\0' || *end!=')' || *(end+1)!=':') {
244                 type=REG_NONE;
245             } else {
246                 *lpValue = end + 2;
247             }
248         }
249         return type;
250     }
251     *parse_type=REG_NONE;
252     return REG_NONE;
253 }
254
255 /******************************************************************************
256  * Replaces escape sequences with the characters.
257  */
258 static void REGPROC_unescape_string(WCHAR* str)
259 {
260     int str_idx = 0;            /* current character under analysis */
261     int val_idx = 0;            /* the last character of the unescaped string */
262     int len = lstrlenW(str);
263     for (str_idx = 0; str_idx < len; str_idx++, val_idx++) {
264         if (str[str_idx] == '\\') {
265             str_idx++;
266             switch (str[str_idx]) {
267             case 'n':
268                 str[val_idx] = '\n';
269                 break;
270             case '\\':
271             case '"':
272                 str[val_idx] = str[str_idx];
273                 break;
274             default:
275                 fprintf(stderr,"Warning! Unrecognized escape sequence: \\%c'\n",
276                         str[str_idx]);
277                 str[val_idx] = str[str_idx];
278                 break;
279             }
280         } else {
281             str[val_idx] = str[str_idx];
282         }
283     }
284     str[val_idx] = '\0';
285 }
286
287 static BOOL parseKeyName(LPWSTR lpKeyName, HKEY *hKey, LPWSTR *lpKeyPath)
288 {
289     WCHAR* lpSlash = NULL;
290     unsigned int i, len;
291
292     if (lpKeyName == NULL)
293         return FALSE;
294
295     for(i = 0; *(lpKeyName+i) != 0; i++)
296     {
297         if(*(lpKeyName+i) == '\\')
298         {
299             lpSlash = lpKeyName+i;
300             break;
301         }
302     }
303
304     if (lpSlash)
305     {
306         len = lpSlash-lpKeyName;
307     }
308     else
309     {
310         len = lstrlenW(lpKeyName);
311         lpSlash = lpKeyName+len;
312     }
313     *hKey = NULL;
314
315     for (i = 0; i < REG_CLASS_NUMBER; i++) {
316         if (CompareStringW(LOCALE_USER_DEFAULT, 0, lpKeyName, len, reg_class_namesW[i], len) == CSTR_EQUAL &&
317             len == lstrlenW(reg_class_namesW[i])) {
318             *hKey = reg_class_keys[i];
319             break;
320         }
321     }
322
323     if (*hKey == NULL)
324         return FALSE;
325
326
327     if (*lpSlash != '\0')
328         lpSlash++;
329     *lpKeyPath = lpSlash;
330     return TRUE;
331 }
332
333 /* Globals used by the setValue() & co */
334 static LPSTR currentKeyName;
335 static HKEY  currentKeyHandle = NULL;
336
337 /******************************************************************************
338  * Sets the value with name val_name to the data in val_data for the currently
339  * opened key.
340  *
341  * Parameters:
342  * val_name - name of the registry value
343  * val_data - registry value data
344  */
345 static LONG setValue(WCHAR* val_name, WCHAR* val_data, BOOL is_unicode)
346 {
347     LONG res;
348     DWORD  dwDataType, dwParseType;
349     LPBYTE lpbData;
350     DWORD  dwData, dwLen;
351     WCHAR del[] = {'-',0};
352
353     if ( (val_name == NULL) || (val_data == NULL) )
354         return ERROR_INVALID_PARAMETER;
355
356     if (lstrcmpW(val_data, del) == 0)
357     {
358         res=RegDeleteValueW(currentKeyHandle,val_name);
359         return (res == ERROR_FILE_NOT_FOUND ? ERROR_SUCCESS : res);
360     }
361
362     /* Get the data type stored into the value field */
363     dwDataType = getDataType(&val_data, &dwParseType);
364
365     if (dwParseType == REG_SZ)          /* no conversion for string */
366     {
367         REGPROC_unescape_string(val_data);
368         /* Compute dwLen after REGPROC_unescape_string because it may
369          * have changed the string length and we don't want to store
370          * the extra garbage in the registry.
371          */
372         dwLen = lstrlenW(val_data);
373         if(val_data[dwLen-1] != '"')
374             return ERROR_INVALID_DATA;
375         if (dwLen>0 && val_data[dwLen-1]=='"')
376         {
377             dwLen--;
378             val_data[dwLen]='\0';
379         }
380         lpbData = (BYTE*) val_data;
381         dwLen++;  /* include terminating null */
382         dwLen = dwLen * sizeof(WCHAR); /* size is in bytes */
383     }
384     else if (dwParseType == REG_DWORD)  /* Convert the dword types */
385     {
386         if (!convertHexToDWord(val_data, &dwData))
387             return ERROR_INVALID_DATA;
388         lpbData = (BYTE*)&dwData;
389         dwLen = sizeof(dwData);
390     }
391     else if (dwParseType == REG_BINARY) /* Convert the binary data */
392     {
393         lpbData = convertHexCSVToHex(val_data, &dwLen);
394         if (!lpbData)
395             return ERROR_INVALID_DATA;
396
397         if((dwDataType == REG_MULTI_SZ || dwDataType == REG_EXPAND_SZ) && !is_unicode)
398         {
399             LPBYTE tmp = lpbData;
400             lpbData = (LPBYTE)GetWideStringN((char*)lpbData, dwLen, &dwLen);
401             dwLen *= sizeof(WCHAR);
402             HeapFree(GetProcessHeap(), 0, tmp);
403         }
404     }
405     else                                /* unknown format */
406     {
407         fprintf(stderr,"%s: ERROR, unknown data format\n", getAppName());
408         return ERROR_INVALID_DATA;
409     }
410
411     res = RegSetValueExW(
412                currentKeyHandle,
413                val_name,
414                0,                  /* Reserved */
415                dwDataType,
416                lpbData,
417                dwLen);
418     if (dwParseType == REG_BINARY)
419         HeapFree(GetProcessHeap(), 0, lpbData);
420     return res;
421 }
422
423 /******************************************************************************
424  * A helper function for processRegEntry() that opens the current key.
425  * That key must be closed by calling closeKey().
426  */
427 static LONG openKeyW(WCHAR* stdInput)
428 {
429     HKEY keyClass;
430     WCHAR* keyPath;
431     DWORD dwDisp;
432     LONG res;
433
434     /* Sanity checks */
435     if (stdInput == NULL)
436         return ERROR_INVALID_PARAMETER;
437
438     /* Get the registry class */
439     if (!parseKeyName(stdInput, &keyClass, &keyPath))
440         return ERROR_INVALID_PARAMETER;
441
442     res = RegCreateKeyExW(
443                keyClass,                 /* Class     */
444                keyPath,                  /* Sub Key   */
445                0,                        /* MUST BE 0 */
446                NULL,                     /* object type */
447                REG_OPTION_NON_VOLATILE,  /* option, REG_OPTION_NON_VOLATILE ... */
448                KEY_ALL_ACCESS,           /* access mask, KEY_ALL_ACCESS */
449                NULL,                     /* security attribute */
450                &currentKeyHandle,        /* result */
451                &dwDisp);                 /* disposition, REG_CREATED_NEW_KEY or
452                                                         REG_OPENED_EXISTING_KEY */
453
454     if (res == ERROR_SUCCESS)
455         currentKeyName = GetMultiByteString(stdInput);
456     else
457         currentKeyHandle = NULL;
458
459     return res;
460
461 }
462
463 /******************************************************************************
464  * Close the currently opened key.
465  */
466 static void closeKey(void)
467 {
468     if (currentKeyHandle)
469     {
470         HeapFree(GetProcessHeap(), 0, currentKeyName);
471         RegCloseKey(currentKeyHandle);
472         currentKeyHandle = NULL;
473     }
474 }
475
476 /******************************************************************************
477  * This function is a wrapper for the setValue function.  It prepares the
478  * land and cleans the area once completed.
479  * Note: this function modifies the line parameter.
480  *
481  * line - registry file unwrapped line. Should have the registry value name and
482  *      complete registry value data.
483  */
484 static void processSetValue(WCHAR* line, BOOL is_unicode)
485 {
486     WCHAR* val_name;                   /* registry value name   */
487     WCHAR* val_data;                   /* registry value data   */
488     int line_idx = 0;                 /* current character under analysis */
489     LONG res;
490
491     /* get value name */
492     while ( isspaceW(line[line_idx]) ) line_idx++;
493     if (line[line_idx] == '@' && line[line_idx + 1] == '=') {
494         line[line_idx] = '\0';
495         val_name = line;
496         line_idx++;
497     } else if (line[line_idx] == '\"') {
498         line_idx++;
499         val_name = line + line_idx;
500         while (line[line_idx]) {
501             if (line[line_idx] == '\\')   /* skip escaped character */
502             {
503                 line_idx += 2;
504             } else {
505                 if (line[line_idx] == '\"') {
506                     line[line_idx] = '\0';
507                     line_idx++;
508                     break;
509                 } else {
510                     line_idx++;
511                 }
512             }
513         }
514         while ( isspaceW(line[line_idx]) ) line_idx++;
515         if (!line[line_idx]) {
516             fprintf(stderr, "%s: warning: unexpected EOL\n", getAppName());
517             return;
518         }
519         if (line[line_idx] != '=') {
520             char* lineA;
521             line[line_idx] = '\"';
522             lineA = GetMultiByteString(line);
523             fprintf(stderr,"%s: warning: unrecognized line: '%s'\n", getAppName(), lineA);
524             HeapFree(GetProcessHeap(), 0, lineA);
525             return;
526         }
527
528     } else {
529         char* lineA = GetMultiByteString(line);
530         fprintf(stderr,"%s: warning: unrecognized line: '%s'\n", getAppName(), lineA);
531         HeapFree(GetProcessHeap(), 0, lineA);
532         return;
533     }
534     line_idx++;                   /* skip the '=' character */
535
536     while ( isspaceW(line[line_idx]) ) line_idx++;
537     val_data = line + line_idx;
538     /* trim trailing blanks */
539     line_idx = strlenW(val_data);
540     while (line_idx > 0 && isspaceW(val_data[line_idx-1])) line_idx--;
541     val_data[line_idx] = '\0';
542
543     REGPROC_unescape_string(val_name);
544     res = setValue(val_name, val_data, is_unicode);
545     if ( res != ERROR_SUCCESS )
546     {
547         char* val_nameA = GetMultiByteString(val_name);
548         char* val_dataA = GetMultiByteString(val_data);
549         fprintf(stderr,"%s: ERROR Key %s not created. Value: %s, Data: %s\n",
550                 getAppName(),
551                 currentKeyName,
552                 val_nameA,
553                 val_dataA);
554         HeapFree(GetProcessHeap(), 0, val_nameA);
555         HeapFree(GetProcessHeap(), 0, val_dataA);
556     }
557 }
558
559 /******************************************************************************
560  * This function receives the currently read entry and performs the
561  * corresponding action.
562  * isUnicode affects parsing of REG_MULTI_SZ values
563  */
564 static void processRegEntry(WCHAR* stdInput, BOOL isUnicode)
565 {
566     /*
567      * We encountered the end of the file, make sure we
568      * close the opened key and exit
569      */
570     if (stdInput == NULL) {
571         closeKey();
572         return;
573     }
574
575     if      ( stdInput[0] == '[')      /* We are reading a new key */
576     {
577         WCHAR* keyEnd;
578         closeKey();                    /* Close the previous key */
579
580         /* Get rid of the square brackets */
581         stdInput++;
582         keyEnd = strrchrW(stdInput, ']');
583         if (keyEnd)
584             *keyEnd='\0';
585
586         /* delete the key if we encounter '-' at the start of reg key */
587         if ( stdInput[0] == '-')
588         {
589             delete_registry_key(stdInput + 1);
590         } else if ( openKeyW(stdInput) != ERROR_SUCCESS )
591         {
592             char* stdInputA = GetMultiByteString(stdInput);
593             fprintf(stderr,"%s: setValue failed to open key %s\n",
594                     getAppName(), stdInputA);
595             HeapFree(GetProcessHeap(), 0, stdInputA);
596         }
597     } else if( currentKeyHandle &&
598                (( stdInput[0] == '@') || /* reading a default @=data pair */
599                 ( stdInput[0] == '\"'))) /* reading a new value=data pair */
600     {
601         processSetValue(stdInput, isUnicode);
602     } else
603     {
604         /* Since we are assuming that the file format is valid we must be
605          * reading a blank line which indicates the end of this key processing
606          */
607         closeKey();
608     }
609 }
610
611 /******************************************************************************
612  * Processes a registry file.
613  * Correctly processes comments (in # and ; form), line continuation.
614  *
615  * Parameters:
616  *   in - input stream to read from
617  *   first_chars - beginning of stream, read due to Unicode check
618  */
619 static void processRegLinesA(FILE *in, char* first_chars)
620 {
621     LPSTR line           = NULL;  /* line read from input stream */
622     ULONG lineSize       = REG_VAL_BUF_SIZE;
623
624     line = HeapAlloc(GetProcessHeap(), 0, lineSize);
625     CHECK_ENOUGH_MEMORY(line);
626     memcpy(line, first_chars, 2);
627
628     while (!feof(in)) {
629         LPSTR s; /* The pointer into line for where the current fgets should read */
630         WCHAR* lineW;
631         s = line;
632
633         if(first_chars)
634         {
635             s += 2;
636             first_chars = NULL;
637         }
638
639         for (;;) {
640             size_t size_remaining;
641             int size_to_get, i;
642             char *s_eol; /* various local uses */
643
644             /* Do we need to expand the buffer ? */
645             assert (s >= line && s <= line + lineSize);
646             size_remaining = lineSize - (s-line);
647             if (size_remaining < 2) /* room for 1 character and the \0 */
648             {
649                 char *new_buffer;
650                 size_t new_size = lineSize + REG_VAL_BUF_SIZE;
651                 if (new_size > lineSize) /* no arithmetic overflow */
652                     new_buffer = HeapReAlloc (GetProcessHeap(), 0, line, new_size);
653                 else
654                     new_buffer = NULL;
655                 CHECK_ENOUGH_MEMORY(new_buffer);
656                 line = new_buffer;
657                 s = line + lineSize - size_remaining;
658                 lineSize = new_size;
659                 size_remaining = lineSize - (s-line);
660             }
661
662             /* Get as much as possible into the buffer, terminated either by
663              * eof, error, eol or getting the maximum amount.  Abort on error.
664              */
665             size_to_get = (size_remaining > INT_MAX ? INT_MAX : size_remaining);
666
667             /* get a single line. note that `i' must be one past the last
668              * meaningful character in `s' when this loop exits */
669             for(i = 0; i < size_to_get-1; ++i){
670                 int xchar;
671
672                 xchar = fgetc(in);
673                 s[i] = xchar;
674                 if(xchar == EOF){
675                     if(ferror(in)){
676                         perror("While reading input");
677                         exit(IO_ERROR);
678                     }else
679                         assert(feof(in));
680                     break;
681                 }
682                 if(s[i] == '\r'){
683                     /* read the next character iff it's \n */
684                     if(i+2 >= size_to_get){
685                         /* buffer too short, so put back the EOL char to
686                          * read next cycle */
687                         ungetc('\r', in);
688                         break;
689                     }
690                     s[i+1] = fgetc(in);
691                     if(s[i+1] != '\n'){
692                         ungetc(s[i+1], in);
693                         i = i+1;
694                     }else
695                         i = i+2;
696                     break;
697                 }
698                 if(s[i] == '\n'){
699                     i = i+1;
700                     break;
701                 }
702             }
703             s[i] = '\0';
704
705             /* If we didn't read the eol nor the eof go around for the rest */
706             s_eol = strpbrk (s, "\r\n");
707             if (!feof (in) && !s_eol) {
708                 s = strchr (s, '\0');
709                 continue;
710             }
711
712             /* If it is a comment line then discard it and go around again */
713             if (line [0] == '#' || line [0] == ';') {
714                 s = line;
715                 continue;
716             }
717
718             /* Remove any line feed.  Leave s_eol on the first \0 */
719             if (s_eol) {
720                if (*s_eol == '\r' && *(s_eol+1) == '\n')
721                    *(s_eol+1) = '\0';
722                *s_eol = '\0';
723             } else
724                 s_eol = strchr (s, '\0');
725
726             /* If there is a concatenating \\ then go around again */
727             if (s_eol > line && *(s_eol-1) == '\\') {
728                 int c;
729                 s = s_eol-1;
730
731                 do
732                 {
733                     c = fgetc(in);
734                 } while(c == ' ' || c == '\t');
735
736                 if(c == EOF)
737                 {
738                     fprintf(stderr,"%s: ERROR - invalid continuation.\n",
739                             getAppName());
740                 }
741                 else
742                 {
743                     *s = c;
744                     s++;
745                 }
746                 continue;
747             }
748
749             lineW = GetWideString(line);
750
751             break; /* That is the full virtual line */
752         }
753
754         processRegEntry(lineW, FALSE);
755         HeapFree(GetProcessHeap(), 0, lineW);
756     }
757     processRegEntry(NULL, FALSE);
758
759     HeapFree(GetProcessHeap(), 0, line);
760 }
761
762 static void processRegLinesW(FILE *in)
763 {
764     WCHAR* buf           = NULL;  /* line read from input stream */
765     ULONG lineSize       = REG_VAL_BUF_SIZE;
766     size_t CharsInBuf = -1;
767
768     WCHAR* s; /* The pointer into buf for where the current fgets should read */
769     WCHAR* line; /* The start of the current line */
770
771     buf = HeapAlloc(GetProcessHeap(), 0, lineSize * sizeof(WCHAR));
772     CHECK_ENOUGH_MEMORY(buf);
773
774     s = buf;
775     line = buf;
776
777     while(!feof(in)) {
778         size_t size_remaining;
779         int size_to_get;
780         WCHAR *s_eol = NULL; /* various local uses */
781
782         /* Do we need to expand the buffer ? */
783         assert (s >= buf && s <= buf + lineSize);
784         size_remaining = lineSize - (s-buf);
785         if (size_remaining < 2) /* room for 1 character and the \0 */
786         {
787             WCHAR *new_buffer;
788             size_t new_size = lineSize + (REG_VAL_BUF_SIZE / sizeof(WCHAR));
789             if (new_size > lineSize) /* no arithmetic overflow */
790                 new_buffer = HeapReAlloc (GetProcessHeap(), 0, buf, new_size * sizeof(WCHAR));
791             else
792                 new_buffer = NULL;
793             CHECK_ENOUGH_MEMORY(new_buffer);
794             buf = new_buffer;
795             line = buf;
796             s = buf + lineSize - size_remaining;
797             lineSize = new_size;
798             size_remaining = lineSize - (s-buf);
799         }
800
801         /* Get as much as possible into the buffer, terminated either by
802         * eof, error or getting the maximum amount.  Abort on error.
803         */
804         size_to_get = (size_remaining > INT_MAX ? INT_MAX : size_remaining);
805
806         CharsInBuf = fread(s, sizeof(WCHAR), size_to_get - 1, in);
807         s[CharsInBuf] = 0;
808
809         if (CharsInBuf == 0) {
810             if (ferror(in)) {
811                 perror ("While reading input");
812                 exit (IO_ERROR);
813             } else {
814                 assert (feof(in));
815                 *s = '\0';
816                 /* It is not clear to me from the definition that the
817                 * contents of the buffer are well defined on detecting
818                 * an eof without managing to read anything.
819                 */
820             }
821         }
822
823         /* If we didn't read the eol nor the eof go around for the rest */
824         while(1)
825         {
826             const WCHAR line_endings[] = {'\r','\n',0};
827             s_eol = strpbrkW(line, line_endings);
828
829             if(!s_eol) {
830                 /* Move the stub of the line to the start of the buffer so
831                  * we get the maximum space to read into, and so we don't
832                  * have to recalculate 'line' if the buffer expands */
833                 MoveMemory(buf, line, (strlenW(line)+1) * sizeof(WCHAR));
834                 line = buf;
835                 s = strchrW(line, '\0');
836                 break;
837             }
838
839             /* If it is a comment line then discard it and go around again */
840             if (*line == '#' || *line == ';') {
841                 if (*s_eol == '\r' && *(s_eol+1) == '\n')
842                     line = s_eol + 2;
843                 else
844                     line = s_eol + 1;
845                 continue;
846             }
847
848             /* If there is a concatenating \\ then go around again */
849             if (*(s_eol-1) == '\\') {
850                 WCHAR* NextLine = s_eol + 1;
851
852                 if(*s_eol == '\r' && *(s_eol+1) == '\n')
853                     NextLine++;
854
855                 while(*(NextLine+1) == ' ' || *(NextLine+1) == '\t')
856                     NextLine++;
857
858                 MoveMemory(s_eol - 1, NextLine, (CharsInBuf - (NextLine - s) + 1)*sizeof(WCHAR));
859                 CharsInBuf -= NextLine - s_eol + 1;
860                 s_eol = 0;
861                 continue;
862             }
863
864             /* Remove any line feed.  Leave s_eol on the last \0 */
865             if (*s_eol == '\r' && *(s_eol + 1) == '\n')
866                 *s_eol++ = '\0';
867             *s_eol = '\0';
868
869             processRegEntry(line, TRUE);
870             line = s_eol + 1;
871             s_eol = 0;
872             continue; /* That is the full virtual line */
873         }
874     }
875
876     processRegEntry(NULL, TRUE);
877
878     HeapFree(GetProcessHeap(), 0, buf);
879 }
880
881 /****************************************************************************
882  * REGPROC_print_error
883  *
884  * Print the message for GetLastError
885  */
886
887 static void REGPROC_print_error(void)
888 {
889     LPVOID lpMsgBuf;
890     DWORD error_code;
891     int status;
892
893     error_code = GetLastError ();
894     status = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
895                             NULL, error_code, 0, (LPSTR) &lpMsgBuf, 0, NULL);
896     if (!status) {
897         fprintf(stderr,"%s: Cannot display message for error %d, status %d\n",
898                 getAppName(), error_code, GetLastError());
899         exit(1);
900     }
901     puts(lpMsgBuf);
902     LocalFree(lpMsgBuf);
903     exit(1);
904 }
905
906 /******************************************************************************
907  * Checks whether the buffer has enough room for the string or required size.
908  * Resizes the buffer if necessary.
909  *
910  * Parameters:
911  * buffer - pointer to a buffer for string
912  * len - current length of the buffer in characters.
913  * required_len - length of the string to place to the buffer in characters.
914  *   The length does not include the terminating null character.
915  */
916 static void REGPROC_resize_char_buffer(WCHAR **buffer, DWORD *len, DWORD required_len)
917 {
918     required_len++;
919     if (required_len > *len) {
920         *len = required_len;
921         if (!*buffer)
922             *buffer = HeapAlloc(GetProcessHeap(), 0, *len * sizeof(**buffer));
923         else
924             *buffer = HeapReAlloc(GetProcessHeap(), 0, *buffer, *len * sizeof(**buffer));
925         CHECK_ENOUGH_MEMORY(*buffer);
926     }
927 }
928
929 /******************************************************************************
930  * Same as REGPROC_resize_char_buffer() but on a regular buffer.
931  *
932  * Parameters:
933  * buffer - pointer to a buffer
934  * len - current size of the buffer in bytes
935  * required_size - size of the data to place in the buffer in bytes
936  */
937 static void REGPROC_resize_binary_buffer(BYTE **buffer, DWORD *size, DWORD required_size)
938 {
939     if (required_size > *size) {
940         *size = required_size;
941         if (!*buffer)
942             *buffer = HeapAlloc(GetProcessHeap(), 0, *size);
943         else
944             *buffer = HeapReAlloc(GetProcessHeap(), 0, *buffer, *size);
945         CHECK_ENOUGH_MEMORY(*buffer);
946     }
947 }
948
949 /******************************************************************************
950  * Prints string str to file
951  */
952 static void REGPROC_export_string(WCHAR **line_buf, DWORD *line_buf_size, DWORD *line_len, WCHAR *str, DWORD str_len)
953 {
954     DWORD i, pos;
955     DWORD extra = 0;
956
957     REGPROC_resize_char_buffer(line_buf, line_buf_size, *line_len + str_len + 10);
958
959     /* escaping characters */
960     pos = *line_len;
961     for (i = 0; i < str_len; i++) {
962         WCHAR c = str[i];
963         switch (c) {
964         case '\n':
965             extra++;
966             REGPROC_resize_char_buffer(line_buf, line_buf_size, *line_len + str_len + extra);
967             (*line_buf)[pos++] = '\\';
968             (*line_buf)[pos++] = 'n';
969             break;
970
971         case '\\':
972         case '"':
973             extra++;
974             REGPROC_resize_char_buffer(line_buf, line_buf_size, *line_len + str_len + extra);
975             (*line_buf)[pos++] = '\\';
976             /* Fall through */
977
978         default:
979             (*line_buf)[pos++] = c;
980             break;
981         }
982     }
983     (*line_buf)[pos] = '\0';
984     *line_len = pos;
985 }
986
987 static void REGPROC_export_binary(WCHAR **line_buf, DWORD *line_buf_size, DWORD *line_len, DWORD type, BYTE *value, DWORD value_size, BOOL unicode)
988 {
989     DWORD hex_pos, data_pos;
990     const WCHAR *hex_prefix;
991     const WCHAR hex[] = {'h','e','x',':',0};
992     WCHAR hex_buf[17];
993     const WCHAR concat[] = {'\\','\r','\n',' ',' ',0};
994     DWORD concat_prefix, concat_len;
995     const WCHAR newline[] = {'\r','\n',0};
996     CHAR* value_multibyte = NULL;
997
998     if (type == REG_BINARY) {
999         hex_prefix = hex;
1000     } else {
1001         const WCHAR hex_format[] = {'h','e','x','(','%','x',')',':',0};
1002         hex_prefix = hex_buf;
1003         sprintfW(hex_buf, hex_format, type);
1004         if ((type == REG_SZ || type == REG_EXPAND_SZ || type == REG_MULTI_SZ) && !unicode)
1005         {
1006             value_multibyte = GetMultiByteStringN((WCHAR*)value, value_size / sizeof(WCHAR), &value_size);
1007             value = (BYTE*)value_multibyte;
1008         }
1009     }
1010
1011     concat_len = lstrlenW(concat);
1012     concat_prefix = 2;
1013
1014     hex_pos = *line_len;
1015     *line_len += lstrlenW(hex_prefix);
1016     data_pos = *line_len;
1017     *line_len += value_size * 3;
1018     /* - The 2 spaces that concat places at the start of the
1019      *   line effectively reduce the space available for data.
1020      * - If the value name and hex prefix are very long
1021      *   ( > REG_FILE_HEX_LINE_LEN) or *line_len divides
1022      *   without a remainder then we may overestimate
1023      *   the needed number of lines by one. But that's ok.
1024      * - The trailing '\r' takes the place of a comma so
1025      *   we only need to add 1 for the trailing '\n'
1026      */
1027     *line_len += *line_len / (REG_FILE_HEX_LINE_LEN - concat_prefix) * concat_len + 1;
1028     REGPROC_resize_char_buffer(line_buf, line_buf_size, *line_len);
1029     lstrcpyW(*line_buf + hex_pos, hex_prefix);
1030     if (value_size)
1031     {
1032         const WCHAR format[] = {'%','0','2','x',0};
1033         DWORD i, column;
1034
1035         column = data_pos; /* no line wrap yet */
1036         i = 0;
1037         while (1)
1038         {
1039             sprintfW(*line_buf + data_pos, format, (unsigned int)value[i]);
1040             data_pos += 2;
1041             if (++i == value_size)
1042                 break;
1043
1044             (*line_buf)[data_pos++] = ',';
1045             column += 3;
1046
1047             /* wrap the line */
1048             if (column >= REG_FILE_HEX_LINE_LEN) {
1049                 lstrcpyW(*line_buf + data_pos, concat);
1050                 data_pos += concat_len;
1051                 column = concat_prefix;
1052             }
1053         }
1054     }
1055     lstrcpyW(*line_buf + data_pos, newline);
1056     HeapFree(GetProcessHeap(), 0, value_multibyte);
1057 }
1058
1059 /******************************************************************************
1060  * Writes the given line to a file, in multi-byte or wide characters
1061  */
1062 static void REGPROC_write_line(FILE *file, const WCHAR* str, BOOL unicode)
1063 {
1064     if(unicode)
1065     {
1066         fwrite(str, sizeof(WCHAR), lstrlenW(str), file);
1067     } else
1068     {
1069         char* strA = GetMultiByteString(str);
1070         fputs(strA, file);
1071         HeapFree(GetProcessHeap(), 0, strA);
1072     }
1073 }
1074
1075 /******************************************************************************
1076  * Writes contents of the registry key to the specified file stream.
1077  *
1078  * Parameters:
1079  * file - writable file stream to export registry branch to.
1080  * key - registry branch to export.
1081  * reg_key_name_buf - name of the key with registry class.
1082  *      Is resized if necessary.
1083  * reg_key_name_size - length of the buffer for the registry class in characters.
1084  * val_name_buf - buffer for storing value name.
1085  *      Is resized if necessary.
1086  * val_name_size - length of the buffer for storing value names in characters.
1087  * val_buf - buffer for storing values while extracting.
1088  *      Is resized if necessary.
1089  * val_size - size of the buffer for storing values in bytes.
1090  */
1091 static void export_hkey(FILE *file, HKEY key,
1092                  WCHAR **reg_key_name_buf, DWORD *reg_key_name_size,
1093                  WCHAR **val_name_buf, DWORD *val_name_size,
1094                  BYTE **val_buf, DWORD *val_size,
1095                  WCHAR **line_buf, DWORD *line_buf_size,
1096                  BOOL unicode)
1097 {
1098     DWORD max_sub_key_len;
1099     DWORD max_val_name_len;
1100     DWORD max_val_size;
1101     DWORD curr_len;
1102     DWORD i;
1103     BOOL more_data;
1104     LONG ret;
1105     WCHAR key_format[] = {'\r','\n','[','%','s',']','\r','\n',0};
1106
1107     /* get size information and resize the buffers if necessary */
1108     if (RegQueryInfoKeyW(key, NULL, NULL, NULL, NULL,
1109                         &max_sub_key_len, NULL,
1110                         NULL, &max_val_name_len, &max_val_size, NULL, NULL
1111                        ) != ERROR_SUCCESS) {
1112         REGPROC_print_error();
1113     }
1114     curr_len = strlenW(*reg_key_name_buf);
1115     REGPROC_resize_char_buffer(reg_key_name_buf, reg_key_name_size,
1116                                max_sub_key_len + curr_len + 1);
1117     REGPROC_resize_char_buffer(val_name_buf, val_name_size,
1118                                max_val_name_len);
1119     REGPROC_resize_binary_buffer(val_buf, val_size, max_val_size);
1120     REGPROC_resize_char_buffer(line_buf, line_buf_size, lstrlenW(*reg_key_name_buf) + 4);
1121     /* output data for the current key */
1122     sprintfW(*line_buf, key_format, *reg_key_name_buf);
1123     REGPROC_write_line(file, *line_buf, unicode);
1124
1125     /* print all the values */
1126     i = 0;
1127     more_data = TRUE;
1128     while(more_data) {
1129         DWORD value_type;
1130         DWORD val_name_size1 = *val_name_size;
1131         DWORD val_size1 = *val_size;
1132         ret = RegEnumValueW(key, i, *val_name_buf, &val_name_size1, NULL,
1133                            &value_type, *val_buf, &val_size1);
1134         if (ret == ERROR_MORE_DATA) {
1135             /* Increase the size of the buffers and retry */
1136             REGPROC_resize_char_buffer(val_name_buf, val_name_size, val_name_size1);
1137             REGPROC_resize_binary_buffer(val_buf, val_size, val_size1);
1138         } else if (ret != ERROR_SUCCESS) {
1139             more_data = FALSE;
1140             if (ret != ERROR_NO_MORE_ITEMS) {
1141                 REGPROC_print_error();
1142             }
1143         } else {
1144             DWORD line_len;
1145             i++;
1146
1147             if ((*val_name_buf)[0]) {
1148                 const WCHAR val_start[] = {'"','%','s','"','=',0};
1149
1150                 line_len = 0;
1151                 REGPROC_export_string(line_buf, line_buf_size, &line_len, *val_name_buf, lstrlenW(*val_name_buf));
1152                 REGPROC_resize_char_buffer(val_name_buf, val_name_size, lstrlenW(*line_buf) + 1);
1153                 lstrcpyW(*val_name_buf, *line_buf);
1154
1155                 line_len = 3 + lstrlenW(*val_name_buf);
1156                 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_len);
1157                 sprintfW(*line_buf, val_start, *val_name_buf);
1158             } else {
1159                 const WCHAR std_val[] = {'@','=',0};
1160                 line_len = 2;
1161                 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_len);
1162                 lstrcpyW(*line_buf, std_val);
1163             }
1164
1165             switch (value_type) {
1166             case REG_SZ:
1167             {
1168                 WCHAR* wstr = (WCHAR*)*val_buf;
1169
1170                 if (val_size1 < sizeof(WCHAR) || val_size1 % sizeof(WCHAR) ||
1171                     wstr[val_size1 / sizeof(WCHAR) - 1]) {
1172                     REGPROC_export_binary(line_buf, line_buf_size, &line_len, value_type, *val_buf, val_size1, unicode);
1173                 } else {
1174                     const WCHAR start[] = {'"',0};
1175                     const WCHAR end[] = {'"','\r','\n',0};
1176                     DWORD len;
1177
1178                     len = lstrlenW(start);
1179                     REGPROC_resize_char_buffer(line_buf, line_buf_size, line_len + len);
1180                     lstrcpyW(*line_buf + line_len, start);
1181                     line_len += len;
1182
1183                     /* At this point we know wstr is '\0'-terminated
1184                      * so we can subtract 1 from the size
1185                      */
1186                     REGPROC_export_string(line_buf, line_buf_size, &line_len, wstr, val_size1 / sizeof(WCHAR) - 1);
1187
1188                     REGPROC_resize_char_buffer(line_buf, line_buf_size, line_len + lstrlenW(end));
1189                     lstrcpyW(*line_buf + line_len, end);
1190                 }
1191                 break;
1192             }
1193
1194             case REG_DWORD:
1195             {
1196                 WCHAR format[] = {'d','w','o','r','d',':','%','0','8','x','\r','\n',0};
1197
1198                 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_len + 15);
1199                 sprintfW(*line_buf + line_len, format, *((DWORD *)*val_buf));
1200                 break;
1201             }
1202
1203             default:
1204             {
1205                 char* key_nameA = GetMultiByteString(*reg_key_name_buf);
1206                 char* value_nameA = GetMultiByteString(*val_name_buf);
1207                 fprintf(stderr,"%s: warning - unsupported registry format '%d', "
1208                         "treat as binary\n",
1209                         getAppName(), value_type);
1210                 fprintf(stderr,"key name: \"%s\"\n", key_nameA);
1211                 fprintf(stderr,"value name:\"%s\"\n\n", value_nameA);
1212                 HeapFree(GetProcessHeap(), 0, key_nameA);
1213                 HeapFree(GetProcessHeap(), 0, value_nameA);
1214             }
1215                 /* falls through */
1216             case REG_EXPAND_SZ:
1217             case REG_MULTI_SZ:
1218                 /* falls through */
1219             case REG_BINARY:
1220                 REGPROC_export_binary(line_buf, line_buf_size, &line_len, value_type, *val_buf, val_size1, unicode);
1221             }
1222             REGPROC_write_line(file, *line_buf, unicode);
1223         }
1224     }
1225
1226     i = 0;
1227     more_data = TRUE;
1228     (*reg_key_name_buf)[curr_len] = '\\';
1229     while(more_data) {
1230         DWORD buf_size = *reg_key_name_size - curr_len - 1;
1231
1232         ret = RegEnumKeyExW(key, i, *reg_key_name_buf + curr_len + 1, &buf_size,
1233                            NULL, NULL, NULL, NULL);
1234         if (ret == ERROR_MORE_DATA) {
1235             /* Increase the size of the buffer and retry */
1236             REGPROC_resize_char_buffer(reg_key_name_buf, reg_key_name_size, curr_len + 1 + buf_size);
1237         } else if (ret != ERROR_SUCCESS) {
1238             more_data = FALSE;
1239             if (ret != ERROR_NO_MORE_ITEMS) {
1240                 REGPROC_print_error();
1241             }
1242         } else {
1243             HKEY subkey;
1244
1245             i++;
1246             if (RegOpenKeyW(key, *reg_key_name_buf + curr_len + 1,
1247                            &subkey) == ERROR_SUCCESS) {
1248                 export_hkey(file, subkey, reg_key_name_buf, reg_key_name_size,
1249                             val_name_buf, val_name_size, val_buf, val_size,
1250                             line_buf, line_buf_size, unicode);
1251                 RegCloseKey(subkey);
1252             } else {
1253                 REGPROC_print_error();
1254             }
1255         }
1256     }
1257     (*reg_key_name_buf)[curr_len] = '\0';
1258 }
1259
1260 /******************************************************************************
1261  * Open file in binary mode for export.
1262  */
1263 static FILE *REGPROC_open_export_file(WCHAR *file_name, BOOL unicode)
1264 {
1265     FILE *file;
1266     WCHAR dash = '-';
1267
1268     if (strncmpW(file_name,&dash,1)==0) {
1269         file=stdout;
1270         _setmode(_fileno(file), _O_BINARY);
1271     } else
1272     {
1273         CHAR* file_nameA = GetMultiByteString(file_name);
1274         file = fopen(file_nameA, "wb");
1275         if (!file) {
1276             perror("");
1277             fprintf(stderr,"%s: Can't open file \"%s\"\n", getAppName(), file_nameA);
1278             HeapFree(GetProcessHeap(), 0, file_nameA);
1279             exit(1);
1280         }
1281         HeapFree(GetProcessHeap(), 0, file_nameA);
1282     }
1283     if(unicode)
1284     {
1285         const BYTE unicode_seq[] = {0xff,0xfe};
1286         const WCHAR header[] = {'W','i','n','d','o','w','s',' ','R','e','g','i','s','t','r','y',' ','E','d','i','t','o','r',' ','V','e','r','s','i','o','n',' ','5','.','0','0','\r','\n'};
1287         fwrite(unicode_seq, sizeof(BYTE), sizeof(unicode_seq)/sizeof(unicode_seq[0]), file);
1288         fwrite(header, sizeof(WCHAR), sizeof(header)/sizeof(header[0]), file);
1289     } else
1290     {
1291         fputs("REGEDIT4\r\n", file);
1292     }
1293
1294     return file;
1295 }
1296
1297 /******************************************************************************
1298  * Writes contents of the registry key to the specified file stream.
1299  *
1300  * Parameters:
1301  * file_name - name of a file to export registry branch to.
1302  * reg_key_name - registry branch to export. The whole registry is exported if
1303  *      reg_key_name is NULL or contains an empty string.
1304  */
1305 BOOL export_registry_key(WCHAR *file_name, WCHAR *reg_key_name, DWORD format)
1306 {
1307     WCHAR *reg_key_name_buf;
1308     WCHAR *val_name_buf;
1309     BYTE *val_buf;
1310     WCHAR *line_buf;
1311     DWORD reg_key_name_size = KEY_MAX_LEN;
1312     DWORD val_name_size = KEY_MAX_LEN;
1313     DWORD val_size = REG_VAL_BUF_SIZE;
1314     DWORD line_buf_size = KEY_MAX_LEN + REG_VAL_BUF_SIZE;
1315     FILE *file = NULL;
1316     BOOL unicode = (format == REG_FORMAT_5);
1317
1318     reg_key_name_buf = HeapAlloc(GetProcessHeap(), 0,
1319                                  reg_key_name_size  * sizeof(*reg_key_name_buf));
1320     val_name_buf = HeapAlloc(GetProcessHeap(), 0,
1321                              val_name_size * sizeof(*val_name_buf));
1322     val_buf = HeapAlloc(GetProcessHeap(), 0, val_size);
1323     line_buf = HeapAlloc(GetProcessHeap(), 0, line_buf_size * sizeof(*line_buf));
1324     CHECK_ENOUGH_MEMORY(reg_key_name_buf && val_name_buf && val_buf && line_buf);
1325
1326     if (reg_key_name && reg_key_name[0]) {
1327         HKEY reg_key_class;
1328         WCHAR *branch_name = NULL;
1329         HKEY key;
1330
1331         REGPROC_resize_char_buffer(&reg_key_name_buf, &reg_key_name_size,
1332                                    lstrlenW(reg_key_name));
1333         lstrcpyW(reg_key_name_buf, reg_key_name);
1334
1335         /* open the specified key */
1336         if (!parseKeyName(reg_key_name, &reg_key_class, &branch_name)) {
1337             CHAR* key_nameA = GetMultiByteString(reg_key_name);
1338             fprintf(stderr,"%s: Incorrect registry class specification in '%s'\n",
1339                     getAppName(), key_nameA);
1340             HeapFree(GetProcessHeap(), 0, key_nameA);
1341             exit(1);
1342         }
1343         if (!branch_name[0]) {
1344             /* no branch - registry class is specified */
1345             file = REGPROC_open_export_file(file_name, unicode);
1346             export_hkey(file, reg_key_class,
1347                         &reg_key_name_buf, &reg_key_name_size,
1348                         &val_name_buf, &val_name_size,
1349                         &val_buf, &val_size, &line_buf,
1350                         &line_buf_size, unicode);
1351         } else if (RegOpenKeyW(reg_key_class, branch_name, &key) == ERROR_SUCCESS) {
1352             file = REGPROC_open_export_file(file_name, unicode);
1353             export_hkey(file, key,
1354                         &reg_key_name_buf, &reg_key_name_size,
1355                         &val_name_buf, &val_name_size,
1356                         &val_buf, &val_size, &line_buf,
1357                         &line_buf_size, unicode);
1358             RegCloseKey(key);
1359         } else {
1360             CHAR* key_nameA = GetMultiByteString(reg_key_name);
1361             fprintf(stderr,"%s: Can't export. Registry key '%s' does not exist!\n",
1362                     getAppName(), key_nameA);
1363             HeapFree(GetProcessHeap(), 0, key_nameA);
1364             REGPROC_print_error();
1365         }
1366     } else {
1367         unsigned int i;
1368
1369         /* export all registry classes */
1370         file = REGPROC_open_export_file(file_name, unicode);
1371         for (i = 0; i < REG_CLASS_NUMBER; i++) {
1372             /* do not export HKEY_CLASSES_ROOT */
1373             if (reg_class_keys[i] != HKEY_CLASSES_ROOT &&
1374                     reg_class_keys[i] != HKEY_CURRENT_USER &&
1375                     reg_class_keys[i] != HKEY_CURRENT_CONFIG &&
1376                     reg_class_keys[i] != HKEY_DYN_DATA) {
1377                 lstrcpyW(reg_key_name_buf, reg_class_namesW[i]);
1378                 export_hkey(file, reg_class_keys[i],
1379                             &reg_key_name_buf, &reg_key_name_size,
1380                             &val_name_buf, &val_name_size,
1381                             &val_buf, &val_size, &line_buf,
1382                             &line_buf_size, unicode);
1383             }
1384         }
1385     }
1386
1387     if (file) {
1388         fclose(file);
1389     }
1390     HeapFree(GetProcessHeap(), 0, reg_key_name);
1391     HeapFree(GetProcessHeap(), 0, val_name_buf);
1392     HeapFree(GetProcessHeap(), 0, val_buf);
1393     HeapFree(GetProcessHeap(), 0, line_buf);
1394     return TRUE;
1395 }
1396
1397 /******************************************************************************
1398  * Reads contents of the specified file into the registry.
1399  */
1400 BOOL import_registry_file(FILE* reg_file)
1401 {
1402     if (reg_file)
1403     {
1404         BYTE s[2];
1405         if (fread( s, 2, 1, reg_file) == 1)
1406         {
1407             if (s[0] == 0xff && s[1] == 0xfe)
1408             {
1409                 processRegLinesW(reg_file);
1410             } else
1411             {
1412                 processRegLinesA(reg_file, (char*)s);
1413             }
1414         }
1415         return TRUE;
1416     }
1417     return FALSE;
1418 }
1419
1420 /******************************************************************************
1421  * Removes the registry key with all subkeys. Parses full key name.
1422  *
1423  * Parameters:
1424  * reg_key_name - full name of registry branch to delete. Ignored if is NULL,
1425  *      empty, points to register key class, does not exist.
1426  */
1427 void delete_registry_key(WCHAR *reg_key_name)
1428 {
1429     WCHAR *key_name = NULL;
1430     HKEY key_class;
1431
1432     if (!reg_key_name || !reg_key_name[0])
1433         return;
1434
1435     if (!parseKeyName(reg_key_name, &key_class, &key_name)) {
1436         char* reg_key_nameA = GetMultiByteString(reg_key_name);
1437         fprintf(stderr,"%s: Incorrect registry class specification in '%s'\n",
1438                 getAppName(), reg_key_nameA);
1439         HeapFree(GetProcessHeap(), 0, reg_key_nameA);
1440         exit(1);
1441     }
1442     if (!*key_name) {
1443         char* reg_key_nameA = GetMultiByteString(reg_key_name);
1444         fprintf(stderr,"%s: Can't delete registry class '%s'\n",
1445                 getAppName(), reg_key_nameA);
1446         HeapFree(GetProcessHeap(), 0, reg_key_nameA);
1447         exit(1);
1448     }
1449
1450     RegDeleteTreeW(key_class, key_name);
1451 }