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)
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/unicode.h>
65 #include <wine/debug.h>
73 WINE_DEFAULT_DEBUG_CHANNEL(wineboot);
75 #define MAX_LINE_LENGTH (2*MAX_PATH+2)
77 extern BOOL shutdown_close_windows( BOOL force );
78 extern void kill_processes( BOOL kill_desktop );
81 /* Performs the rename operations dictated in %SystemRoot%\Wininit.ini.
82 * Returns FALSE if there was an error, or otherwise if all is ok.
84 static BOOL wininit(void)
86 static const WCHAR nulW[] = {'N','U','L',0};
87 static const WCHAR renameW[] = {'r','e','n','a','m','e',0};
88 static const WCHAR wininitW[] = {'w','i','n','i','n','i','t','.','i','n','i',0};
89 static const WCHAR wininitbakW[] = {'w','i','n','i','n','i','t','.','b','a','k',0};
90 WCHAR initial_buffer[1024];
91 WCHAR *str, *buffer = initial_buffer;
92 DWORD size = sizeof(initial_buffer)/sizeof(WCHAR);
97 if (!(res = GetPrivateProfileSectionW( renameW, buffer, size, wininitW ))) return TRUE;
98 if (res < size - 2) break;
99 if (buffer != initial_buffer) HeapFree( GetProcessHeap(), 0, buffer );
101 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return FALSE;
104 for (str = buffer; *str; str += strlenW(str) + 1)
108 if (*str == ';') continue; /* comment */
109 if (!(value = strchrW( str, '=' ))) continue;
111 /* split the line into key and value */
114 if (!lstrcmpiW( nulW, str ))
116 WINE_TRACE("Deleting file %s\n", wine_dbgstr_w(value) );
117 if( !DeleteFileW( value ) )
118 WINE_WARN("Error deleting file %s\n", wine_dbgstr_w(value) );
122 WINE_TRACE("Renaming file %s to %s\n", wine_dbgstr_w(value), wine_dbgstr_w(str) );
124 if( !MoveFileExW(value, str, MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) )
125 WINE_WARN("Error renaming %s to %s\n", wine_dbgstr_w(value), wine_dbgstr_w(str) );
130 if (buffer != initial_buffer) HeapFree( GetProcessHeap(), 0, buffer );
132 if( !MoveFileExW( wininitW, wininitbakW, MOVEFILE_REPLACE_EXISTING) )
134 WINE_ERR("Couldn't rename wininit.ini, error %d\n", GetLastError() );
142 static BOOL pendingRename(void)
144 static const WCHAR ValueName[] = {'P','e','n','d','i','n','g',
145 'F','i','l','e','R','e','n','a','m','e',
146 'O','p','e','r','a','t','i','o','n','s',0};
147 static const WCHAR SessionW[] = { 'S','y','s','t','e','m','\\',
148 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
149 'C','o','n','t','r','o','l','\\',
150 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
152 const WCHAR *src=NULL, *dst=NULL;
157 WINE_TRACE("Entered\n");
159 if( (res=RegOpenKeyExW( HKEY_LOCAL_MACHINE, SessionW, 0, KEY_ALL_ACCESS, &hSession ))
162 if( res==ERROR_FILE_NOT_FOUND )
164 WINE_TRACE("The key was not found - skipping\n");
169 WINE_ERR("Couldn't open key, error %d\n", res );
176 res=RegQueryValueExW( hSession, ValueName, NULL, NULL /* The value type does not really interest us, as it is not
177 truly a REG_MULTI_SZ anyways */,
179 if( res==ERROR_FILE_NOT_FOUND )
181 /* No value - nothing to do. Great! */
182 WINE_TRACE("Value not present - nothing to rename\n");
187 if( res!=ERROR_SUCCESS )
189 WINE_ERR("Couldn't query value's length (%d)\n", res );
194 buffer=HeapAlloc( GetProcessHeap(),0,dataLength );
197 WINE_ERR("Couldn't allocate %u bytes for the value\n", dataLength );
202 res=RegQueryValueExW( hSession, ValueName, NULL, NULL, (LPBYTE)buffer, &dataLength );
203 if( res!=ERROR_SUCCESS )
205 WINE_ERR("Couldn't query value after successfully querying before (%u),\n"
206 "please report to wine-devel@winehq.org\n", res);
211 /* Make sure that the data is long enough and ends with two NULLs. This
212 * simplifies the code later on.
214 if( dataLength<2*sizeof(buffer[0]) ||
215 buffer[dataLength/sizeof(buffer[0])-1]!='\0' ||
216 buffer[dataLength/sizeof(buffer[0])-2]!='\0' )
218 WINE_ERR("Improper value format - doesn't end with NULL\n");
223 for( src=buffer; (src-buffer)*sizeof(src[0])<dataLength && *src!='\0';
224 src=dst+lstrlenW(dst)+1 )
228 WINE_TRACE("processing next command\n");
230 dst=src+lstrlenW(src)+1;
232 /* We need to skip the \??\ header */
233 if( src[0]=='\\' && src[1]=='?' && src[2]=='?' && src[3]=='\\' )
238 dwFlags|=MOVEFILE_REPLACE_EXISTING;
242 if( dst[0]=='\\' && dst[1]=='?' && dst[2]=='?' && dst[3]=='\\' )
247 /* Rename the file */
248 MoveFileExW( src, dst, dwFlags );
251 /* Delete the file or directory */
252 if( (res=GetFileAttributesW(src))!=INVALID_FILE_ATTRIBUTES )
254 if( (res&FILE_ATTRIBUTE_DIRECTORY)==0 )
260 /* It's a directory */
261 RemoveDirectoryW(src);
265 WINE_ERR("couldn't get file attributes (%d)\n", GetLastError() );
270 if((res=RegDeleteValueW(hSession, ValueName))!=ERROR_SUCCESS )
272 WINE_ERR("Error deleting the value (%u)\n", GetLastError() );
278 HeapFree(GetProcessHeap(), 0, buffer);
281 RegCloseKey( hSession );
287 RUNKEY_RUN, RUNKEY_RUNONCE, RUNKEY_RUNSERVICES, RUNKEY_RUNSERVICESONCE
290 const WCHAR runkeys_names[][30]=
293 {'R','u','n','O','n','c','e',0},
294 {'R','u','n','S','e','r','v','i','c','e','s',0},
295 {'R','u','n','S','e','r','v','i','c','e','s','O','n','c','e',0}
298 #define INVALID_RUNCMD_RETURN -1
300 * This function runs the specified command in the specified dir.
301 * [in,out] cmdline - the command line to run. The function may change the passed buffer.
302 * [in] dir - the dir to run the command in. If it is NULL, then the current dir is used.
303 * [in] wait - whether to wait for the run program to finish before returning.
304 * [in] minimized - Whether to ask the program to run minimized.
307 * If running the process failed, returns INVALID_RUNCMD_RETURN. Use GetLastError to get the error code.
308 * If wait is FALSE - returns 0 if successful.
309 * If wait is TRUE - returns the program's return value.
311 static DWORD runCmd(LPWSTR cmdline, LPCWSTR dir, BOOL wait, BOOL minimized)
314 PROCESS_INFORMATION info;
317 memset(&si, 0, sizeof(si));
321 si.dwFlags=STARTF_USESHOWWINDOW;
322 si.wShowWindow=SW_MINIMIZE;
324 memset(&info, 0, sizeof(info));
326 if( !CreateProcessW(NULL, cmdline, NULL, NULL, FALSE, 0, NULL, dir, &si, &info) )
328 WINE_ERR("Failed to run command %s (%d)\n", wine_dbgstr_w(cmdline),
331 return INVALID_RUNCMD_RETURN;
334 WINE_TRACE("Successfully ran command %s - Created process handle %p\n",
335 wine_dbgstr_w(cmdline), info.hProcess );
338 { /* wait for the process to exit */
339 WaitForSingleObject(info.hProcess, INFINITE);
340 GetExitCodeProcess(info.hProcess, &exit_code);
343 CloseHandle( info.hProcess );
349 * Process a "Run" type registry key.
350 * hkRoot is the HKEY from which "Software\Microsoft\Windows\CurrentVersion" is
352 * szKeyName is the key holding the actual entries.
353 * bDelete tells whether we should delete each value right before executing it.
354 * bSynchronous tells whether we should wait for the prog to complete before
355 * going on to the next prog.
357 static BOOL ProcessRunKeys( HKEY hkRoot, LPCWSTR szKeyName, BOOL bDelete,
360 static const WCHAR WINKEY_NAME[]={'S','o','f','t','w','a','r','e','\\',
361 'M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\',
362 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
363 HKEY hkWin=NULL, hkRun=NULL;
364 DWORD res=ERROR_SUCCESS;
365 DWORD i, nMaxCmdLine=0, nMaxValue=0;
366 WCHAR *szCmdLine=NULL;
369 if (hkRoot==HKEY_LOCAL_MACHINE)
370 WINE_TRACE("processing %s entries under HKLM\n",wine_dbgstr_w(szKeyName) );
372 WINE_TRACE("processing %s entries under HKCU\n",wine_dbgstr_w(szKeyName) );
374 if( (res=RegOpenKeyExW( hkRoot, WINKEY_NAME, 0, KEY_READ, &hkWin ))!=ERROR_SUCCESS )
376 WINE_ERR("RegOpenKey failed on Software\\Microsoft\\Windows\\CurrentVersion (%d)\n",
382 if( (res=RegOpenKeyExW( hkWin, szKeyName, 0, bDelete?KEY_ALL_ACCESS:KEY_READ, &hkRun ))!=
385 if( res==ERROR_FILE_NOT_FOUND )
387 WINE_TRACE("Key doesn't exist - nothing to be done\n");
392 WINE_ERR("RegOpenKey failed on run key (%d)\n", res);
397 if( (res=RegQueryInfoKeyW( hkRun, NULL, NULL, NULL, NULL, NULL, NULL, &i, &nMaxValue,
398 &nMaxCmdLine, NULL, NULL ))!=ERROR_SUCCESS )
400 WINE_ERR("Couldn't query key info (%d)\n", res );
407 WINE_TRACE("No commands to execute.\n");
413 if( (szCmdLine=HeapAlloc(GetProcessHeap(),0,nMaxCmdLine))==NULL )
415 WINE_ERR("Couldn't allocate memory for the commands to be executed\n");
417 res=ERROR_NOT_ENOUGH_MEMORY;
421 if( (szValue=HeapAlloc(GetProcessHeap(),0,(++nMaxValue)*sizeof(*szValue)))==NULL )
423 WINE_ERR("Couldn't allocate memory for the value names\n");
425 res=ERROR_NOT_ENOUGH_MEMORY;
431 DWORD nValLength=nMaxValue, nDataLength=nMaxCmdLine;
436 if( (res=RegEnumValueW( hkRun, i, szValue, &nValLength, 0, &type,
437 (LPBYTE)szCmdLine, &nDataLength ))!=ERROR_SUCCESS )
439 WINE_ERR("Couldn't read in value %d - %d\n", i, res );
444 if( bDelete && (res=RegDeleteValueW( hkRun, szValue ))!=ERROR_SUCCESS )
446 WINE_ERR("Couldn't delete value - %d, %d. Running command anyways.\n", i, res );
451 WINE_ERR("Incorrect type of value #%d (%d)\n", i, type );
456 if( (res=runCmd(szCmdLine, NULL, bSynchronous, FALSE ))==INVALID_RUNCMD_RETURN )
458 WINE_ERR("Error running cmd #%d (%d)\n", i, GetLastError() );
461 WINE_TRACE("Done processing cmd #%d\n", i);
467 HeapFree( GetProcessHeap(), 0, szValue );
468 HeapFree( GetProcessHeap(), 0, szCmdLine );
471 RegCloseKey( hkRun );
473 RegCloseKey( hkWin );
475 WINE_TRACE("done\n");
477 return res==ERROR_SUCCESS?TRUE:FALSE;
481 * WFP is Windows File Protection, in NT5 and Windows 2000 it maintains a cache
482 * of known good dlls and scans through and replaces corrupted DLLs with these
483 * known good versions. The only programs that should install into this dll
484 * cache are Windows Updates and IE (which is treated like a Windows Update)
486 * Implementing this allows installing ie in win2k mode to actaully install the
487 * system dlls that we expect and need
489 static int ProcessWindowsFileProtection(void)
491 WIN32_FIND_DATA finddata;
492 LPSTR custom_dllcache = NULL;
493 static CHAR default_dllcache[] = "C:\\Windows\\System32\\dllcache";
499 CHAR find_string[MAX_PATH];
500 CHAR windowsdir[MAX_PATH];
502 rc = RegOpenKeyA( HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", &hkey );
503 if (rc == ERROR_SUCCESS)
506 rc = RegQueryValueEx( hkey, "SFCDllCacheDir", 0, NULL, NULL, &sz);
507 if (rc == ERROR_MORE_DATA)
510 custom_dllcache = HeapAlloc(GetProcessHeap(),0,sz);
511 RegQueryValueEx( hkey, "SFCDllCacheDir", 0, NULL, (LPBYTE)custom_dllcache, &sz);
517 dllcache = custom_dllcache;
519 dllcache = default_dllcache;
521 strcpy(find_string,dllcache);
522 strcat(find_string,"\\*.*");
524 GetWindowsDirectory(windowsdir,MAX_PATH);
526 find_handle = FindFirstFile(find_string,&finddata);
527 find_rc = find_handle != INVALID_HANDLE_VALUE;
530 CHAR targetpath[MAX_PATH];
531 CHAR currentpath[MAX_PATH];
534 CHAR tempfile[MAX_PATH];
536 if (strcmp(finddata.cFileName,".") == 0 ||
537 strcmp(finddata.cFileName,"..") == 0)
539 find_rc = FindNextFile(find_handle,&finddata);
545 VerFindFile(VFFF_ISSHAREDFILE, finddata.cFileName, windowsdir,
546 windowsdir, currentpath, &sz, targetpath,&sz2);
548 rc = VerInstallFile(0, finddata.cFileName, finddata.cFileName,
549 dllcache, targetpath, currentpath, tempfile,&sz);
550 if (rc != ERROR_SUCCESS)
552 WINE_ERR("WFP: %s error 0x%x\n",finddata.cFileName,rc);
553 DeleteFile(tempfile);
555 find_rc = FindNextFile(find_handle,&finddata);
557 FindClose(find_handle);
558 HeapFree(GetProcessHeap(),0,custom_dllcache);
563 static void start_services(void)
565 static const WCHAR servicesW[] = {'S','y','s','t','e','m','\\',
566 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
567 'S','e','r','v','i','c','e','s',0};
568 static const WCHAR startW[] = {'S','t','a','r','t',0};
570 DWORD type, size, start, index = 0;
571 WCHAR name[MAX_PATH];
574 if (RegOpenKeyW( HKEY_LOCAL_MACHINE, servicesW, &hkey )) return;
576 if (!(manager = OpenSCManagerW( NULL, NULL, SC_MANAGER_ALL_ACCESS )))
582 while (!RegEnumKeyW( hkey, index++, name, sizeof(name) ))
584 if (RegOpenKeyW( hkey, name, &skey )) continue;
585 size = sizeof(start);
586 if (!RegQueryValueExW( skey, startW, NULL, &type, (LPBYTE)&start, &size ) && type == REG_DWORD)
588 if (start == SERVICE_BOOT_START ||
589 start == SERVICE_SYSTEM_START ||
590 start == SERVICE_AUTO_START)
592 SC_HANDLE handle = OpenServiceW( manager, name, SERVICE_ALL_ACCESS );
595 WINE_TRACE( "starting service %s start %u\n", wine_dbgstr_w(name), start );
596 StartServiceW( handle, 0, NULL );
597 CloseServiceHandle( handle );
603 CloseServiceHandle( manager );
607 /* Process items in the StartUp group of the user's Programs under the Start Menu. Some installers put
608 * shell links here to restart themselves after boot. */
609 static BOOL ProcessStartupItems(void)
615 IShellFolder *psfDesktop = NULL, *psfStartup = NULL;
616 LPITEMIDLIST pidlStartup = NULL, pidlItem;
618 IEnumIDList *iEnumList = NULL;
620 WCHAR wszCommand[MAX_PATH];
622 WINE_TRACE("Processing items in the StartUp folder.\n");
624 hr = SHGetMalloc(&ppM);
627 WINE_ERR("Couldn't get IMalloc object.\n");
631 hr = SHGetDesktopFolder(&psfDesktop);
634 WINE_ERR("Couldn't get desktop folder.\n");
638 hr = SHGetSpecialFolderLocation(NULL, CSIDL_STARTUP, &pidlStartup);
641 WINE_TRACE("Couldn't get StartUp folder location.\n");
645 hr = IShellFolder_BindToObject(psfDesktop, pidlStartup, NULL, &IID_IShellFolder, (LPVOID*)&psfStartup);
648 WINE_TRACE("Couldn't bind IShellFolder to StartUp folder.\n");
652 hr = IShellFolder_EnumObjects(psfStartup, NULL, SHCONTF_NONFOLDERS | SHCONTF_INCLUDEHIDDEN, &iEnumList);
655 WINE_TRACE("Unable to enumerate StartUp objects.\n");
659 while (IEnumIDList_Next(iEnumList, 1, &pidlItem, &NumPIDLs) == S_OK &&
662 hr = IShellFolder_GetDisplayNameOf(psfStartup, pidlItem, SHGDN_FORPARSING, &strret);
664 WINE_TRACE("Unable to get display name of enumeration item.\n");
667 hr = StrRetToBufW(&strret, pidlItem, wszCommand, MAX_PATH);
669 WINE_TRACE("Unable to parse display name.\n");
671 if ((iRet = (int)ShellExecuteW(NULL, NULL, wszCommand, NULL, NULL, SW_SHOWNORMAL)) <= 32)
672 WINE_ERR("Error %d executing command %s.\n", iRet, wine_dbgstr_w(wszCommand));
675 IMalloc_Free(ppM, pidlItem);
682 if (iEnumList) IEnumIDList_Release(iEnumList);
683 if (psfStartup) IShellFolder_Release(psfStartup);
684 if (pidlStartup) IMalloc_Free(ppM, pidlStartup);
689 static void usage(void)
691 WINE_MESSAGE( "Usage: wineboot [options]\n" );
692 WINE_MESSAGE( "Options;\n" );
693 WINE_MESSAGE( " -h,--help Display this help message\n" );
694 WINE_MESSAGE( " -e,--end-session End the current session cleanly\n" );
695 WINE_MESSAGE( " -f,--force Force exit for processes that don't exit cleanly\n" );
696 WINE_MESSAGE( " -k,--kill Kill running processes without any cleanup\n" );
697 WINE_MESSAGE( " -r,--restart Restart only, don't do normal startup operations\n" );
698 WINE_MESSAGE( " -s,--shutdown Shutdown only, don't reboot\n" );
701 static const char short_options[] = "efhkrs";
703 static const struct option long_options[] =
705 { "help", 0, 0, 'h' },
706 { "end-session", 0, 0, 'e' },
707 { "force", 0, 0, 'f' },
708 { "kill", 0, 0, 'k' },
709 { "restart", 0, 0, 'r' },
710 { "shutdown", 0, 0, 's' },
714 int main( int argc, char *argv[] )
716 /* First, set the current directory to SystemRoot */
717 TCHAR gen_path[MAX_PATH];
720 int end_session = 0, force = 0, kill = 0, restart = 0, shutdown = 0;
722 res=GetWindowsDirectory( gen_path, sizeof(gen_path) );
726 WINE_ERR("Couldn't get the windows directory - error %d\n",
732 if( res>=sizeof(gen_path) )
734 WINE_ERR("Windows path too long (%d)\n", res );
739 if( !SetCurrentDirectory( gen_path ) )
741 WINE_ERR("Cannot set the dir to %s (%d)\n", gen_path, GetLastError() );
747 while ((optc = getopt_long(argc, argv, short_options, long_options, NULL )) != -1)
751 case 'e': end_session = 1; break;
752 case 'f': force = 1; break;
753 case 'k': kill = 1; break;
754 case 'r': restart = 1; break;
755 case 's': shutdown = 1; break;
756 case 'h': usage(); return 0;
757 case '?': usage(); return 1;
763 if (!shutdown_close_windows( force )) return 1;
766 if (end_session || kill) kill_processes( shutdown );
768 if (shutdown) return 0;
773 ProcessWindowsFileProtection();
774 ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICESONCE], TRUE, FALSE );
777 ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICES], FALSE, FALSE );
780 ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNONCE], TRUE, TRUE );
783 ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUN], FALSE, FALSE );
784 ProcessRunKeys( HKEY_CURRENT_USER, runkeys_names[RUNKEY_RUN], FALSE, FALSE );
785 ProcessStartupItems();
788 WINE_TRACE("Operation done\n");