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