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