push 38a8c0aff9170390b5a3ded41e7cf5b02f3a73d8
[wine/hacks.git] / programs / wineboot / wineboot.c
blob60a51b704ffd52fdf9f458984a4856f4f6c7cb05
1 /*
2 * Copyright (C) 2002 Andreas Mohr
3 * Copyright (C) 2002 Shachar Shemesh
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.
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.
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
19 /* Wine "bootup" handler application
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):
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)
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)
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)
43 * Somewhere in there is processing the RunOnceEx entries (also no imp)
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).
54 #include "config.h"
55 #include "wine/port.h"
57 #define COBJMACROS
58 #define WIN32_LEAN_AND_MEAN
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>
80 #include <shlobj.h>
81 #include <shobjidl.h>
82 #include <shlwapi.h>
83 #include <shellapi.h>
84 #include <setupapi.h>
86 WINE_DEFAULT_DEBUG_CHANNEL(wineboot);
88 #define MAX_LINE_LENGTH (2*MAX_PATH+2)
90 extern BOOL shutdown_close_windows( BOOL force );
91 extern void kill_processes( BOOL kill_desktop );
93 static WCHAR windowsdir[MAX_PATH];
95 /* retrieve the (unix) path to the wine.inf file */
96 static char *get_wine_inf_path(void)
98 const char *build_dir, *data_dir;
99 char *name = NULL;
101 if ((data_dir = wine_get_data_dir()))
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" );
108 else if ((build_dir = wine_get_build_dir()))
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" );
115 return name;
118 /* update the timestamp if different from the reference time */
119 static BOOL update_timestamp( const char *config_dir, unsigned long timestamp )
121 BOOL ret = FALSE;
122 int fd, count;
123 char buffer[100];
124 char *file = HeapAlloc( GetProcessHeap(), 0, strlen(config_dir) + sizeof("/.update-timestamp") );
126 if (!file) return FALSE;
127 strcpy( file, config_dir );
128 strcat( file, "/.update-timestamp" );
130 if ((fd = open( file, O_RDWR )) != -1)
132 if ((count = read( fd, buffer, sizeof(buffer) - 1 )) >= 0)
134 buffer[count] = 0;
135 if (!strncmp( buffer, "disable", sizeof("disable")-1 )) goto done;
136 if (timestamp == strtoul( buffer, NULL, 10 )) goto done;
138 lseek( fd, 0, SEEK_SET );
139 ftruncate( fd, 0 );
141 else
143 if (errno != ENOENT) goto done;
144 if ((fd = open( file, O_WRONLY | O_CREAT | O_TRUNC, 0666 )) == -1) goto done;
147 count = sprintf( buffer, "%lu\n", timestamp );
148 if (write( fd, buffer, count ) != count)
150 WINE_WARN( "failed to update timestamp in %s\n", file );
151 ftruncate( fd, 0 );
153 else ret = TRUE;
155 done:
156 if (fd != -1) close( fd );
157 HeapFree( GetProcessHeap(), 0, file );
158 return ret;
161 /* create the volatile hardware registry keys */
162 static void create_hardware_registry_keys(void)
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];
184 NtQuerySystemInformation( SystemCpuInformation, &sci, sizeof(sci), NULL );
185 if (NtPowerInformation(ProcessorInformation, NULL, 0, &power_info, sizeof(power_info)))
186 power_info.MaxMhz = 0;
188 /*TODO: report 64bit processors properly*/
189 sprintfW( idW, IntelCpuDescrW, sci.Level, HIBYTE(sci.Revision), LOBYTE(sci.Revision) );
191 if (RegCreateKeyExW( HKEY_LOCAL_MACHINE, SystemW, 0, NULL, REG_OPTION_VOLATILE,
192 KEY_ALL_ACCESS, NULL, &system_key, NULL ))
193 return;
195 RegSetValueExW( system_key, IdentifierW, 0, REG_SZ, (const BYTE *)SysidW, sizeof(SysidW) );
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;
204 for (i = 0; i < NtCurrentTeb()->Peb->NumberOfProcessors; i++)
206 WCHAR numW[10];
208 sprintfW( numW, PercentDW, i );
209 if (!RegCreateKeyExW( cpu_key, numW, 0, NULL, REG_OPTION_VOLATILE,
210 KEY_ALL_ACCESS, NULL, &hkey, NULL ))
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 );
220 if (!RegCreateKeyExW( fpu_key, numW, 0, NULL, REG_OPTION_VOLATILE,
221 KEY_ALL_ACCESS, NULL, &hkey, NULL ))
223 RegSetValueExW( hkey, IdentifierW, 0, REG_SZ,
224 (const BYTE *)idW, (strlenW(idW) + 1) * sizeof(WCHAR) );
225 RegCloseKey( hkey );
228 RegCloseKey( fpu_key );
229 RegCloseKey( cpu_key );
230 RegCloseKey( system_key );
233 /* create the platform-specific environment registry keys */
234 static void create_environment_registry_keys( void )
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};
252 HKEY env_key;
253 SYSTEM_CPU_INFORMATION sci;
254 WCHAR buffer[60];
256 NtQuerySystemInformation( SystemCpuInformation, &sci, sizeof(sci), NULL );
258 if (RegCreateKeyW( HKEY_LOCAL_MACHINE, EnvironW, &env_key )) return;
260 sprintfW( buffer, PercentDW, NtCurrentTeb()->Peb->NumberOfProcessors );
261 RegSetValueExW( env_key, NumProcW, 0, REG_SZ, (BYTE *)buffer, (strlenW(buffer) + 1) * sizeof(WCHAR) );
263 /* TODO: currently hardcoded x86, add different processors */
264 RegSetValueExW( env_key, ProcArchW, 0, REG_SZ, (const BYTE *)x86W, sizeof(x86W) );
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) );
270 sprintfW( buffer, PercentDW, sci.Level );
271 RegSetValueExW( env_key, ProcLvlW, 0, REG_SZ, (BYTE *)buffer, (strlenW(buffer) + 1) * sizeof(WCHAR) );
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) );
277 RegCloseKey( env_key );
280 /* Performs the rename operations dictated in %SystemRoot%\Wininit.ini.
281 * Returns FALSE if there was an error, or otherwise if all is ok.
283 static BOOL wininit(void)
285 static const WCHAR nulW[] = {'N','U','L',0};
286 static const WCHAR renameW[] = {'r','e','n','a','m','e',0};
287 static const WCHAR wininitW[] = {'w','i','n','i','n','i','t','.','i','n','i',0};
288 static const WCHAR wininitbakW[] = {'w','i','n','i','n','i','t','.','b','a','k',0};
289 WCHAR initial_buffer[1024];
290 WCHAR *str, *buffer = initial_buffer;
291 DWORD size = sizeof(initial_buffer)/sizeof(WCHAR);
292 DWORD res;
294 for (;;)
296 if (!(res = GetPrivateProfileSectionW( renameW, buffer, size, wininitW ))) return TRUE;
297 if (res < size - 2) break;
298 if (buffer != initial_buffer) HeapFree( GetProcessHeap(), 0, buffer );
299 size *= 2;
300 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return FALSE;
303 for (str = buffer; *str; str += strlenW(str) + 1)
305 WCHAR *value;
307 if (*str == ';') continue; /* comment */
308 if (!(value = strchrW( str, '=' ))) continue;
310 /* split the line into key and value */
311 *value++ = 0;
313 if (!lstrcmpiW( nulW, str ))
315 WINE_TRACE("Deleting file %s\n", wine_dbgstr_w(value) );
316 if( !DeleteFileW( value ) )
317 WINE_WARN("Error deleting file %s\n", wine_dbgstr_w(value) );
319 else
321 WINE_TRACE("Renaming file %s to %s\n", wine_dbgstr_w(value), wine_dbgstr_w(str) );
323 if( !MoveFileExW(value, str, MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) )
324 WINE_WARN("Error renaming %s to %s\n", wine_dbgstr_w(value), wine_dbgstr_w(str) );
326 str = value;
329 if (buffer != initial_buffer) HeapFree( GetProcessHeap(), 0, buffer );
331 if( !MoveFileExW( wininitW, wininitbakW, MOVEFILE_REPLACE_EXISTING) )
333 WINE_ERR("Couldn't rename wininit.ini, error %d\n", GetLastError() );
335 return FALSE;
338 return TRUE;
341 static BOOL pendingRename(void)
343 static const WCHAR ValueName[] = {'P','e','n','d','i','n','g',
344 'F','i','l','e','R','e','n','a','m','e',
345 'O','p','e','r','a','t','i','o','n','s',0};
346 static const WCHAR SessionW[] = { 'S','y','s','t','e','m','\\',
347 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
348 'C','o','n','t','r','o','l','\\',
349 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
350 WCHAR *buffer=NULL;
351 const WCHAR *src=NULL, *dst=NULL;
352 DWORD dataLength=0;
353 HKEY hSession=NULL;
354 DWORD res;
356 WINE_TRACE("Entered\n");
358 if( (res=RegOpenKeyExW( HKEY_LOCAL_MACHINE, SessionW, 0, KEY_ALL_ACCESS, &hSession ))
359 !=ERROR_SUCCESS )
361 WINE_TRACE("The key was not found - skipping\n");
362 return TRUE;
365 res=RegQueryValueExW( hSession, ValueName, NULL, NULL /* The value type does not really interest us, as it is not
366 truly a REG_MULTI_SZ anyways */,
367 NULL, &dataLength );
368 if( res==ERROR_FILE_NOT_FOUND )
370 /* No value - nothing to do. Great! */
371 WINE_TRACE("Value not present - nothing to rename\n");
372 res=TRUE;
373 goto end;
376 if( res!=ERROR_SUCCESS )
378 WINE_ERR("Couldn't query value's length (%d)\n", res );
379 res=FALSE;
380 goto end;
383 buffer=HeapAlloc( GetProcessHeap(),0,dataLength );
384 if( buffer==NULL )
386 WINE_ERR("Couldn't allocate %u bytes for the value\n", dataLength );
387 res=FALSE;
388 goto end;
391 res=RegQueryValueExW( hSession, ValueName, NULL, NULL, (LPBYTE)buffer, &dataLength );
392 if( res!=ERROR_SUCCESS )
394 WINE_ERR("Couldn't query value after successfully querying before (%u),\n"
395 "please report to wine-devel@winehq.org\n", res);
396 res=FALSE;
397 goto end;
400 /* Make sure that the data is long enough and ends with two NULLs. This
401 * simplifies the code later on.
403 if( dataLength<2*sizeof(buffer[0]) ||
404 buffer[dataLength/sizeof(buffer[0])-1]!='\0' ||
405 buffer[dataLength/sizeof(buffer[0])-2]!='\0' )
407 WINE_ERR("Improper value format - doesn't end with NULL\n");
408 res=FALSE;
409 goto end;
412 for( src=buffer; (src-buffer)*sizeof(src[0])<dataLength && *src!='\0';
413 src=dst+lstrlenW(dst)+1 )
415 DWORD dwFlags=0;
417 WINE_TRACE("processing next command\n");
419 dst=src+lstrlenW(src)+1;
421 /* We need to skip the \??\ header */
422 if( src[0]=='\\' && src[1]=='?' && src[2]=='?' && src[3]=='\\' )
423 src+=4;
425 if( dst[0]=='!' )
427 dwFlags|=MOVEFILE_REPLACE_EXISTING;
428 dst++;
431 if( dst[0]=='\\' && dst[1]=='?' && dst[2]=='?' && dst[3]=='\\' )
432 dst+=4;
434 if( *dst!='\0' )
436 /* Rename the file */
437 MoveFileExW( src, dst, dwFlags );
438 } else
440 /* Delete the file or directory */
441 if( (res=GetFileAttributesW(src))!=INVALID_FILE_ATTRIBUTES )
443 if( (res&FILE_ATTRIBUTE_DIRECTORY)==0 )
445 /* It's a file */
446 DeleteFileW(src);
447 } else
449 /* It's a directory */
450 RemoveDirectoryW(src);
452 } else
454 WINE_ERR("couldn't get file attributes (%d)\n", GetLastError() );
459 if((res=RegDeleteValueW(hSession, ValueName))!=ERROR_SUCCESS )
461 WINE_ERR("Error deleting the value (%u)\n", GetLastError() );
462 res=FALSE;
463 } else
464 res=TRUE;
466 end:
467 HeapFree(GetProcessHeap(), 0, buffer);
469 if( hSession!=NULL )
470 RegCloseKey( hSession );
472 return res;
475 enum runkeys {
476 RUNKEY_RUN, RUNKEY_RUNONCE, RUNKEY_RUNSERVICES, RUNKEY_RUNSERVICESONCE
479 const WCHAR runkeys_names[][30]=
481 {'R','u','n',0},
482 {'R','u','n','O','n','c','e',0},
483 {'R','u','n','S','e','r','v','i','c','e','s',0},
484 {'R','u','n','S','e','r','v','i','c','e','s','O','n','c','e',0}
487 #define INVALID_RUNCMD_RETURN -1
489 * This function runs the specified command in the specified dir.
490 * [in,out] cmdline - the command line to run. The function may change the passed buffer.
491 * [in] dir - the dir to run the command in. If it is NULL, then the current dir is used.
492 * [in] wait - whether to wait for the run program to finish before returning.
493 * [in] minimized - Whether to ask the program to run minimized.
495 * Returns:
496 * If running the process failed, returns INVALID_RUNCMD_RETURN. Use GetLastError to get the error code.
497 * If wait is FALSE - returns 0 if successful.
498 * If wait is TRUE - returns the program's return value.
500 static DWORD runCmd(LPWSTR cmdline, LPCWSTR dir, BOOL wait, BOOL minimized)
502 STARTUPINFOW si;
503 PROCESS_INFORMATION info;
504 DWORD exit_code=0;
506 memset(&si, 0, sizeof(si));
507 si.cb=sizeof(si);
508 if( minimized )
510 si.dwFlags=STARTF_USESHOWWINDOW;
511 si.wShowWindow=SW_MINIMIZE;
513 memset(&info, 0, sizeof(info));
515 if( !CreateProcessW(NULL, cmdline, NULL, NULL, FALSE, 0, NULL, dir, &si, &info) )
517 WINE_WARN("Failed to run command %s (%d)\n", wine_dbgstr_w(cmdline), GetLastError() );
518 return INVALID_RUNCMD_RETURN;
521 WINE_TRACE("Successfully ran command %s - Created process handle %p\n",
522 wine_dbgstr_w(cmdline), info.hProcess );
524 if(wait)
525 { /* wait for the process to exit */
526 WaitForSingleObject(info.hProcess, INFINITE);
527 GetExitCodeProcess(info.hProcess, &exit_code);
530 CloseHandle( info.hThread );
531 CloseHandle( info.hProcess );
533 return exit_code;
537 * Process a "Run" type registry key.
538 * hkRoot is the HKEY from which "Software\Microsoft\Windows\CurrentVersion" is
539 * opened.
540 * szKeyName is the key holding the actual entries.
541 * bDelete tells whether we should delete each value right before executing it.
542 * bSynchronous tells whether we should wait for the prog to complete before
543 * going on to the next prog.
545 static BOOL ProcessRunKeys( HKEY hkRoot, LPCWSTR szKeyName, BOOL bDelete,
546 BOOL bSynchronous )
548 static const WCHAR WINKEY_NAME[]={'S','o','f','t','w','a','r','e','\\',
549 'M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\',
550 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
551 HKEY hkWin, hkRun;
552 DWORD res;
553 DWORD i, nMaxCmdLine=0, nMaxValue=0;
554 WCHAR *szCmdLine=NULL;
555 WCHAR *szValue=NULL;
557 if (hkRoot==HKEY_LOCAL_MACHINE)
558 WINE_TRACE("processing %s entries under HKLM\n",wine_dbgstr_w(szKeyName) );
559 else
560 WINE_TRACE("processing %s entries under HKCU\n",wine_dbgstr_w(szKeyName) );
562 if (RegOpenKeyExW( hkRoot, WINKEY_NAME, 0, KEY_READ, &hkWin ) != ERROR_SUCCESS)
563 return TRUE;
565 if (RegOpenKeyExW( hkWin, szKeyName, 0, bDelete?KEY_ALL_ACCESS:KEY_READ, &hkRun ) != ERROR_SUCCESS)
567 RegCloseKey( hkWin );
568 return TRUE;
570 RegCloseKey( hkWin );
572 if( (res=RegQueryInfoKeyW( hkRun, NULL, NULL, NULL, NULL, NULL, NULL, &i, &nMaxValue,
573 &nMaxCmdLine, NULL, NULL ))!=ERROR_SUCCESS )
574 goto end;
576 if( i==0 )
578 WINE_TRACE("No commands to execute.\n");
580 res=ERROR_SUCCESS;
581 goto end;
584 if( (szCmdLine=HeapAlloc(GetProcessHeap(),0,nMaxCmdLine))==NULL )
586 WINE_ERR("Couldn't allocate memory for the commands to be executed\n");
588 res=ERROR_NOT_ENOUGH_MEMORY;
589 goto end;
592 if( (szValue=HeapAlloc(GetProcessHeap(),0,(++nMaxValue)*sizeof(*szValue)))==NULL )
594 WINE_ERR("Couldn't allocate memory for the value names\n");
596 res=ERROR_NOT_ENOUGH_MEMORY;
597 goto end;
600 while( i>0 )
602 DWORD nValLength=nMaxValue, nDataLength=nMaxCmdLine;
603 DWORD type;
605 --i;
607 if( (res=RegEnumValueW( hkRun, i, szValue, &nValLength, 0, &type,
608 (LPBYTE)szCmdLine, &nDataLength ))!=ERROR_SUCCESS )
610 WINE_ERR("Couldn't read in value %d - %d\n", i, res );
612 continue;
615 if( bDelete && (res=RegDeleteValueW( hkRun, szValue ))!=ERROR_SUCCESS )
617 WINE_ERR("Couldn't delete value - %d, %d. Running command anyways.\n", i, res );
620 if( type!=REG_SZ )
622 WINE_ERR("Incorrect type of value #%d (%d)\n", i, type );
624 continue;
627 if( (res=runCmd(szCmdLine, NULL, bSynchronous, FALSE ))==INVALID_RUNCMD_RETURN )
629 WINE_ERR("Error running cmd %s (%d)\n", wine_dbgstr_w(szCmdLine), GetLastError() );
632 WINE_TRACE("Done processing cmd #%d\n", i);
635 res=ERROR_SUCCESS;
637 end:
638 HeapFree( GetProcessHeap(), 0, szValue );
639 HeapFree( GetProcessHeap(), 0, szCmdLine );
641 if( hkRun!=NULL )
642 RegCloseKey( hkRun );
644 WINE_TRACE("done\n");
646 return res==ERROR_SUCCESS;
650 * WFP is Windows File Protection, in NT5 and Windows 2000 it maintains a cache
651 * of known good dlls and scans through and replaces corrupted DLLs with these
652 * known good versions. The only programs that should install into this dll
653 * cache are Windows Updates and IE (which is treated like a Windows Update)
655 * Implementing this allows installing ie in win2k mode to actually install the
656 * system dlls that we expect and need
658 static int ProcessWindowsFileProtection(void)
660 static const WCHAR winlogonW[] = {'S','o','f','t','w','a','r','e','\\',
661 'M','i','c','r','o','s','o','f','t','\\',
662 'W','i','n','d','o','w','s',' ','N','T','\\',
663 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
664 'W','i','n','l','o','g','o','n',0};
665 static const WCHAR cachedirW[] = {'S','F','C','D','l','l','C','a','c','h','e','D','i','r',0};
666 static const WCHAR dllcacheW[] = {'\\','d','l','l','c','a','c','h','e','\\','*',0};
667 static const WCHAR wildcardW[] = {'\\','*',0};
668 WIN32_FIND_DATAW finddata;
669 HANDLE find_handle;
670 BOOL find_rc;
671 DWORD rc;
672 HKEY hkey;
673 LPWSTR dllcache = NULL;
675 if (!RegOpenKeyW( HKEY_LOCAL_MACHINE, winlogonW, &hkey ))
677 DWORD sz = 0;
678 if (!RegQueryValueExW( hkey, cachedirW, 0, NULL, NULL, &sz))
680 sz += sizeof(WCHAR);
681 dllcache = HeapAlloc(GetProcessHeap(),0,sz + sizeof(wildcardW));
682 RegQueryValueExW( hkey, cachedirW, 0, NULL, (LPBYTE)dllcache, &sz);
683 strcatW( dllcache, wildcardW );
686 RegCloseKey(hkey);
688 if (!dllcache)
690 DWORD sz = GetSystemDirectoryW( NULL, 0 );
691 dllcache = HeapAlloc( GetProcessHeap(), 0, sz * sizeof(WCHAR) + sizeof(dllcacheW));
692 GetSystemDirectoryW( dllcache, sz );
693 strcatW( dllcache, dllcacheW );
696 find_handle = FindFirstFileW(dllcache,&finddata);
697 dllcache[ strlenW(dllcache) - 2] = 0; /* strip off wildcard */
698 find_rc = find_handle != INVALID_HANDLE_VALUE;
699 while (find_rc)
701 static const WCHAR dotW[] = {'.',0};
702 static const WCHAR dotdotW[] = {'.','.',0};
703 WCHAR targetpath[MAX_PATH];
704 WCHAR currentpath[MAX_PATH];
705 UINT sz;
706 UINT sz2;
707 WCHAR tempfile[MAX_PATH];
709 if (strcmpW(finddata.cFileName,dotW) == 0 || strcmpW(finddata.cFileName,dotdotW) == 0)
711 find_rc = FindNextFileW(find_handle,&finddata);
712 continue;
715 sz = MAX_PATH;
716 sz2 = MAX_PATH;
717 VerFindFileW(VFFF_ISSHAREDFILE, finddata.cFileName, windowsdir,
718 windowsdir, currentpath, &sz, targetpath, &sz2);
719 sz = MAX_PATH;
720 rc = VerInstallFileW(0, finddata.cFileName, finddata.cFileName,
721 dllcache, targetpath, currentpath, tempfile, &sz);
722 if (rc != ERROR_SUCCESS)
724 WINE_WARN("WFP: %s error 0x%x\n",wine_dbgstr_w(finddata.cFileName),rc);
725 DeleteFileW(tempfile);
728 /* now delete the source file so that we don't try to install it over and over again */
729 lstrcpynW( targetpath, dllcache, MAX_PATH - 1 );
730 sz = strlenW( targetpath );
731 targetpath[sz++] = '\\';
732 lstrcpynW( targetpath + sz, finddata.cFileName, MAX_PATH - sz );
733 if (!DeleteFileW( targetpath ))
734 WINE_WARN( "failed to delete %s: error %u\n", wine_dbgstr_w(targetpath), GetLastError() );
736 find_rc = FindNextFileW(find_handle,&finddata);
738 FindClose(find_handle);
739 HeapFree(GetProcessHeap(),0,dllcache);
740 return 1;
743 static BOOL start_services_process(void)
745 static const WCHAR svcctl_started_event[] = SVCCTL_STARTED_EVENT;
746 static const WCHAR services[] = {'\\','s','e','r','v','i','c','e','s','.','e','x','e',0};
747 PROCESS_INFORMATION pi;
748 STARTUPINFOW si;
749 HANDLE wait_handles[2];
750 WCHAR path[MAX_PATH];
752 if (!GetSystemDirectoryW(path, MAX_PATH - strlenW(services)))
753 return FALSE;
754 strcatW(path, services);
755 ZeroMemory(&si, sizeof(si));
756 si.cb = sizeof(si);
757 if (!CreateProcessW(path, path, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
759 WINE_ERR("Couldn't start services.exe: error %u\n", GetLastError());
760 return FALSE;
762 CloseHandle(pi.hThread);
764 wait_handles[0] = CreateEventW(NULL, TRUE, FALSE, svcctl_started_event);
765 wait_handles[1] = pi.hProcess;
767 /* wait for the event to become available or the process to exit */
768 if ((WaitForMultipleObjects(2, wait_handles, FALSE, INFINITE)) == WAIT_OBJECT_0 + 1)
770 DWORD exit_code;
771 GetExitCodeProcess(pi.hProcess, &exit_code);
772 WINE_ERR("Unexpected termination of services.exe - exit code %d\n", exit_code);
773 CloseHandle(pi.hProcess);
774 CloseHandle(wait_handles[0]);
775 return FALSE;
778 CloseHandle(pi.hProcess);
779 CloseHandle(wait_handles[0]);
780 return TRUE;
783 /* execute rundll32 on the wine.inf file if necessary */
784 static void update_wineprefix( int force )
786 static const WCHAR cmdlineW[] = {'D','e','f','a','u','l','t','I','n','s','t','a','l','l',' ',
787 '1','2','8',' ','\\','\\','?','\\','u','n','i','x' };
789 const char *config_dir = wine_get_config_dir();
790 char *inf_path = get_wine_inf_path();
791 int fd;
792 struct stat st;
794 if (!inf_path)
796 WINE_MESSAGE( "wine: failed to update %s, wine.inf not found\n", config_dir );
797 return;
799 if ((fd = open( inf_path, O_RDONLY )) == -1)
801 WINE_MESSAGE( "wine: failed to update %s with %s: %s\n",
802 config_dir, inf_path, strerror(errno) );
803 goto done;
805 fstat( fd, &st );
806 close( fd );
808 if (update_timestamp( config_dir, st.st_mtime ) || force)
810 WCHAR *buffer;
811 DWORD len = MultiByteToWideChar( CP_UNIXCP, 0, inf_path, -1, NULL, 0 );
812 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(cmdlineW) + len*sizeof(WCHAR) ))) goto done;
813 memcpy( buffer, cmdlineW, sizeof(cmdlineW) );
814 MultiByteToWideChar( CP_UNIXCP, 0, inf_path, -1, buffer + sizeof(cmdlineW)/sizeof(WCHAR), len );
816 InstallHinfSectionW( 0, 0, buffer, 0 );
817 HeapFree( GetProcessHeap(), 0, buffer );
818 WINE_MESSAGE( "wine: configuration in '%s' has been updated.\n", config_dir );
821 done:
822 HeapFree( GetProcessHeap(), 0, inf_path );
825 /* Process items in the StartUp group of the user's Programs under the Start Menu. Some installers put
826 * shell links here to restart themselves after boot. */
827 static BOOL ProcessStartupItems(void)
829 BOOL ret = FALSE;
830 HRESULT hr;
831 IMalloc *ppM = NULL;
832 IShellFolder *psfDesktop = NULL, *psfStartup = NULL;
833 LPITEMIDLIST pidlStartup = NULL, pidlItem;
834 ULONG NumPIDLs;
835 IEnumIDList *iEnumList = NULL;
836 STRRET strret;
837 WCHAR wszCommand[MAX_PATH];
839 WINE_TRACE("Processing items in the StartUp folder.\n");
841 hr = SHGetMalloc(&ppM);
842 if (FAILED(hr))
844 WINE_ERR("Couldn't get IMalloc object.\n");
845 goto done;
848 hr = SHGetDesktopFolder(&psfDesktop);
849 if (FAILED(hr))
851 WINE_ERR("Couldn't get desktop folder.\n");
852 goto done;
855 hr = SHGetSpecialFolderLocation(NULL, CSIDL_STARTUP, &pidlStartup);
856 if (FAILED(hr))
858 WINE_TRACE("Couldn't get StartUp folder location.\n");
859 goto done;
862 hr = IShellFolder_BindToObject(psfDesktop, pidlStartup, NULL, &IID_IShellFolder, (LPVOID*)&psfStartup);
863 if (FAILED(hr))
865 WINE_TRACE("Couldn't bind IShellFolder to StartUp folder.\n");
866 goto done;
869 hr = IShellFolder_EnumObjects(psfStartup, NULL, SHCONTF_NONFOLDERS | SHCONTF_INCLUDEHIDDEN, &iEnumList);
870 if (FAILED(hr))
872 WINE_TRACE("Unable to enumerate StartUp objects.\n");
873 goto done;
876 while (IEnumIDList_Next(iEnumList, 1, &pidlItem, &NumPIDLs) == S_OK &&
877 (NumPIDLs) == 1)
879 hr = IShellFolder_GetDisplayNameOf(psfStartup, pidlItem, SHGDN_FORPARSING, &strret);
880 if (FAILED(hr))
881 WINE_TRACE("Unable to get display name of enumeration item.\n");
882 else
884 hr = StrRetToBufW(&strret, pidlItem, wszCommand, MAX_PATH);
885 if (FAILED(hr))
886 WINE_TRACE("Unable to parse display name.\n");
887 else
889 HINSTANCE hinst;
891 hinst = ShellExecuteW(NULL, NULL, wszCommand, NULL, NULL, SW_SHOWNORMAL);
892 if (PtrToUlong(hinst) <= 32)
893 WINE_WARN("Error %p executing command %s.\n", hinst, wine_dbgstr_w(wszCommand));
897 IMalloc_Free(ppM, pidlItem);
900 /* Return success */
901 ret = TRUE;
903 done:
904 if (iEnumList) IEnumIDList_Release(iEnumList);
905 if (psfStartup) IShellFolder_Release(psfStartup);
906 if (pidlStartup) IMalloc_Free(ppM, pidlStartup);
908 return ret;
911 static void usage(void)
913 WINE_MESSAGE( "Usage: wineboot [options]\n" );
914 WINE_MESSAGE( "Options;\n" );
915 WINE_MESSAGE( " -h,--help Display this help message\n" );
916 WINE_MESSAGE( " -e,--end-session End the current session cleanly\n" );
917 WINE_MESSAGE( " -f,--force Force exit for processes that don't exit cleanly\n" );
918 WINE_MESSAGE( " -i,--init Perform initialization for first Wine instance\n" );
919 WINE_MESSAGE( " -k,--kill Kill running processes without any cleanup\n" );
920 WINE_MESSAGE( " -r,--restart Restart only, don't do normal startup operations\n" );
921 WINE_MESSAGE( " -s,--shutdown Shutdown only, don't reboot\n" );
922 WINE_MESSAGE( " -u,--update Update the wineprefix directory\n" );
925 static const char short_options[] = "efhikrsu";
927 static const struct option long_options[] =
929 { "help", 0, 0, 'h' },
930 { "end-session", 0, 0, 'e' },
931 { "force", 0, 0, 'f' },
932 { "init" , 0, 0, 'i' },
933 { "kill", 0, 0, 'k' },
934 { "restart", 0, 0, 'r' },
935 { "shutdown", 0, 0, 's' },
936 { "update", 0, 0, 'u' },
937 { NULL, 0, 0, 0 }
940 int main( int argc, char *argv[] )
942 extern HANDLE CDECL __wine_make_process_system(void);
943 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
945 /* First, set the current directory to SystemRoot */
946 int optc;
947 int end_session = 0, force = 0, init = 0, kill = 0, restart = 0, shutdown = 0, update = 0;
948 HANDLE event;
949 SECURITY_ATTRIBUTES sa;
951 GetWindowsDirectoryW( windowsdir, MAX_PATH );
952 if( !SetCurrentDirectoryW( windowsdir ) )
953 WINE_ERR("Cannot set the dir to %s (%d)\n", wine_dbgstr_w(windowsdir), GetLastError() );
955 while ((optc = getopt_long(argc, argv, short_options, long_options, NULL )) != -1)
957 switch(optc)
959 case 'e': end_session = 1; break;
960 case 'f': force = 1; break;
961 case 'i': init = 1; break;
962 case 'k': kill = 1; break;
963 case 'r': restart = 1; break;
964 case 's': shutdown = 1; break;
965 case 'u': update = 1; break;
966 case 'h': usage(); return 0;
967 case '?': usage(); return 1;
971 if (end_session)
973 if (!shutdown_close_windows( force )) return 1;
976 if (kill) kill_processes( shutdown );
978 if (shutdown) return 0;
980 sa.nLength = sizeof(sa);
981 sa.lpSecurityDescriptor = NULL;
982 sa.bInheritHandle = TRUE; /* so that services.exe inherits it */
983 event = CreateEventW( &sa, TRUE, FALSE, wineboot_eventW );
985 ResetEvent( event ); /* in case this is a restart */
987 create_hardware_registry_keys();
988 create_environment_registry_keys();
989 wininit();
990 pendingRename();
992 ProcessWindowsFileProtection();
993 ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICESONCE], TRUE, FALSE );
995 if (init || (kill && !restart))
997 ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICES], FALSE, FALSE );
998 start_services_process();
1000 if (init || update) update_wineprefix( update );
1002 ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNONCE], TRUE, TRUE );
1004 if (!init && !restart)
1006 ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUN], FALSE, FALSE );
1007 ProcessRunKeys( HKEY_CURRENT_USER, runkeys_names[RUNKEY_RUN], FALSE, FALSE );
1008 ProcessStartupItems();
1011 WINE_TRACE("Operation done\n");
1013 SetEvent( event );
1014 return 0;