crypt32: Pass flags to enumeration callback.
[wine/hacks.git] / programs / wineboot / wineboot.c
blob2201ed56dc5e1f16f60acd1880edb2ec779563fa
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 <wine/svcctl.h>
75 #include <wine/unicode.h>
76 #include <wine/library.h>
77 #include <wine/debug.h>
79 #include <shlobj.h>
80 #include <shobjidl.h>
81 #include <shlwapi.h>
82 #include <shellapi.h>
83 #include <setupapi.h>
85 WINE_DEFAULT_DEBUG_CHANNEL(wineboot);
87 #define MAX_LINE_LENGTH (2*MAX_PATH+2)
89 extern BOOL shutdown_close_windows( BOOL force );
90 extern void kill_processes( BOOL kill_desktop );
92 static WCHAR windowsdir[MAX_PATH];
94 /* retrieve the (unix) path to the wine.inf file */
95 static char *get_wine_inf_path(void)
97 const char *build_dir, *data_dir;
98 char *name = NULL;
100 if ((data_dir = wine_get_data_dir()))
102 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(data_dir) + sizeof("/wine.inf") )))
103 return NULL;
104 strcpy( name, data_dir );
105 strcat( name, "/wine.inf" );
107 else if ((build_dir = wine_get_build_dir()))
109 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(build_dir) + sizeof("/tools/wine.inf") )))
110 return NULL;
111 strcpy( name, build_dir );
112 strcat( name, "/tools/wine.inf" );
114 return name;
117 /* update the timestamp if different from the reference time */
118 static BOOL update_timestamp( const char *config_dir, unsigned long timestamp )
120 BOOL ret = FALSE;
121 int fd, count;
122 char buffer[100];
123 char *file = HeapAlloc( GetProcessHeap(), 0, strlen(config_dir) + sizeof("/.update-timestamp") );
125 if (!file) return FALSE;
126 strcpy( file, config_dir );
127 strcat( file, "/.update-timestamp" );
129 if ((fd = open( file, O_RDWR )) != -1)
131 if ((count = read( fd, buffer, sizeof(buffer) - 1 )) >= 0)
133 buffer[count] = 0;
134 if (!strncmp( buffer, "disable", sizeof("disable")-1 )) goto done;
135 if (timestamp == strtoul( buffer, NULL, 10 )) goto done;
137 lseek( fd, 0, SEEK_SET );
138 ftruncate( fd, 0 );
140 else
142 if (errno != ENOENT) goto done;
143 if ((fd = open( file, O_WRONLY | O_CREAT | O_TRUNC, 0666 )) == -1) goto done;
146 count = sprintf( buffer, "%lu\n", timestamp );
147 if (write( fd, buffer, count ) != count)
149 WINE_WARN( "failed to update timestamp in %s\n", file );
150 ftruncate( fd, 0 );
152 else ret = TRUE;
154 done:
155 if (fd != -1) close( fd );
156 HeapFree( GetProcessHeap(), 0, file );
157 return ret;
160 /* Performs the rename operations dictated in %SystemRoot%\Wininit.ini.
161 * Returns FALSE if there was an error, or otherwise if all is ok.
163 static BOOL wininit(void)
165 static const WCHAR nulW[] = {'N','U','L',0};
166 static const WCHAR renameW[] = {'r','e','n','a','m','e',0};
167 static const WCHAR wininitW[] = {'w','i','n','i','n','i','t','.','i','n','i',0};
168 static const WCHAR wininitbakW[] = {'w','i','n','i','n','i','t','.','b','a','k',0};
169 WCHAR initial_buffer[1024];
170 WCHAR *str, *buffer = initial_buffer;
171 DWORD size = sizeof(initial_buffer)/sizeof(WCHAR);
172 DWORD res;
174 for (;;)
176 if (!(res = GetPrivateProfileSectionW( renameW, buffer, size, wininitW ))) return TRUE;
177 if (res < size - 2) break;
178 if (buffer != initial_buffer) HeapFree( GetProcessHeap(), 0, buffer );
179 size *= 2;
180 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return FALSE;
183 for (str = buffer; *str; str += strlenW(str) + 1)
185 WCHAR *value;
187 if (*str == ';') continue; /* comment */
188 if (!(value = strchrW( str, '=' ))) continue;
190 /* split the line into key and value */
191 *value++ = 0;
193 if (!lstrcmpiW( nulW, str ))
195 WINE_TRACE("Deleting file %s\n", wine_dbgstr_w(value) );
196 if( !DeleteFileW( value ) )
197 WINE_WARN("Error deleting file %s\n", wine_dbgstr_w(value) );
199 else
201 WINE_TRACE("Renaming file %s to %s\n", wine_dbgstr_w(value), wine_dbgstr_w(str) );
203 if( !MoveFileExW(value, str, MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) )
204 WINE_WARN("Error renaming %s to %s\n", wine_dbgstr_w(value), wine_dbgstr_w(str) );
206 str = value;
209 if (buffer != initial_buffer) HeapFree( GetProcessHeap(), 0, buffer );
211 if( !MoveFileExW( wininitW, wininitbakW, MOVEFILE_REPLACE_EXISTING) )
213 WINE_ERR("Couldn't rename wininit.ini, error %d\n", GetLastError() );
215 return FALSE;
218 return TRUE;
221 static BOOL pendingRename(void)
223 static const WCHAR ValueName[] = {'P','e','n','d','i','n','g',
224 'F','i','l','e','R','e','n','a','m','e',
225 'O','p','e','r','a','t','i','o','n','s',0};
226 static const WCHAR SessionW[] = { 'S','y','s','t','e','m','\\',
227 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
228 'C','o','n','t','r','o','l','\\',
229 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
230 WCHAR *buffer=NULL;
231 const WCHAR *src=NULL, *dst=NULL;
232 DWORD dataLength=0;
233 HKEY hSession=NULL;
234 DWORD res;
236 WINE_TRACE("Entered\n");
238 if( (res=RegOpenKeyExW( HKEY_LOCAL_MACHINE, SessionW, 0, KEY_ALL_ACCESS, &hSession ))
239 !=ERROR_SUCCESS )
241 WINE_TRACE("The key was not found - skipping\n");
242 return TRUE;
245 res=RegQueryValueExW( hSession, ValueName, NULL, NULL /* The value type does not really interest us, as it is not
246 truly a REG_MULTI_SZ anyways */,
247 NULL, &dataLength );
248 if( res==ERROR_FILE_NOT_FOUND )
250 /* No value - nothing to do. Great! */
251 WINE_TRACE("Value not present - nothing to rename\n");
252 res=TRUE;
253 goto end;
256 if( res!=ERROR_SUCCESS )
258 WINE_ERR("Couldn't query value's length (%d)\n", res );
259 res=FALSE;
260 goto end;
263 buffer=HeapAlloc( GetProcessHeap(),0,dataLength );
264 if( buffer==NULL )
266 WINE_ERR("Couldn't allocate %u bytes for the value\n", dataLength );
267 res=FALSE;
268 goto end;
271 res=RegQueryValueExW( hSession, ValueName, NULL, NULL, (LPBYTE)buffer, &dataLength );
272 if( res!=ERROR_SUCCESS )
274 WINE_ERR("Couldn't query value after successfully querying before (%u),\n"
275 "please report to wine-devel@winehq.org\n", res);
276 res=FALSE;
277 goto end;
280 /* Make sure that the data is long enough and ends with two NULLs. This
281 * simplifies the code later on.
283 if( dataLength<2*sizeof(buffer[0]) ||
284 buffer[dataLength/sizeof(buffer[0])-1]!='\0' ||
285 buffer[dataLength/sizeof(buffer[0])-2]!='\0' )
287 WINE_ERR("Improper value format - doesn't end with NULL\n");
288 res=FALSE;
289 goto end;
292 for( src=buffer; (src-buffer)*sizeof(src[0])<dataLength && *src!='\0';
293 src=dst+lstrlenW(dst)+1 )
295 DWORD dwFlags=0;
297 WINE_TRACE("processing next command\n");
299 dst=src+lstrlenW(src)+1;
301 /* We need to skip the \??\ header */
302 if( src[0]=='\\' && src[1]=='?' && src[2]=='?' && src[3]=='\\' )
303 src+=4;
305 if( dst[0]=='!' )
307 dwFlags|=MOVEFILE_REPLACE_EXISTING;
308 dst++;
311 if( dst[0]=='\\' && dst[1]=='?' && dst[2]=='?' && dst[3]=='\\' )
312 dst+=4;
314 if( *dst!='\0' )
316 /* Rename the file */
317 MoveFileExW( src, dst, dwFlags );
318 } else
320 /* Delete the file or directory */
321 if( (res=GetFileAttributesW(src))!=INVALID_FILE_ATTRIBUTES )
323 if( (res&FILE_ATTRIBUTE_DIRECTORY)==0 )
325 /* It's a file */
326 DeleteFileW(src);
327 } else
329 /* It's a directory */
330 RemoveDirectoryW(src);
332 } else
334 WINE_ERR("couldn't get file attributes (%d)\n", GetLastError() );
339 if((res=RegDeleteValueW(hSession, ValueName))!=ERROR_SUCCESS )
341 WINE_ERR("Error deleting the value (%u)\n", GetLastError() );
342 res=FALSE;
343 } else
344 res=TRUE;
346 end:
347 HeapFree(GetProcessHeap(), 0, buffer);
349 if( hSession!=NULL )
350 RegCloseKey( hSession );
352 return res;
355 enum runkeys {
356 RUNKEY_RUN, RUNKEY_RUNONCE, RUNKEY_RUNSERVICES, RUNKEY_RUNSERVICESONCE
359 const WCHAR runkeys_names[][30]=
361 {'R','u','n',0},
362 {'R','u','n','O','n','c','e',0},
363 {'R','u','n','S','e','r','v','i','c','e','s',0},
364 {'R','u','n','S','e','r','v','i','c','e','s','O','n','c','e',0}
367 #define INVALID_RUNCMD_RETURN -1
369 * This function runs the specified command in the specified dir.
370 * [in,out] cmdline - the command line to run. The function may change the passed buffer.
371 * [in] dir - the dir to run the command in. If it is NULL, then the current dir is used.
372 * [in] wait - whether to wait for the run program to finish before returning.
373 * [in] minimized - Whether to ask the program to run minimized.
375 * Returns:
376 * If running the process failed, returns INVALID_RUNCMD_RETURN. Use GetLastError to get the error code.
377 * If wait is FALSE - returns 0 if successful.
378 * If wait is TRUE - returns the program's return value.
380 static DWORD runCmd(LPWSTR cmdline, LPCWSTR dir, BOOL wait, BOOL minimized)
382 STARTUPINFOW si;
383 PROCESS_INFORMATION info;
384 DWORD exit_code=0;
386 memset(&si, 0, sizeof(si));
387 si.cb=sizeof(si);
388 if( minimized )
390 si.dwFlags=STARTF_USESHOWWINDOW;
391 si.wShowWindow=SW_MINIMIZE;
393 memset(&info, 0, sizeof(info));
395 if( !CreateProcessW(NULL, cmdline, NULL, NULL, FALSE, 0, NULL, dir, &si, &info) )
397 WINE_WARN("Failed to run command %s (%d)\n", wine_dbgstr_w(cmdline), GetLastError() );
398 return INVALID_RUNCMD_RETURN;
401 WINE_TRACE("Successfully ran command %s - Created process handle %p\n",
402 wine_dbgstr_w(cmdline), info.hProcess );
404 if(wait)
405 { /* wait for the process to exit */
406 WaitForSingleObject(info.hProcess, INFINITE);
407 GetExitCodeProcess(info.hProcess, &exit_code);
410 CloseHandle( info.hThread );
411 CloseHandle( info.hProcess );
413 return exit_code;
417 * Process a "Run" type registry key.
418 * hkRoot is the HKEY from which "Software\Microsoft\Windows\CurrentVersion" is
419 * opened.
420 * szKeyName is the key holding the actual entries.
421 * bDelete tells whether we should delete each value right before executing it.
422 * bSynchronous tells whether we should wait for the prog to complete before
423 * going on to the next prog.
425 static BOOL ProcessRunKeys( HKEY hkRoot, LPCWSTR szKeyName, BOOL bDelete,
426 BOOL bSynchronous )
428 static const WCHAR WINKEY_NAME[]={'S','o','f','t','w','a','r','e','\\',
429 'M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\',
430 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
431 HKEY hkWin, hkRun;
432 DWORD res;
433 DWORD i, nMaxCmdLine=0, nMaxValue=0;
434 WCHAR *szCmdLine=NULL;
435 WCHAR *szValue=NULL;
437 if (hkRoot==HKEY_LOCAL_MACHINE)
438 WINE_TRACE("processing %s entries under HKLM\n",wine_dbgstr_w(szKeyName) );
439 else
440 WINE_TRACE("processing %s entries under HKCU\n",wine_dbgstr_w(szKeyName) );
442 if (RegOpenKeyExW( hkRoot, WINKEY_NAME, 0, KEY_READ, &hkWin ) != ERROR_SUCCESS)
443 return TRUE;
445 if (RegOpenKeyExW( hkWin, szKeyName, 0, bDelete?KEY_ALL_ACCESS:KEY_READ, &hkRun ) != ERROR_SUCCESS)
447 RegCloseKey( hkWin );
448 return TRUE;
450 RegCloseKey( hkWin );
452 if( (res=RegQueryInfoKeyW( hkRun, NULL, NULL, NULL, NULL, NULL, NULL, &i, &nMaxValue,
453 &nMaxCmdLine, NULL, NULL ))!=ERROR_SUCCESS )
454 goto end;
456 if( i==0 )
458 WINE_TRACE("No commands to execute.\n");
460 res=ERROR_SUCCESS;
461 goto end;
464 if( (szCmdLine=HeapAlloc(GetProcessHeap(),0,nMaxCmdLine))==NULL )
466 WINE_ERR("Couldn't allocate memory for the commands to be executed\n");
468 res=ERROR_NOT_ENOUGH_MEMORY;
469 goto end;
472 if( (szValue=HeapAlloc(GetProcessHeap(),0,(++nMaxValue)*sizeof(*szValue)))==NULL )
474 WINE_ERR("Couldn't allocate memory for the value names\n");
476 res=ERROR_NOT_ENOUGH_MEMORY;
477 goto end;
480 while( i>0 )
482 DWORD nValLength=nMaxValue, nDataLength=nMaxCmdLine;
483 DWORD type;
485 --i;
487 if( (res=RegEnumValueW( hkRun, i, szValue, &nValLength, 0, &type,
488 (LPBYTE)szCmdLine, &nDataLength ))!=ERROR_SUCCESS )
490 WINE_ERR("Couldn't read in value %d - %d\n", i, res );
492 continue;
495 if( bDelete && (res=RegDeleteValueW( hkRun, szValue ))!=ERROR_SUCCESS )
497 WINE_ERR("Couldn't delete value - %d, %d. Running command anyways.\n", i, res );
500 if( type!=REG_SZ )
502 WINE_ERR("Incorrect type of value #%d (%d)\n", i, type );
504 continue;
507 if( (res=runCmd(szCmdLine, NULL, bSynchronous, FALSE ))==INVALID_RUNCMD_RETURN )
509 WINE_ERR("Error running cmd #%d (%d)\n", i, GetLastError() );
512 WINE_TRACE("Done processing cmd #%d\n", i);
515 res=ERROR_SUCCESS;
517 end:
518 HeapFree( GetProcessHeap(), 0, szValue );
519 HeapFree( GetProcessHeap(), 0, szCmdLine );
521 if( hkRun!=NULL )
522 RegCloseKey( hkRun );
524 WINE_TRACE("done\n");
526 return res==ERROR_SUCCESS;
530 * WFP is Windows File Protection, in NT5 and Windows 2000 it maintains a cache
531 * of known good dlls and scans through and replaces corrupted DLLs with these
532 * known good versions. The only programs that should install into this dll
533 * cache are Windows Updates and IE (which is treated like a Windows Update)
535 * Implementing this allows installing ie in win2k mode to actually install the
536 * system dlls that we expect and need
538 static int ProcessWindowsFileProtection(void)
540 static const WCHAR winlogonW[] = {'S','o','f','t','w','a','r','e','\\',
541 'M','i','c','r','o','s','o','f','t','\\',
542 'W','i','n','d','o','w','s',' ','N','T','\\',
543 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
544 'W','i','n','l','o','g','o','n',0};
545 static const WCHAR cachedirW[] = {'S','F','C','D','l','l','C','a','c','h','e','D','i','r',0};
546 static const WCHAR dllcacheW[] = {'\\','d','l','l','c','a','c','h','e','\\','*',0};
547 static const WCHAR wildcardW[] = {'\\','*',0};
548 WIN32_FIND_DATAW finddata;
549 HANDLE find_handle;
550 BOOL find_rc;
551 DWORD rc;
552 HKEY hkey;
553 LPWSTR dllcache = NULL;
555 if (!RegOpenKeyW( HKEY_LOCAL_MACHINE, winlogonW, &hkey ))
557 DWORD sz = 0;
558 if (!RegQueryValueExW( hkey, cachedirW, 0, NULL, NULL, &sz))
560 sz += sizeof(WCHAR);
561 dllcache = HeapAlloc(GetProcessHeap(),0,sz + sizeof(wildcardW));
562 RegQueryValueExW( hkey, cachedirW, 0, NULL, (LPBYTE)dllcache, &sz);
563 strcatW( dllcache, wildcardW );
566 RegCloseKey(hkey);
568 if (!dllcache)
570 DWORD sz = GetSystemDirectoryW( NULL, 0 );
571 dllcache = HeapAlloc( GetProcessHeap(), 0, sz * sizeof(WCHAR) + sizeof(dllcacheW));
572 GetSystemDirectoryW( dllcache, sz );
573 strcatW( dllcache, dllcacheW );
576 find_handle = FindFirstFileW(dllcache,&finddata);
577 dllcache[ strlenW(dllcache) - 2] = 0; /* strip off wildcard */
578 find_rc = find_handle != INVALID_HANDLE_VALUE;
579 while (find_rc)
581 static const WCHAR dotW[] = {'.',0};
582 static const WCHAR dotdotW[] = {'.','.',0};
583 WCHAR targetpath[MAX_PATH];
584 WCHAR currentpath[MAX_PATH];
585 UINT sz;
586 UINT sz2;
587 WCHAR tempfile[MAX_PATH];
589 if (strcmpW(finddata.cFileName,dotW) == 0 || strcmpW(finddata.cFileName,dotdotW) == 0)
591 find_rc = FindNextFileW(find_handle,&finddata);
592 continue;
595 sz = MAX_PATH;
596 sz2 = MAX_PATH;
597 VerFindFileW(VFFF_ISSHAREDFILE, finddata.cFileName, windowsdir,
598 windowsdir, currentpath, &sz, targetpath, &sz2);
599 sz = MAX_PATH;
600 rc = VerInstallFileW(0, finddata.cFileName, finddata.cFileName,
601 dllcache, targetpath, currentpath, tempfile, &sz);
602 if (rc != ERROR_SUCCESS)
604 WINE_WARN("WFP: %s error 0x%x\n",wine_dbgstr_w(finddata.cFileName),rc);
605 DeleteFileW(tempfile);
608 /* now delete the source file so that we don't try to install it over and over again */
609 lstrcpynW( targetpath, dllcache, MAX_PATH - 1 );
610 sz = strlenW( targetpath );
611 targetpath[sz++] = '\\';
612 lstrcpynW( targetpath + sz, finddata.cFileName, MAX_PATH - sz );
613 if (!DeleteFileW( targetpath ))
614 WINE_WARN( "failed to delete %s: error %u\n", wine_dbgstr_w(targetpath), GetLastError() );
616 find_rc = FindNextFileW(find_handle,&finddata);
618 FindClose(find_handle);
619 HeapFree(GetProcessHeap(),0,dllcache);
620 return 1;
623 static BOOL start_services_process(void)
625 static const WCHAR svcctl_started_event[] = SVCCTL_STARTED_EVENT;
626 static const WCHAR services[] = {'\\','s','e','r','v','i','c','e','s','.','e','x','e',0};
627 PROCESS_INFORMATION pi;
628 STARTUPINFOW si;
629 HANDLE wait_handles[2];
630 WCHAR path[MAX_PATH];
632 if (!GetSystemDirectoryW(path, MAX_PATH - strlenW(services)))
633 return FALSE;
634 strcatW(path, services);
635 ZeroMemory(&si, sizeof(si));
636 si.cb = sizeof(si);
637 if (!CreateProcessW(path, path, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
639 WINE_ERR("Couldn't start services.exe: error %u\n", GetLastError());
640 return FALSE;
642 CloseHandle(pi.hThread);
644 wait_handles[0] = CreateEventW(NULL, TRUE, FALSE, svcctl_started_event);
645 wait_handles[1] = pi.hProcess;
647 /* wait for the event to become available or the process to exit */
648 if ((WaitForMultipleObjects(2, wait_handles, FALSE, INFINITE)) == WAIT_OBJECT_0 + 1)
650 DWORD exit_code;
651 GetExitCodeProcess(pi.hProcess, &exit_code);
652 WINE_ERR("Unexpected termination of services.exe - exit code %d\n", exit_code);
653 CloseHandle(pi.hProcess);
654 CloseHandle(wait_handles[0]);
655 return FALSE;
658 CloseHandle(pi.hProcess);
659 CloseHandle(wait_handles[0]);
660 return TRUE;
663 /* execute rundll32 on the wine.inf file if necessary */
664 static void update_wineprefix( int force )
666 static const WCHAR cmdlineW[] = {'D','e','f','a','u','l','t','I','n','s','t','a','l','l',' ',
667 '1','2','8',' ','\\','\\','?','\\','u','n','i','x' };
669 const char *config_dir = wine_get_config_dir();
670 char *inf_path = get_wine_inf_path();
671 struct stat st;
673 if (!inf_path)
675 WINE_WARN( "cannot find path to wine.inf file\n" );
676 return;
678 if (stat( inf_path, &st ) == -1)
680 WINE_WARN( "cannot stat wine.inf file: %s\n", strerror(errno) );
681 goto done;
684 if (update_timestamp( config_dir, st.st_mtime ) || force)
686 WCHAR *buffer;
687 DWORD len = MultiByteToWideChar( CP_UNIXCP, 0, inf_path, -1, NULL, 0 );
688 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(cmdlineW) + len*sizeof(WCHAR) ))) goto done;
689 memcpy( buffer, cmdlineW, sizeof(cmdlineW) );
690 MultiByteToWideChar( CP_UNIXCP, 0, inf_path, -1, buffer + sizeof(cmdlineW)/sizeof(WCHAR), len );
692 InstallHinfSectionW( 0, 0, buffer, 0 );
693 HeapFree( GetProcessHeap(), 0, buffer );
694 WINE_MESSAGE( "wine: configuration in '%s' has been updated.\n", config_dir );
697 done:
698 HeapFree( GetProcessHeap(), 0, inf_path );
701 /* Process items in the StartUp group of the user's Programs under the Start Menu. Some installers put
702 * shell links here to restart themselves after boot. */
703 static BOOL ProcessStartupItems(void)
705 BOOL ret = FALSE;
706 HRESULT hr;
707 IMalloc *ppM = NULL;
708 IShellFolder *psfDesktop = NULL, *psfStartup = NULL;
709 LPITEMIDLIST pidlStartup = NULL, pidlItem;
710 ULONG NumPIDLs;
711 IEnumIDList *iEnumList = NULL;
712 STRRET strret;
713 WCHAR wszCommand[MAX_PATH];
715 WINE_TRACE("Processing items in the StartUp folder.\n");
717 hr = SHGetMalloc(&ppM);
718 if (FAILED(hr))
720 WINE_ERR("Couldn't get IMalloc object.\n");
721 goto done;
724 hr = SHGetDesktopFolder(&psfDesktop);
725 if (FAILED(hr))
727 WINE_ERR("Couldn't get desktop folder.\n");
728 goto done;
731 hr = SHGetSpecialFolderLocation(NULL, CSIDL_STARTUP, &pidlStartup);
732 if (FAILED(hr))
734 WINE_TRACE("Couldn't get StartUp folder location.\n");
735 goto done;
738 hr = IShellFolder_BindToObject(psfDesktop, pidlStartup, NULL, &IID_IShellFolder, (LPVOID*)&psfStartup);
739 if (FAILED(hr))
741 WINE_TRACE("Couldn't bind IShellFolder to StartUp folder.\n");
742 goto done;
745 hr = IShellFolder_EnumObjects(psfStartup, NULL, SHCONTF_NONFOLDERS | SHCONTF_INCLUDEHIDDEN, &iEnumList);
746 if (FAILED(hr))
748 WINE_TRACE("Unable to enumerate StartUp objects.\n");
749 goto done;
752 while (IEnumIDList_Next(iEnumList, 1, &pidlItem, &NumPIDLs) == S_OK &&
753 (NumPIDLs) == 1)
755 hr = IShellFolder_GetDisplayNameOf(psfStartup, pidlItem, SHGDN_FORPARSING, &strret);
756 if (FAILED(hr))
757 WINE_TRACE("Unable to get display name of enumeration item.\n");
758 else
760 hr = StrRetToBufW(&strret, pidlItem, wszCommand, MAX_PATH);
761 if (FAILED(hr))
762 WINE_TRACE("Unable to parse display name.\n");
763 else
765 HINSTANCE hinst;
767 hinst = ShellExecuteW(NULL, NULL, wszCommand, NULL, NULL, SW_SHOWNORMAL);
768 if (PtrToUlong(hinst) <= 32)
769 WINE_WARN("Error %p executing command %s.\n", hinst, wine_dbgstr_w(wszCommand));
773 IMalloc_Free(ppM, pidlItem);
776 /* Return success */
777 ret = TRUE;
779 done:
780 if (iEnumList) IEnumIDList_Release(iEnumList);
781 if (psfStartup) IShellFolder_Release(psfStartup);
782 if (pidlStartup) IMalloc_Free(ppM, pidlStartup);
784 return ret;
787 static void usage(void)
789 WINE_MESSAGE( "Usage: wineboot [options]\n" );
790 WINE_MESSAGE( "Options;\n" );
791 WINE_MESSAGE( " -h,--help Display this help message\n" );
792 WINE_MESSAGE( " -e,--end-session End the current session cleanly\n" );
793 WINE_MESSAGE( " -f,--force Force exit for processes that don't exit cleanly\n" );
794 WINE_MESSAGE( " -i,--init Perform initialization for first Wine instance\n" );
795 WINE_MESSAGE( " -k,--kill Kill running processes without any cleanup\n" );
796 WINE_MESSAGE( " -r,--restart Restart only, don't do normal startup operations\n" );
797 WINE_MESSAGE( " -s,--shutdown Shutdown only, don't reboot\n" );
798 WINE_MESSAGE( " -u,--update Update the wineprefix directory\n" );
801 static const char short_options[] = "efhikrsu";
803 static const struct option long_options[] =
805 { "help", 0, 0, 'h' },
806 { "end-session", 0, 0, 'e' },
807 { "force", 0, 0, 'f' },
808 { "init" , 0, 0, 'i' },
809 { "kill", 0, 0, 'k' },
810 { "restart", 0, 0, 'r' },
811 { "shutdown", 0, 0, 's' },
812 { "update", 0, 0, 'u' },
813 { NULL, 0, 0, 0 }
816 int main( int argc, char *argv[] )
818 extern HANDLE __wine_make_process_system(void);
819 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
821 /* First, set the current directory to SystemRoot */
822 int optc;
823 int end_session = 0, force = 0, init = 0, kill = 0, restart = 0, shutdown = 0, update = 0;
824 HANDLE event;
825 SECURITY_ATTRIBUTES sa;
827 GetWindowsDirectoryW( windowsdir, MAX_PATH );
828 if( !SetCurrentDirectoryW( windowsdir ) )
829 WINE_ERR("Cannot set the dir to %s (%d)\n", wine_dbgstr_w(windowsdir), GetLastError() );
831 while ((optc = getopt_long(argc, argv, short_options, long_options, NULL )) != -1)
833 switch(optc)
835 case 'e': end_session = kill = 1; break;
836 case 'f': force = 1; break;
837 case 'i': init = 1; break;
838 case 'k': kill = 1; break;
839 case 'r': restart = 1; break;
840 case 's': shutdown = 1; break;
841 case 'u': update = 1; break;
842 case 'h': usage(); return 0;
843 case '?': usage(); return 1;
847 if (end_session)
849 if (!shutdown_close_windows( force )) return 1;
852 if (kill) kill_processes( shutdown );
854 if (shutdown) return 0;
856 sa.nLength = sizeof(sa);
857 sa.lpSecurityDescriptor = NULL;
858 sa.bInheritHandle = TRUE; /* so that services.exe inherits it */
859 event = CreateEventW( &sa, TRUE, FALSE, wineboot_eventW );
861 ResetEvent( event ); /* in case this is a restart */
863 wininit();
864 pendingRename();
866 ProcessWindowsFileProtection();
867 ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICESONCE], TRUE, FALSE );
869 if (init || (kill && !restart))
871 ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICES], FALSE, FALSE );
872 start_services_process();
874 if (init || update) update_wineprefix( update );
876 ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNONCE], TRUE, TRUE );
878 if (!init && !restart)
880 ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUN], FALSE, FALSE );
881 ProcessRunKeys( HKEY_CURRENT_USER, runkeys_names[RUNKEY_RUN], FALSE, FALSE );
882 ProcessStartupItems();
885 WINE_TRACE("Operation done\n");
887 SetEvent( event );
888 return 0;