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