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