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, ?semi-synchronous?, not implemented yet)
33 * - HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce (9x, asynch)
34 * - HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServices (9x, asynch)
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)
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).
55 #include "wine/port.h"
57 #define WIN32_LEAN_AND_MEAN
64 #include <wine/debug.h>
72 WINE_DEFAULT_DEBUG_CHANNEL(wineboot);
74 #define MAX_LINE_LENGTH (2*MAX_PATH+2)
76 extern BOOL shutdown_close_windows( BOOL force );
77 extern void kill_processes( BOOL kill_desktop );
79 static BOOL GetLine( HANDLE hFile, char *buf, size_t buflen )
88 if( !ReadFile( hFile, buf, 1, &read, NULL ) || read!=1 )
93 } while( isspace( *buf ) );
95 while( buf[i]!='\n' && i<=buflen &&
96 ReadFile( hFile, buf+i+1, 1, &r, NULL ) )
107 if( i>0 && buf[i-1]=='\r' )
115 /* Performs the rename operations dictated in %SystemRoot%\Wininit.ini.
116 * Returns FALSE if there was an error, or otherwise if all is ok.
118 static BOOL wininit(void)
120 const char * const RENAME_FILE="wininit.ini";
121 const char * const RENAME_FILE_TO="wininit.bak";
122 const char * const RENAME_FILE_SECTION="[rename]";
123 char buffer[MAX_LINE_LENGTH];
127 hFile=CreateFileA(RENAME_FILE, GENERIC_READ,
128 FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
131 if( hFile==INVALID_HANDLE_VALUE )
133 DWORD err=GetLastError();
135 if( err==ERROR_FILE_NOT_FOUND )
137 /* No file - nothing to do. Great! */
138 WINE_TRACE("Wininit.ini not present - no renaming to do\n");
143 WINE_ERR("There was an error in reading wininit.ini file - %d\n",
149 while( GetLine( hFile, buffer, sizeof(buffer) ) &&
150 lstrcmpiA(buffer,RENAME_FILE_SECTION)!=0 )
151 ; /* Read the lines until we match the rename section */
153 while( GetLine( hFile, buffer, sizeof(buffer) ) && buffer[0]!='[' )
155 /* First, make sure this is not a comment */
156 if( buffer[0]!=';' && buffer[0]!='\0' )
160 value=strchr(buffer, '=');
164 WINE_WARN("Line with no \"=\" in it in wininit.ini - %s\n",
168 /* split the line into key and value */
171 if( lstrcmpiA( "NUL", buffer )==0 )
173 WINE_TRACE("Deleting file \"%s\"\n", value );
174 /* A file to delete */
175 if( !DeleteFileA( value ) )
176 WINE_WARN("Error deleting file \"%s\"\n", value);
179 WINE_TRACE("Renaming file \"%s\" to \"%s\"\n", value,
182 if( !MoveFileExA(value, buffer, MOVEFILE_COPY_ALLOWED|
183 MOVEFILE_REPLACE_EXISTING) )
185 WINE_WARN("Error renaming \"%s\" to \"%s\"\n", value,
193 CloseHandle( hFile );
195 if( !MoveFileExA( RENAME_FILE, RENAME_FILE_TO, MOVEFILE_REPLACE_EXISTING) )
197 WINE_ERR("Couldn't rename wininit.ini, error %d\n", GetLastError() );
205 static BOOL pendingRename(void)
207 static const WCHAR ValueName[] = {'P','e','n','d','i','n','g',
208 'F','i','l','e','R','e','n','a','m','e',
209 'O','p','e','r','a','t','i','o','n','s',0};
210 static const WCHAR SessionW[] = { 'S','y','s','t','e','m','\\',
211 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
212 'C','o','n','t','r','o','l','\\',
213 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
215 const WCHAR *src=NULL, *dst=NULL;
220 WINE_TRACE("Entered\n");
222 if( (res=RegOpenKeyExW( HKEY_LOCAL_MACHINE, SessionW, 0, KEY_ALL_ACCESS, &hSession ))
225 if( res==ERROR_FILE_NOT_FOUND )
227 WINE_TRACE("The key was not found - skipping\n");
232 WINE_ERR("Couldn't open key, error %d\n", res );
239 res=RegQueryValueExW( hSession, ValueName, NULL, NULL /* The value type does not really interest us, as it is not
240 truly a REG_MULTI_SZ anyways */,
242 if( res==ERROR_FILE_NOT_FOUND )
244 /* No value - nothing to do. Great! */
245 WINE_TRACE("Value not present - nothing to rename\n");
250 if( res!=ERROR_SUCCESS )
252 WINE_ERR("Couldn't query value's length (%d)\n", res );
257 buffer=HeapAlloc( GetProcessHeap(),0,dataLength );
260 WINE_ERR("Couldn't allocate %u bytes for the value\n", dataLength );
265 res=RegQueryValueExW( hSession, ValueName, NULL, NULL, (LPBYTE)buffer, &dataLength );
266 if( res!=ERROR_SUCCESS )
268 WINE_ERR("Couldn't query value after successfully querying before (%u),\n"
269 "please report to wine-devel@winehq.org\n", res);
274 /* Make sure that the data is long enough and ends with two NULLs. This
275 * simplifies the code later on.
277 if( dataLength<2*sizeof(buffer[0]) ||
278 buffer[dataLength/sizeof(buffer[0])-1]!='\0' ||
279 buffer[dataLength/sizeof(buffer[0])-2]!='\0' )
281 WINE_ERR("Improper value format - doesn't end with NULL\n");
286 for( src=buffer; (src-buffer)*sizeof(src[0])<dataLength && *src!='\0';
287 src=dst+lstrlenW(dst)+1 )
291 WINE_TRACE("processing next command\n");
293 dst=src+lstrlenW(src)+1;
295 /* We need to skip the \??\ header */
296 if( src[0]=='\\' && src[1]=='?' && src[2]=='?' && src[3]=='\\' )
301 dwFlags|=MOVEFILE_REPLACE_EXISTING;
305 if( dst[0]=='\\' && dst[1]=='?' && dst[2]=='?' && dst[3]=='\\' )
310 /* Rename the file */
311 MoveFileExW( src, dst, dwFlags );
314 /* Delete the file or directory */
315 if( (res=GetFileAttributesW(src))!=INVALID_FILE_ATTRIBUTES )
317 if( (res&FILE_ATTRIBUTE_DIRECTORY)==0 )
323 /* It's a directory */
324 RemoveDirectoryW(src);
328 WINE_ERR("couldn't get file attributes (%d)\n", GetLastError() );
333 if((res=RegDeleteValueW(hSession, ValueName))!=ERROR_SUCCESS )
335 WINE_ERR("Error deleting the value (%u)\n", GetLastError() );
341 HeapFree(GetProcessHeap(), 0, buffer);
344 RegCloseKey( hSession );
350 RUNKEY_RUN, RUNKEY_RUNONCE, RUNKEY_RUNSERVICES, RUNKEY_RUNSERVICESONCE
353 const WCHAR runkeys_names[][30]=
356 {'R','u','n','O','n','c','e',0},
357 {'R','u','n','S','e','r','v','i','c','e','s',0},
358 {'R','u','n','S','e','r','v','i','c','e','s','O','n','c','e',0}
361 #define INVALID_RUNCMD_RETURN -1
363 * This function runs the specified command in the specified dir.
364 * [in,out] cmdline - the command line to run. The function may change the passed buffer.
365 * [in] dir - the dir to run the command in. If it is NULL, then the current dir is used.
366 * [in] wait - whether to wait for the run program to finish before returning.
367 * [in] minimized - Whether to ask the program to run minimized.
370 * If running the process failed, returns INVALID_RUNCMD_RETURN. Use GetLastError to get the error code.
371 * If wait is FALSE - returns 0 if successful.
372 * If wait is TRUE - returns the program's return value.
374 static DWORD runCmd(LPWSTR cmdline, LPCWSTR dir, BOOL wait, BOOL minimized)
377 PROCESS_INFORMATION info;
380 memset(&si, 0, sizeof(si));
384 si.dwFlags=STARTF_USESHOWWINDOW;
385 si.wShowWindow=SW_MINIMIZE;
387 memset(&info, 0, sizeof(info));
389 if( !CreateProcessW(NULL, cmdline, NULL, NULL, FALSE, 0, NULL, dir, &si, &info) )
391 WINE_ERR("Failed to run command %s (%d)\n", wine_dbgstr_w(cmdline),
394 return INVALID_RUNCMD_RETURN;
397 WINE_TRACE("Successfully ran command %s - Created process handle %p\n",
398 wine_dbgstr_w(cmdline), info.hProcess );
401 { /* wait for the process to exit */
402 WaitForSingleObject(info.hProcess, INFINITE);
403 GetExitCodeProcess(info.hProcess, &exit_code);
406 CloseHandle( info.hProcess );
412 * Process a "Run" type registry key.
413 * hkRoot is the HKEY from which "Software\Microsoft\Windows\CurrentVersion" is
415 * szKeyName is the key holding the actual entries.
416 * bDelete tells whether we should delete each value right before executing it.
417 * bSynchronous tells whether we should wait for the prog to complete before
418 * going on to the next prog.
420 static BOOL ProcessRunKeys( HKEY hkRoot, LPCWSTR szKeyName, BOOL bDelete,
423 static const WCHAR WINKEY_NAME[]={'S','o','f','t','w','a','r','e','\\',
424 'M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\',
425 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
426 HKEY hkWin=NULL, hkRun=NULL;
427 DWORD res=ERROR_SUCCESS;
428 DWORD i, nMaxCmdLine=0, nMaxValue=0;
429 WCHAR *szCmdLine=NULL;
432 if (hkRoot==HKEY_LOCAL_MACHINE)
433 WINE_TRACE("processing %s entries under HKLM\n",wine_dbgstr_w(szKeyName) );
435 WINE_TRACE("processing %s entries under HKCU\n",wine_dbgstr_w(szKeyName) );
437 if( (res=RegOpenKeyExW( hkRoot, WINKEY_NAME, 0, KEY_READ, &hkWin ))!=ERROR_SUCCESS )
439 WINE_ERR("RegOpenKey failed on Software\\Microsoft\\Windows\\CurrentVersion (%d)\n",
445 if( (res=RegOpenKeyExW( hkWin, szKeyName, 0, bDelete?KEY_ALL_ACCESS:KEY_READ, &hkRun ))!=
448 if( res==ERROR_FILE_NOT_FOUND )
450 WINE_TRACE("Key doesn't exist - nothing to be done\n");
455 WINE_ERR("RegOpenKey failed on run key (%d)\n", res);
460 if( (res=RegQueryInfoKeyW( hkRun, NULL, NULL, NULL, NULL, NULL, NULL, &i, &nMaxValue,
461 &nMaxCmdLine, NULL, NULL ))!=ERROR_SUCCESS )
463 WINE_ERR("Couldn't query key info (%d)\n", res );
470 WINE_TRACE("No commands to execute.\n");
476 if( (szCmdLine=HeapAlloc(GetProcessHeap(),0,nMaxCmdLine))==NULL )
478 WINE_ERR("Couldn't allocate memory for the commands to be executed\n");
480 res=ERROR_NOT_ENOUGH_MEMORY;
484 if( (szValue=HeapAlloc(GetProcessHeap(),0,(++nMaxValue)*sizeof(*szValue)))==NULL )
486 WINE_ERR("Couldn't allocate memory for the value names\n");
488 res=ERROR_NOT_ENOUGH_MEMORY;
494 DWORD nValLength=nMaxValue, nDataLength=nMaxCmdLine;
499 if( (res=RegEnumValueW( hkRun, i, szValue, &nValLength, 0, &type,
500 (LPBYTE)szCmdLine, &nDataLength ))!=ERROR_SUCCESS )
502 WINE_ERR("Couldn't read in value %d - %d\n", i, res );
507 if( bDelete && (res=RegDeleteValueW( hkRun, szValue ))!=ERROR_SUCCESS )
509 WINE_ERR("Couldn't delete value - %d, %d. Running command anyways.\n", i, res );
514 WINE_ERR("Incorrect type of value #%d (%d)\n", i, type );
519 if( (res=runCmd(szCmdLine, NULL, bSynchronous, FALSE ))==INVALID_RUNCMD_RETURN )
521 WINE_ERR("Error running cmd #%d (%d)\n", i, GetLastError() );
524 WINE_TRACE("Done processing cmd #%d\n", i);
530 HeapFree( GetProcessHeap(), 0, szValue );
531 HeapFree( GetProcessHeap(), 0, szCmdLine );
534 RegCloseKey( hkRun );
536 RegCloseKey( hkWin );
538 WINE_TRACE("done\n");
540 return res==ERROR_SUCCESS?TRUE:FALSE;
544 * WFP is Windows File Protection, in NT5 and Windows 2000 it maintains a cache
545 * of known good dlls and scans through and replaces corrupted DLLs with these
546 * known good versions. The only programs that should install into this dll
547 * cache are Windows Updates and IE (which is treated like a Windows Update)
549 * Implementing this allows installing ie in win2k mode to actaully install the
550 * system dlls that we expect and need
552 static int ProcessWindowsFileProtection(void)
554 WIN32_FIND_DATA finddata;
555 LPSTR custom_dllcache = NULL;
556 static CHAR default_dllcache[] = "C:\\Windows\\System32\\dllcache";
562 CHAR find_string[MAX_PATH];
563 CHAR windowsdir[MAX_PATH];
565 rc = RegOpenKeyA( HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", &hkey );
566 if (rc == ERROR_SUCCESS)
569 rc = RegQueryValueEx( hkey, "SFCDllCacheDir", 0, NULL, NULL, &sz);
570 if (rc == ERROR_MORE_DATA)
573 custom_dllcache = HeapAlloc(GetProcessHeap(),0,sz);
574 RegQueryValueEx( hkey, "SFCDllCacheDir", 0, NULL, (LPBYTE)custom_dllcache, &sz);
580 dllcache = custom_dllcache;
582 dllcache = default_dllcache;
584 strcpy(find_string,dllcache);
585 strcat(find_string,"\\*.*");
587 GetWindowsDirectory(windowsdir,MAX_PATH);
589 find_handle = FindFirstFile(find_string,&finddata);
590 find_rc = find_handle != INVALID_HANDLE_VALUE;
593 CHAR targetpath[MAX_PATH];
594 CHAR currentpath[MAX_PATH];
597 CHAR tempfile[MAX_PATH];
599 if (strcmp(finddata.cFileName,".") == 0 ||
600 strcmp(finddata.cFileName,"..") == 0)
602 find_rc = FindNextFile(find_handle,&finddata);
608 VerFindFile(VFFF_ISSHAREDFILE, finddata.cFileName, windowsdir,
609 windowsdir, currentpath, &sz, targetpath,&sz2);
611 rc = VerInstallFile(0, finddata.cFileName, finddata.cFileName,
612 dllcache, targetpath, currentpath, tempfile,&sz);
613 if (rc != ERROR_SUCCESS)
615 WINE_ERR("WFP: %s error 0x%x\n",finddata.cFileName,rc);
616 DeleteFile(tempfile);
618 find_rc = FindNextFile(find_handle,&finddata);
620 FindClose(find_handle);
621 HeapFree(GetProcessHeap(),0,custom_dllcache);
625 /* Process items in the StartUp group of the user's Programs under the Start Menu. Some installers put
626 * shell links here to restart themselves after boot. */
627 static BOOL ProcessStartupItems(void)
633 IShellFolder *psfDesktop = NULL, *psfStartup = NULL;
634 LPITEMIDLIST pidlStartup = NULL, pidlItem;
636 IEnumIDList *iEnumList = NULL;
638 WCHAR wszCommand[MAX_PATH];
640 WINE_TRACE("Processing items in the StartUp folder.\n");
642 hr = SHGetMalloc(&ppM);
645 WINE_ERR("Couldn't get IMalloc object.\n");
649 hr = SHGetDesktopFolder(&psfDesktop);
652 WINE_ERR("Couldn't get desktop folder.\n");
656 hr = SHGetSpecialFolderLocation(NULL, CSIDL_STARTUP, &pidlStartup);
659 WINE_TRACE("Couldn't get StartUp folder location.\n");
663 hr = IShellFolder_BindToObject(psfDesktop, pidlStartup, NULL, &IID_IShellFolder, (LPVOID*)&psfStartup);
666 WINE_TRACE("Couldn't bind IShellFolder to StartUp folder.\n");
670 hr = IShellFolder_EnumObjects(psfStartup, NULL, SHCONTF_NONFOLDERS | SHCONTF_INCLUDEHIDDEN, &iEnumList);
673 WINE_TRACE("Unable to enumerate StartUp objects.\n");
677 while (IEnumIDList_Next(iEnumList, 1, &pidlItem, &NumPIDLs) == S_OK &&
680 hr = IShellFolder_GetDisplayNameOf(psfStartup, pidlItem, SHGDN_FORPARSING, &strret);
682 WINE_TRACE("Unable to get display name of enumeration item.\n");
685 hr = StrRetToBufW(&strret, pidlItem, wszCommand, MAX_PATH);
687 WINE_TRACE("Unable to parse display name.\n");
689 if ((iRet = (int)ShellExecuteW(NULL, NULL, wszCommand, NULL, NULL, SW_SHOWNORMAL)) <= 32)
690 WINE_ERR("Error %d executing command %s.\n", iRet, wine_dbgstr_w(wszCommand));
693 IMalloc_Free(ppM, pidlItem);
700 if (iEnumList) IEnumIDList_Release(iEnumList);
701 if (psfStartup) IShellFolder_Release(psfStartup);
702 if (pidlStartup) IMalloc_Free(ppM, pidlStartup);
707 static void usage(void)
709 WINE_MESSAGE( "Usage: wineboot [options]\n" );
710 WINE_MESSAGE( "Options;\n" );
711 WINE_MESSAGE( " -h,--help Display this help message\n" );
712 WINE_MESSAGE( " -e,--end-session End the current session cleanly\n" );
713 WINE_MESSAGE( " -f,--force Force exit for processes that don't exit cleanly\n" );
714 WINE_MESSAGE( " -k,--kill Kill running processes without any cleanup\n" );
715 WINE_MESSAGE( " -r,--restart Restart only, don't do normal startup operations\n" );
716 WINE_MESSAGE( " -s,--shutdown Shutdown only, don't reboot\n" );
719 static const char short_options[] = "efhkrs";
721 static const struct option long_options[] =
723 { "help", 0, 0, 'h' },
724 { "end-session", 0, 0, 'e' },
725 { "force", 0, 0, 'f' },
726 { "kill", 0, 0, 'k' },
727 { "restart", 0, 0, 'r' },
728 { "shutdown", 0, 0, 's' },
732 int main( int argc, char *argv[] )
734 /* First, set the current directory to SystemRoot */
735 TCHAR gen_path[MAX_PATH];
738 int end_session = 0, force = 0, kill = 0, restart = 0, shutdown = 0;
740 res=GetWindowsDirectory( gen_path, sizeof(gen_path) );
744 WINE_ERR("Couldn't get the windows directory - error %d\n",
750 if( res>=sizeof(gen_path) )
752 WINE_ERR("Windows path too long (%d)\n", res );
757 if( !SetCurrentDirectory( gen_path ) )
759 WINE_ERR("Cannot set the dir to %s (%d)\n", gen_path, GetLastError() );
765 while ((optc = getopt_long(argc, argv, short_options, long_options, NULL )) != -1)
769 case 'e': end_session = 1; break;
770 case 'f': force = 1; break;
771 case 'k': kill = 1; break;
772 case 'r': restart = 1; break;
773 case 's': shutdown = 1; break;
774 case 'h': usage(); return 0;
775 case '?': usage(); return 1;
781 if (!shutdown_close_windows( force )) return 1;
784 if (end_session || kill) kill_processes( shutdown );
786 if (shutdown) return 0;
791 ProcessWindowsFileProtection();
792 ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICESONCE], TRUE, FALSE );
793 if (!restart) ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICES], FALSE, FALSE );
794 ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNONCE], TRUE, TRUE );
797 ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUN], FALSE, FALSE );
798 ProcessRunKeys( HKEY_CURRENT_USER, runkeys_names[RUNKEY_RUN], FALSE, FALSE );
799 ProcessStartupItems();
802 WINE_TRACE("Operation done\n");