wineboot: Update the Danish translation.
[wine] / programs / wineboot / wineboot.c
1 /*
2  * Copyright (C) 2002 Andreas Mohr
3  * Copyright (C) 2002 Shachar Shemesh
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
18  */
19 /* Wine "bootup" handler application
20  *
21  * This app handles the various "hooks" windows allows for applications to perform
22  * as part of the bootstrap process. These are roughly divided into three types.
23  * Knowledge base articles that explain this are 137367, 179365, 232487 and 232509.
24  * Also, 119941 has some info on grpconv.exe
25  * The operations performed are (by order of execution):
26  *
27  * Preboot (prior to fully loading the Windows kernel):
28  * - wininit.exe (rename operations left in wininit.ini - Win 9x only)
29  * - PendingRenameOperations (rename operations left in the registry - Win NT+ only)
30  *
31  * Startup (before the user logs in)
32  * - Services (NT)
33  * - HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce (9x, asynch)
34  * - HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServices (9x, asynch)
35  * 
36  * After log in
37  * - HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce (all, synch)
38  * - HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run (all, asynch)
39  * - HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run (all, asynch)
40  * - Startup folders (all, ?asynch?)
41  * - HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce (all, asynch)
42  *
43  * Somewhere in there is processing the RunOnceEx entries (also no imp)
44  * 
45  * Bugs:
46  * - If a pending rename registry does not start with \??\ the entry is
47  *   processed anyways. I'm not sure that is the Windows behaviour.
48  * - Need to check what is the windows behaviour when trying to delete files
49  *   and directories that are read-only
50  * - In the pending rename registry processing - there are no traces of the files
51  *   processed (requires translations from Unicode to Ansi).
52  */
53
54 #include "config.h"
55 #include "wine/port.h"
56
57 #define COBJMACROS
58 #define WIN32_LEAN_AND_MEAN
59
60 #include <errno.h>
61 #include <fcntl.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #ifdef HAVE_GETOPT_H
65 # include <getopt.h>
66 #endif
67 #ifdef HAVE_SYS_STAT_H
68 # include <sys/stat.h>
69 #endif
70 #ifdef HAVE_UNISTD_H
71 # include <unistd.h>
72 #endif
73 #include <windows.h>
74 #include <winternl.h>
75 #include <wine/svcctl.h>
76 #include <wine/unicode.h>
77 #include <wine/library.h>
78 #include <wine/debug.h>
79
80 #include <shlobj.h>
81 #include <shobjidl.h>
82 #include <shlwapi.h>
83 #include <shellapi.h>
84 #include "resource.h"
85
86 WINE_DEFAULT_DEBUG_CHANNEL(wineboot);
87
88 #define MAX_LINE_LENGTH (2*MAX_PATH+2)
89
90 extern BOOL shutdown_close_windows( BOOL force );
91 extern void kill_processes( BOOL kill_desktop );
92
93 static WCHAR windowsdir[MAX_PATH];
94
95 /* retrieve the (unix) path to the wine.inf file */
96 static char *get_wine_inf_path(void)
97 {
98     const char *build_dir, *data_dir;
99     char *name = NULL;
100
101     if ((data_dir = wine_get_data_dir()))
102     {
103         if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(data_dir) + sizeof("/wine.inf") )))
104             return NULL;
105         strcpy( name, data_dir );
106         strcat( name, "/wine.inf" );
107     }
108     else if ((build_dir = wine_get_build_dir()))
109     {
110         if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(build_dir) + sizeof("/tools/wine.inf") )))
111             return NULL;
112         strcpy( name, build_dir );
113         strcat( name, "/tools/wine.inf" );
114     }
115     return name;
116 }
117
118 /* update the timestamp if different from the reference time */
119 static BOOL update_timestamp( const char *config_dir, unsigned long timestamp )
120 {
121     BOOL ret = FALSE;
122     int fd, count;
123     char buffer[100];
124     char *file = HeapAlloc( GetProcessHeap(), 0, strlen(config_dir) + sizeof("/.update-timestamp") );
125
126     if (!file) return FALSE;
127     strcpy( file, config_dir );
128     strcat( file, "/.update-timestamp" );
129
130     if ((fd = open( file, O_RDWR )) != -1)
131     {
132         if ((count = read( fd, buffer, sizeof(buffer) - 1 )) >= 0)
133         {
134             buffer[count] = 0;
135             if (!strncmp( buffer, "disable", sizeof("disable")-1 )) goto done;
136             if (timestamp == strtoul( buffer, NULL, 10 )) goto done;
137         }
138         lseek( fd, 0, SEEK_SET );
139         ftruncate( fd, 0 );
140     }
141     else
142     {
143         if (errno != ENOENT) goto done;
144         if ((fd = open( file, O_WRONLY | O_CREAT | O_TRUNC, 0666 )) == -1) goto done;
145     }
146
147     count = sprintf( buffer, "%lu\n", timestamp );
148     if (write( fd, buffer, count ) != count)
149     {
150         WINE_WARN( "failed to update timestamp in %s\n", file );
151         ftruncate( fd, 0 );
152     }
153     else ret = TRUE;
154
155 done:
156     if (fd != -1) close( fd );
157     HeapFree( GetProcessHeap(), 0, file );
158     return ret;
159 }
160
161 /* wrapper for RegSetValueExW */
162 static DWORD set_reg_value( HKEY hkey, const WCHAR *name, const WCHAR *value )
163 {
164     return RegSetValueExW( hkey, name, 0, REG_SZ, (const BYTE *)value, (strlenW(value) + 1) * sizeof(WCHAR) );
165 }
166
167 /* create the volatile hardware registry keys */
168 static void create_hardware_registry_keys(void)
169 {
170     static const WCHAR SystemW[] = {'H','a','r','d','w','a','r','e','\\',
171                                     'D','e','s','c','r','i','p','t','i','o','n','\\',
172                                     'S','y','s','t','e','m',0};
173     static const WCHAR fpuW[] = {'F','l','o','a','t','i','n','g','P','o','i','n','t','P','r','o','c','e','s','s','o','r',0};
174     static const WCHAR cpuW[] = {'C','e','n','t','r','a','l','P','r','o','c','e','s','s','o','r',0};
175     static const WCHAR IdentifierW[] = {'I','d','e','n','t','i','f','i','e','r',0};
176     static const WCHAR SysidW[] = {'A','T',' ','c','o','m','p','a','t','i','b','l','e',0};
177     static const WCHAR mhzKeyW[] = {'~','M','H','z',0};
178     static const WCHAR VendorIdentifierW[] = {'V','e','n','d','o','r','I','d','e','n','t','i','f','i','e','r',0};
179     static const WCHAR VenidIntelW[] = {'G','e','n','u','i','n','e','I','n','t','e','l',0};
180     /* static const WCHAR VenidAMDW[] = {'A','u','t','h','e','n','t','i','c','A','M','D',0}; */
181     static const WCHAR PercentDW[] = {'%','d',0};
182     static const WCHAR IntelCpuDescrW[] = {'x','8','6',' ','F','a','m','i','l','y',' ','%','d',' ','M','o','d','e','l',' ','%','d',
183                                            ' ','S','t','e','p','p','i','n','g',' ','%','d',0};
184     unsigned int i;
185     HKEY hkey, system_key, cpu_key, fpu_key;
186     SYSTEM_CPU_INFORMATION sci;
187     PROCESSOR_POWER_INFORMATION power_info;
188     WCHAR idW[60];
189
190     NtQuerySystemInformation( SystemCpuInformation, &sci, sizeof(sci), NULL );
191     if (NtPowerInformation(ProcessorInformation, NULL, 0, &power_info, sizeof(power_info)))
192         power_info.MaxMhz = 0;
193
194     /*TODO: report 64bit processors properly*/
195     sprintfW( idW, IntelCpuDescrW, sci.Level, HIBYTE(sci.Revision), LOBYTE(sci.Revision) );
196
197     if (RegCreateKeyExW( HKEY_LOCAL_MACHINE, SystemW, 0, NULL, REG_OPTION_VOLATILE,
198                          KEY_ALL_ACCESS, NULL, &system_key, NULL ))
199         return;
200
201     set_reg_value( system_key, IdentifierW, SysidW );
202
203     if (RegCreateKeyExW( system_key, fpuW, 0, NULL, REG_OPTION_VOLATILE,
204                          KEY_ALL_ACCESS, NULL, &fpu_key, NULL ))
205         fpu_key = 0;
206     if (RegCreateKeyExW( system_key, cpuW, 0, NULL, REG_OPTION_VOLATILE,
207                          KEY_ALL_ACCESS, NULL, &cpu_key, NULL ))
208         cpu_key = 0;
209
210     for (i = 0; i < NtCurrentTeb()->Peb->NumberOfProcessors; i++)
211     {
212         WCHAR numW[10];
213
214         sprintfW( numW, PercentDW, i );
215         if (!RegCreateKeyExW( cpu_key, numW, 0, NULL, REG_OPTION_VOLATILE,
216                               KEY_ALL_ACCESS, NULL, &hkey, NULL ))
217         {
218             set_reg_value( hkey, IdentifierW, idW );
219             /*TODO; report amd's properly*/
220             set_reg_value( hkey, VendorIdentifierW, VenidIntelW );
221             RegSetValueExW( hkey, mhzKeyW, 0, REG_DWORD, (BYTE *)&power_info.MaxMhz, sizeof(DWORD) );
222             RegCloseKey( hkey );
223         }
224         if (!RegCreateKeyExW( fpu_key, numW, 0, NULL, REG_OPTION_VOLATILE,
225                               KEY_ALL_ACCESS, NULL, &hkey, NULL ))
226         {
227             set_reg_value( hkey, IdentifierW, idW );
228             RegCloseKey( hkey );
229         }
230     }
231     RegCloseKey( fpu_key );
232     RegCloseKey( cpu_key );
233     RegCloseKey( system_key );
234 }
235
236
237 /* create the DynData registry keys */
238 static void create_dynamic_registry_keys(void)
239 {
240     static const WCHAR StatDataW[] = {'P','e','r','f','S','t','a','t','s','\\',
241                                       'S','t','a','t','D','a','t','a',0};
242     static const WCHAR ConfigManagerW[] = {'C','o','n','f','i','g',' ','M','a','n','a','g','e','r','\\',
243                                            'E','n','u','m',0};
244     HKEY key;
245
246     if (!RegCreateKeyExW( HKEY_DYN_DATA, StatDataW, 0, NULL, 0, KEY_WRITE, NULL, &key, NULL ))
247         RegCloseKey( key );
248     if (!RegCreateKeyExW( HKEY_DYN_DATA, ConfigManagerW, 0, NULL, 0, KEY_WRITE, NULL, &key, NULL ))
249         RegCloseKey( key );
250 }
251
252 /* create the platform-specific environment registry keys */
253 static void create_environment_registry_keys( void )
254 {
255     static const WCHAR EnvironW[]  = {'S','y','s','t','e','m','\\',
256                                       'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
257                                       'C','o','n','t','r','o','l','\\',
258                                       'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
259                                       'E','n','v','i','r','o','n','m','e','n','t',0};
260     static const WCHAR NumProcW[]  = {'N','U','M','B','E','R','_','O','F','_','P','R','O','C','E','S','S','O','R','S',0};
261     static const WCHAR ProcArchW[] = {'P','R','O','C','E','S','S','O','R','_','A','R','C','H','I','T','E','C','T','U','R','E',0};
262     static const WCHAR x86W[]      = {'x','8','6',0};
263     static const WCHAR ProcIdW[]   = {'P','R','O','C','E','S','S','O','R','_','I','D','E','N','T','I','F','I','E','R',0};
264     static const WCHAR ProcLvlW[]  = {'P','R','O','C','E','S','S','O','R','_','L','E','V','E','L',0};
265     static const WCHAR ProcRevW[]  = {'P','R','O','C','E','S','S','O','R','_','R','E','V','I','S','I','O','N',0};
266     static const WCHAR PercentDW[] = {'%','d',0};
267     static const WCHAR Percent04XW[] = {'%','0','4','x',0};
268     static const WCHAR IntelCpuDescrW[]  = {'x','8','6',' ','F','a','m','i','l','y',' ','%','d',' ','M','o','d','e','l',' ','%','d',
269                                             ' ','S','t','e','p','p','i','n','g',' ','%','d',',',' ','G','e','n','u','i','n','e','I','n','t','e','l',0};
270
271     HKEY env_key;
272     SYSTEM_CPU_INFORMATION sci;
273     WCHAR buffer[60];
274
275     NtQuerySystemInformation( SystemCpuInformation, &sci, sizeof(sci), NULL );
276
277     if (RegCreateKeyW( HKEY_LOCAL_MACHINE, EnvironW, &env_key )) return;
278
279     sprintfW( buffer, PercentDW, NtCurrentTeb()->Peb->NumberOfProcessors );
280     set_reg_value( env_key, NumProcW, buffer );
281
282     /* TODO: currently hardcoded x86, add different processors */
283     set_reg_value( env_key, ProcArchW, x86W );
284
285     /* TODO: currently hardcoded Intel, add different processors */
286     sprintfW( buffer, IntelCpuDescrW, sci.Level, HIBYTE(sci.Revision), LOBYTE(sci.Revision) );
287     set_reg_value( env_key, ProcIdW, buffer );
288
289     sprintfW( buffer, PercentDW, sci.Level );
290     set_reg_value( env_key, ProcLvlW, buffer );
291
292     /* Properly report model/stepping */
293     sprintfW( buffer, Percent04XW, sci.Revision );
294     set_reg_value( env_key, ProcRevW, buffer );
295
296     RegCloseKey( env_key );
297 }
298
299 static void create_volatile_environment_registry_key(void)
300 {
301     static const WCHAR VolatileEnvW[] = {'V','o','l','a','t','i','l','e',' ','E','n','v','i','r','o','n','m','e','n','t',0};
302     static const WCHAR AppDataW[] = {'A','P','P','D','A','T','A',0};
303     static const WCHAR ClientNameW[] = {'C','L','I','E','N','T','N','A','M','E',0};
304     static const WCHAR HomeDriveW[] = {'H','O','M','E','D','R','I','V','E',0};
305     static const WCHAR HomePathW[] = {'H','O','M','E','P','A','T','H',0};
306     static const WCHAR HomeShareW[] = {'H','O','M','E','S','H','A','R','E',0};
307     static const WCHAR LocalAppDataW[] = {'L','O','C','A','L','A','P','P','D','A','T','A',0};
308     static const WCHAR LogonServerW[] = {'L','O','G','O','N','S','E','R','V','E','R',0};
309     static const WCHAR SessionNameW[] = {'S','E','S','S','I','O','N','N','A','M','E',0};
310     static const WCHAR UserNameW[] = {'U','S','E','R','N','A','M','E',0};
311     static const WCHAR UserProfileW[] = {'U','S','E','R','P','R','O','F','I','L','E',0};
312     static const WCHAR ConsoleW[] = {'C','o','n','s','o','l','e',0};
313     static const WCHAR EmptyW[] = {0};
314     WCHAR path[MAX_PATH];
315     WCHAR computername[MAX_COMPUTERNAME_LENGTH + 1 + 2];
316     DWORD size;
317     HKEY hkey;
318     HRESULT hr;
319
320     if (RegCreateKeyExW( HKEY_CURRENT_USER, VolatileEnvW, 0, NULL, REG_OPTION_VOLATILE,
321                          KEY_ALL_ACCESS, NULL, &hkey, NULL ))
322         return;
323
324     hr = SHGetFolderPathW( NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, path );
325     if (SUCCEEDED(hr)) set_reg_value( hkey, AppDataW, path );
326
327     set_reg_value( hkey, ClientNameW, ConsoleW );
328
329     /* Write the profile path's drive letter and directory components into
330      * HOMEDRIVE and HOMEPATH respectively. */
331     hr = SHGetFolderPathW( NULL, CSIDL_PROFILE, NULL, SHGFP_TYPE_CURRENT, path );
332     if (SUCCEEDED(hr))
333     {
334         set_reg_value( hkey, UserProfileW, path );
335         set_reg_value( hkey, HomePathW, path + 2 );
336         path[2] = '\0';
337         set_reg_value( hkey, HomeDriveW, path );
338     }
339
340     size = sizeof(path);
341     if (GetUserNameW( path, &size )) set_reg_value( hkey, UserNameW, path );
342
343     set_reg_value( hkey, HomeShareW, EmptyW );
344
345     hr = SHGetFolderPathW( NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, path );
346     if (SUCCEEDED(hr))
347         set_reg_value( hkey, LocalAppDataW, path );
348
349     size = sizeof(computername) - 2;
350     if (GetComputerNameW(&computername[2], &size))
351     {
352         computername[0] = computername[1] = '\\';
353         set_reg_value( hkey, LogonServerW, computername );
354     }
355
356     set_reg_value( hkey, SessionNameW, ConsoleW );
357     RegCloseKey( hkey );
358 }
359
360 /* Performs the rename operations dictated in %SystemRoot%\Wininit.ini.
361  * Returns FALSE if there was an error, or otherwise if all is ok.
362  */
363 static BOOL wininit(void)
364 {
365     static const WCHAR nulW[] = {'N','U','L',0};
366     static const WCHAR renameW[] = {'r','e','n','a','m','e',0};
367     static const WCHAR wininitW[] = {'w','i','n','i','n','i','t','.','i','n','i',0};
368     static const WCHAR wininitbakW[] = {'w','i','n','i','n','i','t','.','b','a','k',0};
369     WCHAR initial_buffer[1024];
370     WCHAR *str, *buffer = initial_buffer;
371     DWORD size = sizeof(initial_buffer)/sizeof(WCHAR);
372     DWORD res;
373
374     for (;;)
375     {
376         if (!(res = GetPrivateProfileSectionW( renameW, buffer, size, wininitW ))) return TRUE;
377         if (res < size - 2) break;
378         if (buffer != initial_buffer) HeapFree( GetProcessHeap(), 0, buffer );
379         size *= 2;
380         if (!(buffer = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return FALSE;
381     }
382
383     for (str = buffer; *str; str += strlenW(str) + 1)
384     {
385         WCHAR *value;
386
387         if (*str == ';') continue;  /* comment */
388         if (!(value = strchrW( str, '=' ))) continue;
389
390         /* split the line into key and value */
391         *value++ = 0;
392
393         if (!lstrcmpiW( nulW, str ))
394         {
395             WINE_TRACE("Deleting file %s\n", wine_dbgstr_w(value) );
396             if( !DeleteFileW( value ) )
397                 WINE_WARN("Error deleting file %s\n", wine_dbgstr_w(value) );
398         }
399         else
400         {
401             WINE_TRACE("Renaming file %s to %s\n", wine_dbgstr_w(value), wine_dbgstr_w(str) );
402
403             if( !MoveFileExW(value, str, MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) )
404                 WINE_WARN("Error renaming %s to %s\n", wine_dbgstr_w(value), wine_dbgstr_w(str) );
405         }
406         str = value;
407     }
408
409     if (buffer != initial_buffer) HeapFree( GetProcessHeap(), 0, buffer );
410
411     if( !MoveFileExW( wininitW, wininitbakW, MOVEFILE_REPLACE_EXISTING) )
412     {
413         WINE_ERR("Couldn't rename wininit.ini, error %d\n", GetLastError() );
414
415         return FALSE;
416     }
417
418     return TRUE;
419 }
420
421 static BOOL pendingRename(void)
422 {
423     static const WCHAR ValueName[] = {'P','e','n','d','i','n','g',
424                                       'F','i','l','e','R','e','n','a','m','e',
425                                       'O','p','e','r','a','t','i','o','n','s',0};
426     static const WCHAR SessionW[] = { 'S','y','s','t','e','m','\\',
427                                      'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
428                                      'C','o','n','t','r','o','l','\\',
429                                      'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
430     WCHAR *buffer=NULL;
431     const WCHAR *src=NULL, *dst=NULL;
432     DWORD dataLength=0;
433     HKEY hSession=NULL;
434     DWORD res;
435
436     WINE_TRACE("Entered\n");
437
438     if( (res=RegOpenKeyExW( HKEY_LOCAL_MACHINE, SessionW, 0, KEY_ALL_ACCESS, &hSession ))
439             !=ERROR_SUCCESS )
440     {
441         WINE_TRACE("The key was not found - skipping\n");
442         return TRUE;
443     }
444
445     res=RegQueryValueExW( hSession, ValueName, NULL, NULL /* The value type does not really interest us, as it is not
446                                                              truly a REG_MULTI_SZ anyways */,
447             NULL, &dataLength );
448     if( res==ERROR_FILE_NOT_FOUND )
449     {
450         /* No value - nothing to do. Great! */
451         WINE_TRACE("Value not present - nothing to rename\n");
452         res=TRUE;
453         goto end;
454     }
455
456     if( res!=ERROR_SUCCESS )
457     {
458         WINE_ERR("Couldn't query value's length (%d)\n", res );
459         res=FALSE;
460         goto end;
461     }
462
463     buffer=HeapAlloc( GetProcessHeap(),0,dataLength );
464     if( buffer==NULL )
465     {
466         WINE_ERR("Couldn't allocate %u bytes for the value\n", dataLength );
467         res=FALSE;
468         goto end;
469     }
470
471     res=RegQueryValueExW( hSession, ValueName, NULL, NULL, (LPBYTE)buffer, &dataLength );
472     if( res!=ERROR_SUCCESS )
473     {
474         WINE_ERR("Couldn't query value after successfully querying before (%u),\n"
475                 "please report to wine-devel@winehq.org\n", res);
476         res=FALSE;
477         goto end;
478     }
479
480     /* Make sure that the data is long enough and ends with two NULLs. This
481      * simplifies the code later on.
482      */
483     if( dataLength<2*sizeof(buffer[0]) ||
484             buffer[dataLength/sizeof(buffer[0])-1]!='\0' ||
485             buffer[dataLength/sizeof(buffer[0])-2]!='\0' )
486     {
487         WINE_ERR("Improper value format - doesn't end with NULL\n");
488         res=FALSE;
489         goto end;
490     }
491
492     for( src=buffer; (src-buffer)*sizeof(src[0])<dataLength && *src!='\0';
493             src=dst+lstrlenW(dst)+1 )
494     {
495         DWORD dwFlags=0;
496
497         WINE_TRACE("processing next command\n");
498
499         dst=src+lstrlenW(src)+1;
500
501         /* We need to skip the \??\ header */
502         if( src[0]=='\\' && src[1]=='?' && src[2]=='?' && src[3]=='\\' )
503             src+=4;
504
505         if( dst[0]=='!' )
506         {
507             dwFlags|=MOVEFILE_REPLACE_EXISTING;
508             dst++;
509         }
510
511         if( dst[0]=='\\' && dst[1]=='?' && dst[2]=='?' && dst[3]=='\\' )
512             dst+=4;
513
514         if( *dst!='\0' )
515         {
516             /* Rename the file */
517             MoveFileExW( src, dst, dwFlags );
518         } else
519         {
520             /* Delete the file or directory */
521             if( (res=GetFileAttributesW(src))!=INVALID_FILE_ATTRIBUTES )
522             {
523                 if( (res&FILE_ATTRIBUTE_DIRECTORY)==0 )
524                 {
525                     /* It's a file */
526                     DeleteFileW(src);
527                 } else
528                 {
529                     /* It's a directory */
530                     RemoveDirectoryW(src);
531                 }
532             } else
533             {
534                 WINE_ERR("couldn't get file attributes (%d)\n", GetLastError() );
535             }
536         }
537     }
538
539     if((res=RegDeleteValueW(hSession, ValueName))!=ERROR_SUCCESS )
540     {
541         WINE_ERR("Error deleting the value (%u)\n", GetLastError() );
542         res=FALSE;
543     } else
544         res=TRUE;
545     
546 end:
547     HeapFree(GetProcessHeap(), 0, buffer);
548
549     if( hSession!=NULL )
550         RegCloseKey( hSession );
551
552     return res;
553 }
554
555 enum runkeys {
556     RUNKEY_RUN, RUNKEY_RUNONCE, RUNKEY_RUNSERVICES, RUNKEY_RUNSERVICESONCE
557 };
558
559 const WCHAR runkeys_names[][30]=
560 {
561     {'R','u','n',0},
562     {'R','u','n','O','n','c','e',0},
563     {'R','u','n','S','e','r','v','i','c','e','s',0},
564     {'R','u','n','S','e','r','v','i','c','e','s','O','n','c','e',0}
565 };
566
567 #define INVALID_RUNCMD_RETURN -1
568 /*
569  * This function runs the specified command in the specified dir.
570  * [in,out] cmdline - the command line to run. The function may change the passed buffer.
571  * [in] dir - the dir to run the command in. If it is NULL, then the current dir is used.
572  * [in] wait - whether to wait for the run program to finish before returning.
573  * [in] minimized - Whether to ask the program to run minimized.
574  *
575  * Returns:
576  * If running the process failed, returns INVALID_RUNCMD_RETURN. Use GetLastError to get the error code.
577  * If wait is FALSE - returns 0 if successful.
578  * If wait is TRUE - returns the program's return value.
579  */
580 static DWORD runCmd(LPWSTR cmdline, LPCWSTR dir, BOOL wait, BOOL minimized)
581 {
582     STARTUPINFOW si;
583     PROCESS_INFORMATION info;
584     DWORD exit_code=0;
585
586     memset(&si, 0, sizeof(si));
587     si.cb=sizeof(si);
588     if( minimized )
589     {
590         si.dwFlags=STARTF_USESHOWWINDOW;
591         si.wShowWindow=SW_MINIMIZE;
592     }
593     memset(&info, 0, sizeof(info));
594
595     if( !CreateProcessW(NULL, cmdline, NULL, NULL, FALSE, 0, NULL, dir, &si, &info) )
596     {
597         WINE_WARN("Failed to run command %s (%d)\n", wine_dbgstr_w(cmdline), GetLastError() );
598         return INVALID_RUNCMD_RETURN;
599     }
600
601     WINE_TRACE("Successfully ran command %s - Created process handle %p\n",
602                wine_dbgstr_w(cmdline), info.hProcess );
603
604     if(wait)
605     {   /* wait for the process to exit */
606         WaitForSingleObject(info.hProcess, INFINITE);
607         GetExitCodeProcess(info.hProcess, &exit_code);
608     }
609
610     CloseHandle( info.hThread );
611     CloseHandle( info.hProcess );
612
613     return exit_code;
614 }
615
616 /*
617  * Process a "Run" type registry key.
618  * hkRoot is the HKEY from which "Software\Microsoft\Windows\CurrentVersion" is
619  *      opened.
620  * szKeyName is the key holding the actual entries.
621  * bDelete tells whether we should delete each value right before executing it.
622  * bSynchronous tells whether we should wait for the prog to complete before
623  *      going on to the next prog.
624  */
625 static BOOL ProcessRunKeys( HKEY hkRoot, LPCWSTR szKeyName, BOOL bDelete,
626         BOOL bSynchronous )
627 {
628     static const WCHAR WINKEY_NAME[]={'S','o','f','t','w','a','r','e','\\',
629         'M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\',
630         'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
631     HKEY hkWin, hkRun;
632     DWORD res;
633     DWORD i, nMaxCmdLine=0, nMaxValue=0;
634     WCHAR *szCmdLine=NULL;
635     WCHAR *szValue=NULL;
636
637     if (hkRoot==HKEY_LOCAL_MACHINE)
638         WINE_TRACE("processing %s entries under HKLM\n",wine_dbgstr_w(szKeyName) );
639     else
640         WINE_TRACE("processing %s entries under HKCU\n",wine_dbgstr_w(szKeyName) );
641
642     if (RegOpenKeyExW( hkRoot, WINKEY_NAME, 0, KEY_READ, &hkWin ) != ERROR_SUCCESS)
643         return TRUE;
644
645     if (RegOpenKeyExW( hkWin, szKeyName, 0, bDelete?KEY_ALL_ACCESS:KEY_READ, &hkRun ) != ERROR_SUCCESS)
646     {
647         RegCloseKey( hkWin );
648         return TRUE;
649     }
650     RegCloseKey( hkWin );
651
652     if( (res=RegQueryInfoKeyW( hkRun, NULL, NULL, NULL, NULL, NULL, NULL, &i, &nMaxValue,
653                     &nMaxCmdLine, NULL, NULL ))!=ERROR_SUCCESS )
654         goto end;
655
656     if( i==0 )
657     {
658         WINE_TRACE("No commands to execute.\n");
659
660         res=ERROR_SUCCESS;
661         goto end;
662     }
663     
664     if( (szCmdLine=HeapAlloc(GetProcessHeap(),0,nMaxCmdLine))==NULL )
665     {
666         WINE_ERR("Couldn't allocate memory for the commands to be executed\n");
667
668         res=ERROR_NOT_ENOUGH_MEMORY;
669         goto end;
670     }
671
672     if( (szValue=HeapAlloc(GetProcessHeap(),0,(++nMaxValue)*sizeof(*szValue)))==NULL )
673     {
674         WINE_ERR("Couldn't allocate memory for the value names\n");
675
676         res=ERROR_NOT_ENOUGH_MEMORY;
677         goto end;
678     }
679     
680     while( i>0 )
681     {
682         DWORD nValLength=nMaxValue, nDataLength=nMaxCmdLine;
683         DWORD type;
684
685         --i;
686
687         if( (res=RegEnumValueW( hkRun, i, szValue, &nValLength, 0, &type,
688                         (LPBYTE)szCmdLine, &nDataLength ))!=ERROR_SUCCESS )
689         {
690             WINE_ERR("Couldn't read in value %d - %d\n", i, res );
691
692             continue;
693         }
694
695         if( bDelete && (res=RegDeleteValueW( hkRun, szValue ))!=ERROR_SUCCESS )
696         {
697             WINE_ERR("Couldn't delete value - %d, %d. Running command anyways.\n", i, res );
698         }
699         
700         if( type!=REG_SZ )
701         {
702             WINE_ERR("Incorrect type of value #%d (%d)\n", i, type );
703
704             continue;
705         }
706
707         if( (res=runCmd(szCmdLine, NULL, bSynchronous, FALSE ))==INVALID_RUNCMD_RETURN )
708         {
709             WINE_ERR("Error running cmd %s (%d)\n", wine_dbgstr_w(szCmdLine), GetLastError() );
710         }
711
712         WINE_TRACE("Done processing cmd #%d\n", i);
713     }
714
715     res=ERROR_SUCCESS;
716
717 end:
718     HeapFree( GetProcessHeap(), 0, szValue );
719     HeapFree( GetProcessHeap(), 0, szCmdLine );
720
721     if( hkRun!=NULL )
722         RegCloseKey( hkRun );
723
724     WINE_TRACE("done\n");
725
726     return res==ERROR_SUCCESS;
727 }
728
729 /*
730  * WFP is Windows File Protection, in NT5 and Windows 2000 it maintains a cache
731  * of known good dlls and scans through and replaces corrupted DLLs with these
732  * known good versions. The only programs that should install into this dll
733  * cache are Windows Updates and IE (which is treated like a Windows Update)
734  *
735  * Implementing this allows installing ie in win2k mode to actually install the
736  * system dlls that we expect and need
737  */
738 static int ProcessWindowsFileProtection(void)
739 {
740     static const WCHAR winlogonW[] = {'S','o','f','t','w','a','r','e','\\',
741                                       'M','i','c','r','o','s','o','f','t','\\',
742                                       'W','i','n','d','o','w','s',' ','N','T','\\',
743                                       'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
744                                       'W','i','n','l','o','g','o','n',0};
745     static const WCHAR cachedirW[] = {'S','F','C','D','l','l','C','a','c','h','e','D','i','r',0};
746     static const WCHAR dllcacheW[] = {'\\','d','l','l','c','a','c','h','e','\\','*',0};
747     static const WCHAR wildcardW[] = {'\\','*',0};
748     WIN32_FIND_DATAW finddata;
749     HANDLE find_handle;
750     BOOL find_rc;
751     DWORD rc;
752     HKEY hkey;
753     LPWSTR dllcache = NULL;
754
755     if (!RegOpenKeyW( HKEY_LOCAL_MACHINE, winlogonW, &hkey ))
756     {
757         DWORD sz = 0;
758         if (!RegQueryValueExW( hkey, cachedirW, 0, NULL, NULL, &sz))
759         {
760             sz += sizeof(WCHAR);
761             dllcache = HeapAlloc(GetProcessHeap(),0,sz + sizeof(wildcardW));
762             RegQueryValueExW( hkey, cachedirW, 0, NULL, (LPBYTE)dllcache, &sz);
763             strcatW( dllcache, wildcardW );
764         }
765     }
766     RegCloseKey(hkey);
767
768     if (!dllcache)
769     {
770         DWORD sz = GetSystemDirectoryW( NULL, 0 );
771         dllcache = HeapAlloc( GetProcessHeap(), 0, sz * sizeof(WCHAR) + sizeof(dllcacheW));
772         GetSystemDirectoryW( dllcache, sz );
773         strcatW( dllcache, dllcacheW );
774     }
775
776     find_handle = FindFirstFileW(dllcache,&finddata);
777     dllcache[ strlenW(dllcache) - 2] = 0; /* strip off wildcard */
778     find_rc = find_handle != INVALID_HANDLE_VALUE;
779     while (find_rc)
780     {
781         static const WCHAR dotW[] = {'.',0};
782         static const WCHAR dotdotW[] = {'.','.',0};
783         WCHAR targetpath[MAX_PATH];
784         WCHAR currentpath[MAX_PATH];
785         UINT sz;
786         UINT sz2;
787         WCHAR tempfile[MAX_PATH];
788
789         if (strcmpW(finddata.cFileName,dotW) == 0 || strcmpW(finddata.cFileName,dotdotW) == 0)
790         {
791             find_rc = FindNextFileW(find_handle,&finddata);
792             continue;
793         }
794
795         sz = MAX_PATH;
796         sz2 = MAX_PATH;
797         VerFindFileW(VFFF_ISSHAREDFILE, finddata.cFileName, windowsdir,
798                      windowsdir, currentpath, &sz, targetpath, &sz2);
799         sz = MAX_PATH;
800         rc = VerInstallFileW(0, finddata.cFileName, finddata.cFileName,
801                              dllcache, targetpath, currentpath, tempfile, &sz);
802         if (rc != ERROR_SUCCESS)
803         {
804             WINE_WARN("WFP: %s error 0x%x\n",wine_dbgstr_w(finddata.cFileName),rc);
805             DeleteFileW(tempfile);
806         }
807
808         /* now delete the source file so that we don't try to install it over and over again */
809         lstrcpynW( targetpath, dllcache, MAX_PATH - 1 );
810         sz = strlenW( targetpath );
811         targetpath[sz++] = '\\';
812         lstrcpynW( targetpath + sz, finddata.cFileName, MAX_PATH - sz );
813         if (!DeleteFileW( targetpath ))
814             WINE_WARN( "failed to delete %s: error %u\n", wine_dbgstr_w(targetpath), GetLastError() );
815
816         find_rc = FindNextFileW(find_handle,&finddata);
817     }
818     FindClose(find_handle);
819     HeapFree(GetProcessHeap(),0,dllcache);
820     return 1;
821 }
822
823 static BOOL start_services_process(void)
824 {
825     static const WCHAR svcctl_started_event[] = SVCCTL_STARTED_EVENT;
826     static const WCHAR services[] = {'\\','s','e','r','v','i','c','e','s','.','e','x','e',0};
827     PROCESS_INFORMATION pi;
828     STARTUPINFOW si;
829     HANDLE wait_handles[2];
830     WCHAR path[MAX_PATH];
831
832     if (!GetSystemDirectoryW(path, MAX_PATH - strlenW(services)))
833         return FALSE;
834     strcatW(path, services);
835     ZeroMemory(&si, sizeof(si));
836     si.cb = sizeof(si);
837     if (!CreateProcessW(path, path, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
838     {
839         WINE_ERR("Couldn't start services.exe: error %u\n", GetLastError());
840         return FALSE;
841     }
842     CloseHandle(pi.hThread);
843
844     wait_handles[0] = CreateEventW(NULL, TRUE, FALSE, svcctl_started_event);
845     wait_handles[1] = pi.hProcess;
846
847     /* wait for the event to become available or the process to exit */
848     if ((WaitForMultipleObjects(2, wait_handles, FALSE, INFINITE)) == WAIT_OBJECT_0 + 1)
849     {
850         DWORD exit_code;
851         GetExitCodeProcess(pi.hProcess, &exit_code);
852         WINE_ERR("Unexpected termination of services.exe - exit code %d\n", exit_code);
853         CloseHandle(pi.hProcess);
854         CloseHandle(wait_handles[0]);
855         return FALSE;
856     }
857
858     CloseHandle(pi.hProcess);
859     CloseHandle(wait_handles[0]);
860     return TRUE;
861 }
862
863 static INT_PTR CALLBACK wait_dlgproc( HWND hwnd, UINT msg, WPARAM wp, LPARAM lp )
864 {
865     switch (msg)
866     {
867     case WM_INITDIALOG:
868         {
869             WCHAR *buffer, text[1024];
870             const WCHAR *name = (WCHAR *)lp;
871             HICON icon = LoadImageW( 0, (LPCWSTR)IDI_WINLOGO, IMAGE_ICON, 48, 48, LR_SHARED );
872             SendDlgItemMessageW( hwnd, IDC_WAITICON, STM_SETICON, (WPARAM)icon, 0 );
873             SendDlgItemMessageW( hwnd, IDC_WAITTEXT, WM_GETTEXT, 1024, (LPARAM)text );
874             buffer = HeapAlloc( GetProcessHeap(), 0, (strlenW(text) + strlenW(name) + 1) * sizeof(WCHAR) );
875             sprintfW( buffer, text, name );
876             SendDlgItemMessageW( hwnd, IDC_WAITTEXT, WM_SETTEXT, 0, (LPARAM)buffer );
877             HeapFree( GetProcessHeap(), 0, buffer );
878         }
879         break;
880     }
881     return 0;
882 }
883
884 static HWND show_wait_window(void)
885 {
886     const char *config_dir = wine_get_config_dir();
887     WCHAR *name;
888     HWND hwnd;
889     DWORD len;
890
891     len = MultiByteToWideChar( CP_UNIXCP, 0, config_dir, -1, NULL, 0 );
892     name = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
893     MultiByteToWideChar( CP_UNIXCP, 0, config_dir, -1, name, len );
894     hwnd = CreateDialogParamW( GetModuleHandleW(0), MAKEINTRESOURCEW(IDD_WAITDLG), 0,
895                                wait_dlgproc, (LPARAM)name );
896     ShowWindow( hwnd, SW_SHOWNORMAL );
897     HeapFree( GetProcessHeap(), 0, name );
898     return hwnd;
899 }
900
901 static HANDLE start_rundll32( const char *inf_path, BOOL wow64 )
902 {
903     static const WCHAR rundll[] = {'\\','r','u','n','d','l','l','3','2','.','e','x','e',0};
904     static const WCHAR setupapi[] = {' ','s','e','t','u','p','a','p','i',',',
905                                      'I','n','s','t','a','l','l','H','i','n','f','S','e','c','t','i','o','n',0};
906     static const WCHAR definstall[] = {' ','D','e','f','a','u','l','t','I','n','s','t','a','l','l',0};
907     static const WCHAR wowinstall[] = {' ','W','o','w','6','4','I','n','s','t','a','l','l',0};
908     static const WCHAR inf[] = {' ','1','2','8',' ','\\','\\','?','\\','u','n','i','x',0 };
909
910     WCHAR app[MAX_PATH + sizeof(rundll)/sizeof(WCHAR)];
911     STARTUPINFOW si;
912     PROCESS_INFORMATION pi;
913     WCHAR *buffer;
914     DWORD inf_len, cmd_len;
915
916     memset( &si, 0, sizeof(si) );
917     si.cb = sizeof(si);
918
919     if (wow64)
920     {
921         if (!GetSystemWow64DirectoryW( app, MAX_PATH )) return 0;  /* not on 64-bit */
922     }
923     else GetSystemDirectoryW( app, MAX_PATH );
924
925     strcatW( app, rundll );
926
927     cmd_len = strlenW(app) * sizeof(WCHAR) + sizeof(setupapi) + sizeof(definstall) + sizeof(inf);
928     inf_len = MultiByteToWideChar( CP_UNIXCP, 0, inf_path, -1, NULL, 0 );
929
930     if (!(buffer = HeapAlloc( GetProcessHeap(), 0, cmd_len + inf_len * sizeof(WCHAR) ))) return 0;
931
932     strcpyW( buffer, app );
933     strcatW( buffer, setupapi );
934     strcatW( buffer, wow64 ? wowinstall : definstall );
935     strcatW( buffer, inf );
936     MultiByteToWideChar( CP_UNIXCP, 0, inf_path, -1, buffer + strlenW(buffer), inf_len );
937
938     if (CreateProcessW( app, buffer, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ))
939         CloseHandle( pi.hThread );
940     else
941         pi.hProcess = 0;
942
943     HeapFree( GetProcessHeap(), 0, buffer );
944     return pi.hProcess;
945 }
946
947 /* execute rundll32 on the wine.inf file if necessary */
948 static void update_wineprefix( int force )
949 {
950     const char *config_dir = wine_get_config_dir();
951     char *inf_path = get_wine_inf_path();
952     int fd;
953     struct stat st;
954
955     if (!inf_path)
956     {
957         WINE_MESSAGE( "wine: failed to update %s, wine.inf not found\n", config_dir );
958         return;
959     }
960     if ((fd = open( inf_path, O_RDONLY )) == -1)
961     {
962         WINE_MESSAGE( "wine: failed to update %s with %s: %s\n",
963                       config_dir, inf_path, strerror(errno) );
964         goto done;
965     }
966     fstat( fd, &st );
967     close( fd );
968
969     if (update_timestamp( config_dir, st.st_mtime ) || force)
970     {
971         HANDLE process;
972         DWORD count = 0;
973
974         if ((process = start_rundll32( inf_path, FALSE )))
975         {
976             HWND hwnd = show_wait_window();
977             for (;;)
978             {
979                 MSG msg;
980                 DWORD res = MsgWaitForMultipleObjects( 1, &process, FALSE, INFINITE, QS_ALLINPUT );
981                 if (res == WAIT_OBJECT_0)
982                 {
983                     CloseHandle( process );
984                     if (count++ || !(process = start_rundll32( inf_path, TRUE ))) break;
985                 }
986                 else while (PeekMessageW( &msg, 0, 0, 0, PM_REMOVE )) DispatchMessageW( &msg );
987             }
988             DestroyWindow( hwnd );
989         }
990         WINE_MESSAGE( "wine: configuration in '%s' has been updated.\n", config_dir );
991     }
992
993 done:
994     HeapFree( GetProcessHeap(), 0, inf_path );
995 }
996
997 /* Process items in the StartUp group of the user's Programs under the Start Menu. Some installers put
998  * shell links here to restart themselves after boot. */
999 static BOOL ProcessStartupItems(void)
1000 {
1001     BOOL ret = FALSE;
1002     HRESULT hr;
1003     IMalloc *ppM = NULL;
1004     IShellFolder *psfDesktop = NULL, *psfStartup = NULL;
1005     LPITEMIDLIST pidlStartup = NULL, pidlItem;
1006     ULONG NumPIDLs;
1007     IEnumIDList *iEnumList = NULL;
1008     STRRET strret;
1009     WCHAR wszCommand[MAX_PATH];
1010
1011     WINE_TRACE("Processing items in the StartUp folder.\n");
1012
1013     hr = SHGetMalloc(&ppM);
1014     if (FAILED(hr))
1015     {
1016         WINE_ERR("Couldn't get IMalloc object.\n");
1017         goto done;
1018     }
1019
1020     hr = SHGetDesktopFolder(&psfDesktop);
1021     if (FAILED(hr))
1022     {
1023         WINE_ERR("Couldn't get desktop folder.\n");
1024         goto done;
1025     }
1026
1027     hr = SHGetSpecialFolderLocation(NULL, CSIDL_STARTUP, &pidlStartup);
1028     if (FAILED(hr))
1029     {
1030         WINE_TRACE("Couldn't get StartUp folder location.\n");
1031         goto done;
1032     }
1033
1034     hr = IShellFolder_BindToObject(psfDesktop, pidlStartup, NULL, &IID_IShellFolder, (LPVOID*)&psfStartup);
1035     if (FAILED(hr))
1036     {
1037         WINE_TRACE("Couldn't bind IShellFolder to StartUp folder.\n");
1038         goto done;
1039     }
1040
1041     hr = IShellFolder_EnumObjects(psfStartup, NULL, SHCONTF_NONFOLDERS | SHCONTF_INCLUDEHIDDEN, &iEnumList);
1042     if (FAILED(hr))
1043     {
1044         WINE_TRACE("Unable to enumerate StartUp objects.\n");
1045         goto done;
1046     }
1047
1048     while (IEnumIDList_Next(iEnumList, 1, &pidlItem, &NumPIDLs) == S_OK &&
1049            (NumPIDLs) == 1)
1050     {
1051         hr = IShellFolder_GetDisplayNameOf(psfStartup, pidlItem, SHGDN_FORPARSING, &strret);
1052         if (FAILED(hr))
1053             WINE_TRACE("Unable to get display name of enumeration item.\n");
1054         else
1055         {
1056             hr = StrRetToBufW(&strret, pidlItem, wszCommand, MAX_PATH);
1057             if (FAILED(hr))
1058                 WINE_TRACE("Unable to parse display name.\n");
1059             else
1060             {
1061                 HINSTANCE hinst;
1062
1063                 hinst = ShellExecuteW(NULL, NULL, wszCommand, NULL, NULL, SW_SHOWNORMAL);
1064                 if (PtrToUlong(hinst) <= 32)
1065                     WINE_WARN("Error %p executing command %s.\n", hinst, wine_dbgstr_w(wszCommand));
1066             }
1067         }
1068
1069         IMalloc_Free(ppM, pidlItem);
1070     }
1071
1072     /* Return success */
1073     ret = TRUE;
1074
1075 done:
1076     if (iEnumList) IEnumIDList_Release(iEnumList);
1077     if (psfStartup) IShellFolder_Release(psfStartup);
1078     if (pidlStartup) IMalloc_Free(ppM, pidlStartup);
1079
1080     return ret;
1081 }
1082
1083 static void usage(void)
1084 {
1085     WINE_MESSAGE( "Usage: wineboot [options]\n" );
1086     WINE_MESSAGE( "Options;\n" );
1087     WINE_MESSAGE( "    -h,--help         Display this help message\n" );
1088     WINE_MESSAGE( "    -e,--end-session  End the current session cleanly\n" );
1089     WINE_MESSAGE( "    -f,--force        Force exit for processes that don't exit cleanly\n" );
1090     WINE_MESSAGE( "    -i,--init         Perform initialization for first Wine instance\n" );
1091     WINE_MESSAGE( "    -k,--kill         Kill running processes without any cleanup\n" );
1092     WINE_MESSAGE( "    -r,--restart      Restart only, don't do normal startup operations\n" );
1093     WINE_MESSAGE( "    -s,--shutdown     Shutdown only, don't reboot\n" );
1094     WINE_MESSAGE( "    -u,--update       Update the wineprefix directory\n" );
1095 }
1096
1097 static const char short_options[] = "efhikrsu";
1098
1099 static const struct option long_options[] =
1100 {
1101     { "help",        0, 0, 'h' },
1102     { "end-session", 0, 0, 'e' },
1103     { "force",       0, 0, 'f' },
1104     { "init" ,       0, 0, 'i' },
1105     { "kill",        0, 0, 'k' },
1106     { "restart",     0, 0, 'r' },
1107     { "shutdown",    0, 0, 's' },
1108     { "update",      0, 0, 'u' },
1109     { NULL,          0, 0, 0 }
1110 };
1111
1112 int main( int argc, char *argv[] )
1113 {
1114     extern HANDLE CDECL __wine_make_process_system(void);
1115     static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
1116
1117     /* First, set the current directory to SystemRoot */
1118     int optc;
1119     int end_session = 0, force = 0, init = 0, kill = 0, restart = 0, shutdown = 0, update = 0;
1120     HANDLE event;
1121     SECURITY_ATTRIBUTES sa;
1122
1123     GetWindowsDirectoryW( windowsdir, MAX_PATH );
1124     if( !SetCurrentDirectoryW( windowsdir ) )
1125         WINE_ERR("Cannot set the dir to %s (%d)\n", wine_dbgstr_w(windowsdir), GetLastError() );
1126
1127     while ((optc = getopt_long(argc, argv, short_options, long_options, NULL )) != -1)
1128     {
1129         switch(optc)
1130         {
1131         case 'e': end_session = 1; break;
1132         case 'f': force = 1; break;
1133         case 'i': init = 1; break;
1134         case 'k': kill = 1; break;
1135         case 'r': restart = 1; break;
1136         case 's': shutdown = 1; break;
1137         case 'u': update = 1; break;
1138         case 'h': usage(); return 0;
1139         case '?': usage(); return 1;
1140         }
1141     }
1142
1143     if (end_session)
1144     {
1145         if (!shutdown_close_windows( force )) return 1;
1146     }
1147
1148     if (kill) kill_processes( shutdown );
1149
1150     if (shutdown) return 0;
1151
1152     sa.nLength = sizeof(sa);
1153     sa.lpSecurityDescriptor = NULL;
1154     sa.bInheritHandle = TRUE;  /* so that services.exe inherits it */
1155     event = CreateEventW( &sa, TRUE, FALSE, wineboot_eventW );
1156
1157     ResetEvent( event );  /* in case this is a restart */
1158
1159     create_hardware_registry_keys();
1160     create_dynamic_registry_keys();
1161     create_environment_registry_keys();
1162     wininit();
1163     pendingRename();
1164
1165     ProcessWindowsFileProtection();
1166     ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICESONCE], TRUE, FALSE );
1167
1168     if (init || (kill && !restart))
1169     {
1170         ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICES], FALSE, FALSE );
1171         start_services_process();
1172     }
1173     if (init || update) update_wineprefix( update );
1174
1175     create_volatile_environment_registry_key();
1176
1177     ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNONCE], TRUE, TRUE );
1178
1179     if (!init && !restart)
1180     {
1181         ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUN], FALSE, FALSE );
1182         ProcessRunKeys( HKEY_CURRENT_USER, runkeys_names[RUNKEY_RUN], FALSE, FALSE );
1183         ProcessStartupItems();
1184     }
1185
1186     WINE_TRACE("Operation done\n");
1187
1188     SetEvent( event );
1189     return 0;
1190 }