msdaps: Add a stub marshaller object.
[wine/hramrach.git] / programs / wineboot / wineboot.c
blob7c4b14bcd4de79c72cf1147b13a79fed6cb33721
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 /* wrapper for RegSetValueExW */
162 static DWORD set_reg_value( HKEY hkey, const WCHAR *name, const WCHAR *value )
164 return RegSetValueExW( hkey, name, 0, REG_SZ, (BYTE *)value, (strlenW(value) + 1) * sizeof(WCHAR) );
167 /* create the volatile hardware registry keys */
168 static void create_hardware_registry_keys(void)
170 static const WCHAR SystemW[] = {'H','a','r','d','w','a','r','e','\\',
171 'D','e','s','c','r','i','p','t','i','o','n','\\',
172 'S','y','s','t','e','m',0};
173 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};
174 static const WCHAR cpuW[] = {'C','e','n','t','r','a','l','P','r','o','c','e','s','s','o','r',0};
175 static const WCHAR IdentifierW[] = {'I','d','e','n','t','i','f','i','e','r',0};
176 static const WCHAR SysidW[] = {'A','T',' ','c','o','m','p','a','t','i','b','l','e',0};
177 static const WCHAR mhzKeyW[] = {'~','M','H','z',0};
178 static const WCHAR VendorIdentifierW[] = {'V','e','n','d','o','r','I','d','e','n','t','i','f','i','e','r',0};
179 static const WCHAR VenidIntelW[] = {'G','e','n','u','i','n','e','I','n','t','e','l',0};
180 /* static const WCHAR VenidAMDW[] = {'A','u','t','h','e','n','t','i','c','A','M','D',0}; */
181 static const WCHAR PercentDW[] = {'%','d',0};
182 static const WCHAR IntelCpuDescrW[] = {'x','8','6',' ','F','a','m','i','l','y',' ','%','d',' ','M','o','d','e','l',' ','%','d',
183 ' ','S','t','e','p','p','i','n','g',' ','%','d',0};
184 unsigned int i;
185 HKEY hkey, system_key, cpu_key, fpu_key;
186 SYSTEM_CPU_INFORMATION sci;
187 PROCESSOR_POWER_INFORMATION power_info;
188 WCHAR idW[60];
190 NtQuerySystemInformation( SystemCpuInformation, &sci, sizeof(sci), NULL );
191 if (NtPowerInformation(ProcessorInformation, NULL, 0, &power_info, sizeof(power_info)))
192 power_info.MaxMhz = 0;
194 /*TODO: report 64bit processors properly*/
195 sprintfW( idW, IntelCpuDescrW, sci.Level, HIBYTE(sci.Revision), LOBYTE(sci.Revision) );
197 if (RegCreateKeyExW( HKEY_LOCAL_MACHINE, SystemW, 0, NULL, REG_OPTION_VOLATILE,
198 KEY_ALL_ACCESS, NULL, &system_key, NULL ))
199 return;
201 set_reg_value( system_key, IdentifierW, SysidW );
203 if (RegCreateKeyExW( system_key, fpuW, 0, NULL, REG_OPTION_VOLATILE,
204 KEY_ALL_ACCESS, NULL, &fpu_key, NULL ))
205 fpu_key = 0;
206 if (RegCreateKeyExW( system_key, cpuW, 0, NULL, REG_OPTION_VOLATILE,
207 KEY_ALL_ACCESS, NULL, &cpu_key, NULL ))
208 cpu_key = 0;
210 for (i = 0; i < NtCurrentTeb()->Peb->NumberOfProcessors; i++)
212 WCHAR numW[10];
214 sprintfW( numW, PercentDW, i );
215 if (!RegCreateKeyExW( cpu_key, numW, 0, NULL, REG_OPTION_VOLATILE,
216 KEY_ALL_ACCESS, NULL, &hkey, NULL ))
218 set_reg_value( hkey, IdentifierW, idW );
219 /*TODO; report amd's properly*/
220 set_reg_value( hkey, VendorIdentifierW, VenidIntelW );
221 RegSetValueExW( hkey, mhzKeyW, 0, REG_DWORD, (BYTE *)&power_info.MaxMhz, sizeof(DWORD) );
222 RegCloseKey( hkey );
224 if (!RegCreateKeyExW( fpu_key, numW, 0, NULL, REG_OPTION_VOLATILE,
225 KEY_ALL_ACCESS, NULL, &hkey, NULL ))
227 set_reg_value( hkey, IdentifierW, idW );
228 RegCloseKey( hkey );
231 RegCloseKey( fpu_key );
232 RegCloseKey( cpu_key );
233 RegCloseKey( system_key );
236 /* create the platform-specific environment registry keys */
237 static void create_environment_registry_keys( void )
239 static const WCHAR EnvironW[] = {'S','y','s','t','e','m','\\',
240 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
241 'C','o','n','t','r','o','l','\\',
242 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
243 'E','n','v','i','r','o','n','m','e','n','t',0};
244 static const WCHAR NumProcW[] = {'N','U','M','B','E','R','_','O','F','_','P','R','O','C','E','S','S','O','R','S',0};
245 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};
246 static const WCHAR x86W[] = {'x','8','6',0};
247 static const WCHAR ProcIdW[] = {'P','R','O','C','E','S','S','O','R','_','I','D','E','N','T','I','F','I','E','R',0};
248 static const WCHAR ProcLvlW[] = {'P','R','O','C','E','S','S','O','R','_','L','E','V','E','L',0};
249 static const WCHAR ProcRevW[] = {'P','R','O','C','E','S','S','O','R','_','R','E','V','I','S','I','O','N',0};
250 static const WCHAR PercentDW[] = {'%','d',0};
251 static const WCHAR Percent04XW[] = {'%','0','4','x',0};
252 static const WCHAR IntelCpuDescrW[] = {'x','8','6',' ','F','a','m','i','l','y',' ','%','d',' ','M','o','d','e','l',' ','%','d',
253 ' ','S','t','e','p','p','i','n','g',' ','%','d',',',' ','G','e','n','u','i','n','e','I','n','t','e','l',0};
255 HKEY env_key;
256 SYSTEM_CPU_INFORMATION sci;
257 WCHAR buffer[60];
259 NtQuerySystemInformation( SystemCpuInformation, &sci, sizeof(sci), NULL );
261 if (RegCreateKeyW( HKEY_LOCAL_MACHINE, EnvironW, &env_key )) return;
263 sprintfW( buffer, PercentDW, NtCurrentTeb()->Peb->NumberOfProcessors );
264 set_reg_value( env_key, NumProcW, buffer );
266 /* TODO: currently hardcoded x86, add different processors */
267 set_reg_value( env_key, ProcArchW, x86W );
269 /* TODO: currently hardcoded Intel, add different processors */
270 sprintfW( buffer, IntelCpuDescrW, sci.Level, HIBYTE(sci.Revision), LOBYTE(sci.Revision) );
271 set_reg_value( env_key, ProcIdW, buffer );
273 sprintfW( buffer, PercentDW, sci.Level );
274 set_reg_value( env_key, ProcLvlW, buffer );
276 /* Properly report model/stepping */
277 sprintfW( buffer, Percent04XW, sci.Revision );
278 set_reg_value( env_key, ProcRevW, buffer );
280 RegCloseKey( env_key );
283 static void create_volatile_environment_registry_key(void)
285 static const WCHAR VolatileEnvW[] = {'V','o','l','a','t','i','l','e',' ','E','n','v','i','r','o','n','m','e','n','t',0};
286 static const WCHAR AppDataW[] = {'A','P','P','D','A','T','A',0};
287 static const WCHAR ClientNameW[] = {'C','L','I','E','N','T','N','A','M','E',0};
288 static const WCHAR HomeDriveW[] = {'H','O','M','E','D','R','I','V','E',0};
289 static const WCHAR HomePathW[] = {'H','O','M','E','P','A','T','H',0};
290 static const WCHAR HomeShareW[] = {'H','O','M','E','S','H','A','R','E',0};
291 static const WCHAR LocalAppDataW[] = {'L','O','C','A','L','A','P','P','D','A','T','A',0};
292 static const WCHAR LogonServerW[] = {'L','O','G','O','N','S','E','R','V','E','R',0};
293 static const WCHAR SessionNameW[] = {'S','E','S','S','I','O','N','N','A','M','E',0};
294 static const WCHAR UserNameW[] = {'U','S','E','R','N','A','M','E',0};
295 static const WCHAR UserProfileW[] = {'U','S','E','R','P','R','O','F','I','L','E',0};
296 static const WCHAR ConsoleW[] = {'C','o','n','s','o','l','e',0};
297 static const WCHAR EmptyW[] = {0};
298 WCHAR path[MAX_PATH];
299 WCHAR computername[MAX_COMPUTERNAME_LENGTH + 1 + 2];
300 DWORD size;
301 HKEY hkey;
302 HRESULT hr;
304 if (RegCreateKeyExW( HKEY_CURRENT_USER, VolatileEnvW, 0, NULL, REG_OPTION_VOLATILE,
305 KEY_ALL_ACCESS, NULL, &hkey, NULL ))
306 return;
308 hr = SHGetFolderPathW( NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, path );
309 if (SUCCEEDED(hr)) set_reg_value( hkey, AppDataW, path );
311 set_reg_value( hkey, ClientNameW, ConsoleW );
313 /* Write the profile path's drive letter and directory components into
314 * HOMEDRIVE and HOMEPATH respectively. */
315 hr = SHGetFolderPathW( NULL, CSIDL_PROFILE, NULL, SHGFP_TYPE_CURRENT, path );
316 if (SUCCEEDED(hr))
318 set_reg_value( hkey, UserProfileW, path );
319 set_reg_value( hkey, HomePathW, path + 2 );
320 path[2] = '\0';
321 set_reg_value( hkey, HomeDriveW, path );
324 size = sizeof(path);
325 if (GetUserNameW( path, &size )) set_reg_value( hkey, UserNameW, path );
327 set_reg_value( hkey, HomeShareW, EmptyW );
329 hr = SHGetFolderPathW( NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, path );
330 if (SUCCEEDED(hr))
331 set_reg_value( hkey, LocalAppDataW, path );
333 size = sizeof(computername) - 2;
334 if (GetComputerNameW(&computername[2], &size))
336 computername[0] = computername[1] = '\\';
337 set_reg_value( hkey, LogonServerW, computername );
340 set_reg_value( hkey, SessionNameW, ConsoleW );
341 RegCloseKey( hkey );
344 /* Performs the rename operations dictated in %SystemRoot%\Wininit.ini.
345 * Returns FALSE if there was an error, or otherwise if all is ok.
347 static BOOL wininit(void)
349 static const WCHAR nulW[] = {'N','U','L',0};
350 static const WCHAR renameW[] = {'r','e','n','a','m','e',0};
351 static const WCHAR wininitW[] = {'w','i','n','i','n','i','t','.','i','n','i',0};
352 static const WCHAR wininitbakW[] = {'w','i','n','i','n','i','t','.','b','a','k',0};
353 WCHAR initial_buffer[1024];
354 WCHAR *str, *buffer = initial_buffer;
355 DWORD size = sizeof(initial_buffer)/sizeof(WCHAR);
356 DWORD res;
358 for (;;)
360 if (!(res = GetPrivateProfileSectionW( renameW, buffer, size, wininitW ))) return TRUE;
361 if (res < size - 2) break;
362 if (buffer != initial_buffer) HeapFree( GetProcessHeap(), 0, buffer );
363 size *= 2;
364 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return FALSE;
367 for (str = buffer; *str; str += strlenW(str) + 1)
369 WCHAR *value;
371 if (*str == ';') continue; /* comment */
372 if (!(value = strchrW( str, '=' ))) continue;
374 /* split the line into key and value */
375 *value++ = 0;
377 if (!lstrcmpiW( nulW, str ))
379 WINE_TRACE("Deleting file %s\n", wine_dbgstr_w(value) );
380 if( !DeleteFileW( value ) )
381 WINE_WARN("Error deleting file %s\n", wine_dbgstr_w(value) );
383 else
385 WINE_TRACE("Renaming file %s to %s\n", wine_dbgstr_w(value), wine_dbgstr_w(str) );
387 if( !MoveFileExW(value, str, MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) )
388 WINE_WARN("Error renaming %s to %s\n", wine_dbgstr_w(value), wine_dbgstr_w(str) );
390 str = value;
393 if (buffer != initial_buffer) HeapFree( GetProcessHeap(), 0, buffer );
395 if( !MoveFileExW( wininitW, wininitbakW, MOVEFILE_REPLACE_EXISTING) )
397 WINE_ERR("Couldn't rename wininit.ini, error %d\n", GetLastError() );
399 return FALSE;
402 return TRUE;
405 static BOOL pendingRename(void)
407 static const WCHAR ValueName[] = {'P','e','n','d','i','n','g',
408 'F','i','l','e','R','e','n','a','m','e',
409 'O','p','e','r','a','t','i','o','n','s',0};
410 static const WCHAR SessionW[] = { 'S','y','s','t','e','m','\\',
411 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
412 'C','o','n','t','r','o','l','\\',
413 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
414 WCHAR *buffer=NULL;
415 const WCHAR *src=NULL, *dst=NULL;
416 DWORD dataLength=0;
417 HKEY hSession=NULL;
418 DWORD res;
420 WINE_TRACE("Entered\n");
422 if( (res=RegOpenKeyExW( HKEY_LOCAL_MACHINE, SessionW, 0, KEY_ALL_ACCESS, &hSession ))
423 !=ERROR_SUCCESS )
425 WINE_TRACE("The key was not found - skipping\n");
426 return TRUE;
429 res=RegQueryValueExW( hSession, ValueName, NULL, NULL /* The value type does not really interest us, as it is not
430 truly a REG_MULTI_SZ anyways */,
431 NULL, &dataLength );
432 if( res==ERROR_FILE_NOT_FOUND )
434 /* No value - nothing to do. Great! */
435 WINE_TRACE("Value not present - nothing to rename\n");
436 res=TRUE;
437 goto end;
440 if( res!=ERROR_SUCCESS )
442 WINE_ERR("Couldn't query value's length (%d)\n", res );
443 res=FALSE;
444 goto end;
447 buffer=HeapAlloc( GetProcessHeap(),0,dataLength );
448 if( buffer==NULL )
450 WINE_ERR("Couldn't allocate %u bytes for the value\n", dataLength );
451 res=FALSE;
452 goto end;
455 res=RegQueryValueExW( hSession, ValueName, NULL, NULL, (LPBYTE)buffer, &dataLength );
456 if( res!=ERROR_SUCCESS )
458 WINE_ERR("Couldn't query value after successfully querying before (%u),\n"
459 "please report to wine-devel@winehq.org\n", res);
460 res=FALSE;
461 goto end;
464 /* Make sure that the data is long enough and ends with two NULLs. This
465 * simplifies the code later on.
467 if( dataLength<2*sizeof(buffer[0]) ||
468 buffer[dataLength/sizeof(buffer[0])-1]!='\0' ||
469 buffer[dataLength/sizeof(buffer[0])-2]!='\0' )
471 WINE_ERR("Improper value format - doesn't end with NULL\n");
472 res=FALSE;
473 goto end;
476 for( src=buffer; (src-buffer)*sizeof(src[0])<dataLength && *src!='\0';
477 src=dst+lstrlenW(dst)+1 )
479 DWORD dwFlags=0;
481 WINE_TRACE("processing next command\n");
483 dst=src+lstrlenW(src)+1;
485 /* We need to skip the \??\ header */
486 if( src[0]=='\\' && src[1]=='?' && src[2]=='?' && src[3]=='\\' )
487 src+=4;
489 if( dst[0]=='!' )
491 dwFlags|=MOVEFILE_REPLACE_EXISTING;
492 dst++;
495 if( dst[0]=='\\' && dst[1]=='?' && dst[2]=='?' && dst[3]=='\\' )
496 dst+=4;
498 if( *dst!='\0' )
500 /* Rename the file */
501 MoveFileExW( src, dst, dwFlags );
502 } else
504 /* Delete the file or directory */
505 if( (res=GetFileAttributesW(src))!=INVALID_FILE_ATTRIBUTES )
507 if( (res&FILE_ATTRIBUTE_DIRECTORY)==0 )
509 /* It's a file */
510 DeleteFileW(src);
511 } else
513 /* It's a directory */
514 RemoveDirectoryW(src);
516 } else
518 WINE_ERR("couldn't get file attributes (%d)\n", GetLastError() );
523 if((res=RegDeleteValueW(hSession, ValueName))!=ERROR_SUCCESS )
525 WINE_ERR("Error deleting the value (%u)\n", GetLastError() );
526 res=FALSE;
527 } else
528 res=TRUE;
530 end:
531 HeapFree(GetProcessHeap(), 0, buffer);
533 if( hSession!=NULL )
534 RegCloseKey( hSession );
536 return res;
539 enum runkeys {
540 RUNKEY_RUN, RUNKEY_RUNONCE, RUNKEY_RUNSERVICES, RUNKEY_RUNSERVICESONCE
543 const WCHAR runkeys_names[][30]=
545 {'R','u','n',0},
546 {'R','u','n','O','n','c','e',0},
547 {'R','u','n','S','e','r','v','i','c','e','s',0},
548 {'R','u','n','S','e','r','v','i','c','e','s','O','n','c','e',0}
551 #define INVALID_RUNCMD_RETURN -1
553 * This function runs the specified command in the specified dir.
554 * [in,out] cmdline - the command line to run. The function may change the passed buffer.
555 * [in] dir - the dir to run the command in. If it is NULL, then the current dir is used.
556 * [in] wait - whether to wait for the run program to finish before returning.
557 * [in] minimized - Whether to ask the program to run minimized.
559 * Returns:
560 * If running the process failed, returns INVALID_RUNCMD_RETURN. Use GetLastError to get the error code.
561 * If wait is FALSE - returns 0 if successful.
562 * If wait is TRUE - returns the program's return value.
564 static DWORD runCmd(LPWSTR cmdline, LPCWSTR dir, BOOL wait, BOOL minimized)
566 STARTUPINFOW si;
567 PROCESS_INFORMATION info;
568 DWORD exit_code=0;
570 memset(&si, 0, sizeof(si));
571 si.cb=sizeof(si);
572 if( minimized )
574 si.dwFlags=STARTF_USESHOWWINDOW;
575 si.wShowWindow=SW_MINIMIZE;
577 memset(&info, 0, sizeof(info));
579 if( !CreateProcessW(NULL, cmdline, NULL, NULL, FALSE, 0, NULL, dir, &si, &info) )
581 WINE_WARN("Failed to run command %s (%d)\n", wine_dbgstr_w(cmdline), GetLastError() );
582 return INVALID_RUNCMD_RETURN;
585 WINE_TRACE("Successfully ran command %s - Created process handle %p\n",
586 wine_dbgstr_w(cmdline), info.hProcess );
588 if(wait)
589 { /* wait for the process to exit */
590 WaitForSingleObject(info.hProcess, INFINITE);
591 GetExitCodeProcess(info.hProcess, &exit_code);
594 CloseHandle( info.hThread );
595 CloseHandle( info.hProcess );
597 return exit_code;
601 * Process a "Run" type registry key.
602 * hkRoot is the HKEY from which "Software\Microsoft\Windows\CurrentVersion" is
603 * opened.
604 * szKeyName is the key holding the actual entries.
605 * bDelete tells whether we should delete each value right before executing it.
606 * bSynchronous tells whether we should wait for the prog to complete before
607 * going on to the next prog.
609 static BOOL ProcessRunKeys( HKEY hkRoot, LPCWSTR szKeyName, BOOL bDelete,
610 BOOL bSynchronous )
612 static const WCHAR WINKEY_NAME[]={'S','o','f','t','w','a','r','e','\\',
613 'M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\',
614 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
615 HKEY hkWin, hkRun;
616 DWORD res;
617 DWORD i, nMaxCmdLine=0, nMaxValue=0;
618 WCHAR *szCmdLine=NULL;
619 WCHAR *szValue=NULL;
621 if (hkRoot==HKEY_LOCAL_MACHINE)
622 WINE_TRACE("processing %s entries under HKLM\n",wine_dbgstr_w(szKeyName) );
623 else
624 WINE_TRACE("processing %s entries under HKCU\n",wine_dbgstr_w(szKeyName) );
626 if (RegOpenKeyExW( hkRoot, WINKEY_NAME, 0, KEY_READ, &hkWin ) != ERROR_SUCCESS)
627 return TRUE;
629 if (RegOpenKeyExW( hkWin, szKeyName, 0, bDelete?KEY_ALL_ACCESS:KEY_READ, &hkRun ) != ERROR_SUCCESS)
631 RegCloseKey( hkWin );
632 return TRUE;
634 RegCloseKey( hkWin );
636 if( (res=RegQueryInfoKeyW( hkRun, NULL, NULL, NULL, NULL, NULL, NULL, &i, &nMaxValue,
637 &nMaxCmdLine, NULL, NULL ))!=ERROR_SUCCESS )
638 goto end;
640 if( i==0 )
642 WINE_TRACE("No commands to execute.\n");
644 res=ERROR_SUCCESS;
645 goto end;
648 if( (szCmdLine=HeapAlloc(GetProcessHeap(),0,nMaxCmdLine))==NULL )
650 WINE_ERR("Couldn't allocate memory for the commands to be executed\n");
652 res=ERROR_NOT_ENOUGH_MEMORY;
653 goto end;
656 if( (szValue=HeapAlloc(GetProcessHeap(),0,(++nMaxValue)*sizeof(*szValue)))==NULL )
658 WINE_ERR("Couldn't allocate memory for the value names\n");
660 res=ERROR_NOT_ENOUGH_MEMORY;
661 goto end;
664 while( i>0 )
666 DWORD nValLength=nMaxValue, nDataLength=nMaxCmdLine;
667 DWORD type;
669 --i;
671 if( (res=RegEnumValueW( hkRun, i, szValue, &nValLength, 0, &type,
672 (LPBYTE)szCmdLine, &nDataLength ))!=ERROR_SUCCESS )
674 WINE_ERR("Couldn't read in value %d - %d\n", i, res );
676 continue;
679 if( bDelete && (res=RegDeleteValueW( hkRun, szValue ))!=ERROR_SUCCESS )
681 WINE_ERR("Couldn't delete value - %d, %d. Running command anyways.\n", i, res );
684 if( type!=REG_SZ )
686 WINE_ERR("Incorrect type of value #%d (%d)\n", i, type );
688 continue;
691 if( (res=runCmd(szCmdLine, NULL, bSynchronous, FALSE ))==INVALID_RUNCMD_RETURN )
693 WINE_ERR("Error running cmd %s (%d)\n", wine_dbgstr_w(szCmdLine), GetLastError() );
696 WINE_TRACE("Done processing cmd #%d\n", i);
699 res=ERROR_SUCCESS;
701 end:
702 HeapFree( GetProcessHeap(), 0, szValue );
703 HeapFree( GetProcessHeap(), 0, szCmdLine );
705 if( hkRun!=NULL )
706 RegCloseKey( hkRun );
708 WINE_TRACE("done\n");
710 return res==ERROR_SUCCESS;
714 * WFP is Windows File Protection, in NT5 and Windows 2000 it maintains a cache
715 * of known good dlls and scans through and replaces corrupted DLLs with these
716 * known good versions. The only programs that should install into this dll
717 * cache are Windows Updates and IE (which is treated like a Windows Update)
719 * Implementing this allows installing ie in win2k mode to actually install the
720 * system dlls that we expect and need
722 static int ProcessWindowsFileProtection(void)
724 static const WCHAR winlogonW[] = {'S','o','f','t','w','a','r','e','\\',
725 'M','i','c','r','o','s','o','f','t','\\',
726 'W','i','n','d','o','w','s',' ','N','T','\\',
727 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
728 'W','i','n','l','o','g','o','n',0};
729 static const WCHAR cachedirW[] = {'S','F','C','D','l','l','C','a','c','h','e','D','i','r',0};
730 static const WCHAR dllcacheW[] = {'\\','d','l','l','c','a','c','h','e','\\','*',0};
731 static const WCHAR wildcardW[] = {'\\','*',0};
732 WIN32_FIND_DATAW finddata;
733 HANDLE find_handle;
734 BOOL find_rc;
735 DWORD rc;
736 HKEY hkey;
737 LPWSTR dllcache = NULL;
739 if (!RegOpenKeyW( HKEY_LOCAL_MACHINE, winlogonW, &hkey ))
741 DWORD sz = 0;
742 if (!RegQueryValueExW( hkey, cachedirW, 0, NULL, NULL, &sz))
744 sz += sizeof(WCHAR);
745 dllcache = HeapAlloc(GetProcessHeap(),0,sz + sizeof(wildcardW));
746 RegQueryValueExW( hkey, cachedirW, 0, NULL, (LPBYTE)dllcache, &sz);
747 strcatW( dllcache, wildcardW );
750 RegCloseKey(hkey);
752 if (!dllcache)
754 DWORD sz = GetSystemDirectoryW( NULL, 0 );
755 dllcache = HeapAlloc( GetProcessHeap(), 0, sz * sizeof(WCHAR) + sizeof(dllcacheW));
756 GetSystemDirectoryW( dllcache, sz );
757 strcatW( dllcache, dllcacheW );
760 find_handle = FindFirstFileW(dllcache,&finddata);
761 dllcache[ strlenW(dllcache) - 2] = 0; /* strip off wildcard */
762 find_rc = find_handle != INVALID_HANDLE_VALUE;
763 while (find_rc)
765 static const WCHAR dotW[] = {'.',0};
766 static const WCHAR dotdotW[] = {'.','.',0};
767 WCHAR targetpath[MAX_PATH];
768 WCHAR currentpath[MAX_PATH];
769 UINT sz;
770 UINT sz2;
771 WCHAR tempfile[MAX_PATH];
773 if (strcmpW(finddata.cFileName,dotW) == 0 || strcmpW(finddata.cFileName,dotdotW) == 0)
775 find_rc = FindNextFileW(find_handle,&finddata);
776 continue;
779 sz = MAX_PATH;
780 sz2 = MAX_PATH;
781 VerFindFileW(VFFF_ISSHAREDFILE, finddata.cFileName, windowsdir,
782 windowsdir, currentpath, &sz, targetpath, &sz2);
783 sz = MAX_PATH;
784 rc = VerInstallFileW(0, finddata.cFileName, finddata.cFileName,
785 dllcache, targetpath, currentpath, tempfile, &sz);
786 if (rc != ERROR_SUCCESS)
788 WINE_WARN("WFP: %s error 0x%x\n",wine_dbgstr_w(finddata.cFileName),rc);
789 DeleteFileW(tempfile);
792 /* now delete the source file so that we don't try to install it over and over again */
793 lstrcpynW( targetpath, dllcache, MAX_PATH - 1 );
794 sz = strlenW( targetpath );
795 targetpath[sz++] = '\\';
796 lstrcpynW( targetpath + sz, finddata.cFileName, MAX_PATH - sz );
797 if (!DeleteFileW( targetpath ))
798 WINE_WARN( "failed to delete %s: error %u\n", wine_dbgstr_w(targetpath), GetLastError() );
800 find_rc = FindNextFileW(find_handle,&finddata);
802 FindClose(find_handle);
803 HeapFree(GetProcessHeap(),0,dllcache);
804 return 1;
807 static BOOL start_services_process(void)
809 static const WCHAR svcctl_started_event[] = SVCCTL_STARTED_EVENT;
810 static const WCHAR services[] = {'\\','s','e','r','v','i','c','e','s','.','e','x','e',0};
811 PROCESS_INFORMATION pi;
812 STARTUPINFOW si;
813 HANDLE wait_handles[2];
814 WCHAR path[MAX_PATH];
816 if (!GetSystemDirectoryW(path, MAX_PATH - strlenW(services)))
817 return FALSE;
818 strcatW(path, services);
819 ZeroMemory(&si, sizeof(si));
820 si.cb = sizeof(si);
821 if (!CreateProcessW(path, path, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
823 WINE_ERR("Couldn't start services.exe: error %u\n", GetLastError());
824 return FALSE;
826 CloseHandle(pi.hThread);
828 wait_handles[0] = CreateEventW(NULL, TRUE, FALSE, svcctl_started_event);
829 wait_handles[1] = pi.hProcess;
831 /* wait for the event to become available or the process to exit */
832 if ((WaitForMultipleObjects(2, wait_handles, FALSE, INFINITE)) == WAIT_OBJECT_0 + 1)
834 DWORD exit_code;
835 GetExitCodeProcess(pi.hProcess, &exit_code);
836 WINE_ERR("Unexpected termination of services.exe - exit code %d\n", exit_code);
837 CloseHandle(pi.hProcess);
838 CloseHandle(wait_handles[0]);
839 return FALSE;
842 CloseHandle(pi.hProcess);
843 CloseHandle(wait_handles[0]);
844 return TRUE;
847 /* execute rundll32 on the wine.inf file if necessary */
848 static void update_wineprefix( int force )
850 static const WCHAR cmdlineW[] = {'D','e','f','a','u','l','t','I','n','s','t','a','l','l',' ',
851 '1','2','8',' ','\\','\\','?','\\','u','n','i','x' };
853 const char *config_dir = wine_get_config_dir();
854 char *inf_path = get_wine_inf_path();
855 int fd;
856 struct stat st;
858 if (!inf_path)
860 WINE_MESSAGE( "wine: failed to update %s, wine.inf not found\n", config_dir );
861 return;
863 if ((fd = open( inf_path, O_RDONLY )) == -1)
865 WINE_MESSAGE( "wine: failed to update %s with %s: %s\n",
866 config_dir, inf_path, strerror(errno) );
867 goto done;
869 fstat( fd, &st );
870 close( fd );
872 if (update_timestamp( config_dir, st.st_mtime ) || force)
874 WCHAR *buffer;
875 DWORD len = MultiByteToWideChar( CP_UNIXCP, 0, inf_path, -1, NULL, 0 );
876 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(cmdlineW) + len*sizeof(WCHAR) ))) goto done;
877 memcpy( buffer, cmdlineW, sizeof(cmdlineW) );
878 MultiByteToWideChar( CP_UNIXCP, 0, inf_path, -1, buffer + sizeof(cmdlineW)/sizeof(WCHAR), len );
880 InstallHinfSectionW( 0, 0, buffer, 0 );
881 HeapFree( GetProcessHeap(), 0, buffer );
882 WINE_MESSAGE( "wine: configuration in '%s' has been updated.\n", config_dir );
885 done:
886 HeapFree( GetProcessHeap(), 0, inf_path );
889 /* Process items in the StartUp group of the user's Programs under the Start Menu. Some installers put
890 * shell links here to restart themselves after boot. */
891 static BOOL ProcessStartupItems(void)
893 BOOL ret = FALSE;
894 HRESULT hr;
895 IMalloc *ppM = NULL;
896 IShellFolder *psfDesktop = NULL, *psfStartup = NULL;
897 LPITEMIDLIST pidlStartup = NULL, pidlItem;
898 ULONG NumPIDLs;
899 IEnumIDList *iEnumList = NULL;
900 STRRET strret;
901 WCHAR wszCommand[MAX_PATH];
903 WINE_TRACE("Processing items in the StartUp folder.\n");
905 hr = SHGetMalloc(&ppM);
906 if (FAILED(hr))
908 WINE_ERR("Couldn't get IMalloc object.\n");
909 goto done;
912 hr = SHGetDesktopFolder(&psfDesktop);
913 if (FAILED(hr))
915 WINE_ERR("Couldn't get desktop folder.\n");
916 goto done;
919 hr = SHGetSpecialFolderLocation(NULL, CSIDL_STARTUP, &pidlStartup);
920 if (FAILED(hr))
922 WINE_TRACE("Couldn't get StartUp folder location.\n");
923 goto done;
926 hr = IShellFolder_BindToObject(psfDesktop, pidlStartup, NULL, &IID_IShellFolder, (LPVOID*)&psfStartup);
927 if (FAILED(hr))
929 WINE_TRACE("Couldn't bind IShellFolder to StartUp folder.\n");
930 goto done;
933 hr = IShellFolder_EnumObjects(psfStartup, NULL, SHCONTF_NONFOLDERS | SHCONTF_INCLUDEHIDDEN, &iEnumList);
934 if (FAILED(hr))
936 WINE_TRACE("Unable to enumerate StartUp objects.\n");
937 goto done;
940 while (IEnumIDList_Next(iEnumList, 1, &pidlItem, &NumPIDLs) == S_OK &&
941 (NumPIDLs) == 1)
943 hr = IShellFolder_GetDisplayNameOf(psfStartup, pidlItem, SHGDN_FORPARSING, &strret);
944 if (FAILED(hr))
945 WINE_TRACE("Unable to get display name of enumeration item.\n");
946 else
948 hr = StrRetToBufW(&strret, pidlItem, wszCommand, MAX_PATH);
949 if (FAILED(hr))
950 WINE_TRACE("Unable to parse display name.\n");
951 else
953 HINSTANCE hinst;
955 hinst = ShellExecuteW(NULL, NULL, wszCommand, NULL, NULL, SW_SHOWNORMAL);
956 if (PtrToUlong(hinst) <= 32)
957 WINE_WARN("Error %p executing command %s.\n", hinst, wine_dbgstr_w(wszCommand));
961 IMalloc_Free(ppM, pidlItem);
964 /* Return success */
965 ret = TRUE;
967 done:
968 if (iEnumList) IEnumIDList_Release(iEnumList);
969 if (psfStartup) IShellFolder_Release(psfStartup);
970 if (pidlStartup) IMalloc_Free(ppM, pidlStartup);
972 return ret;
975 static void usage(void)
977 WINE_MESSAGE( "Usage: wineboot [options]\n" );
978 WINE_MESSAGE( "Options;\n" );
979 WINE_MESSAGE( " -h,--help Display this help message\n" );
980 WINE_MESSAGE( " -e,--end-session End the current session cleanly\n" );
981 WINE_MESSAGE( " -f,--force Force exit for processes that don't exit cleanly\n" );
982 WINE_MESSAGE( " -i,--init Perform initialization for first Wine instance\n" );
983 WINE_MESSAGE( " -k,--kill Kill running processes without any cleanup\n" );
984 WINE_MESSAGE( " -r,--restart Restart only, don't do normal startup operations\n" );
985 WINE_MESSAGE( " -s,--shutdown Shutdown only, don't reboot\n" );
986 WINE_MESSAGE( " -u,--update Update the wineprefix directory\n" );
989 static const char short_options[] = "efhikrsu";
991 static const struct option long_options[] =
993 { "help", 0, 0, 'h' },
994 { "end-session", 0, 0, 'e' },
995 { "force", 0, 0, 'f' },
996 { "init" , 0, 0, 'i' },
997 { "kill", 0, 0, 'k' },
998 { "restart", 0, 0, 'r' },
999 { "shutdown", 0, 0, 's' },
1000 { "update", 0, 0, 'u' },
1001 { NULL, 0, 0, 0 }
1004 int main( int argc, char *argv[] )
1006 extern HANDLE CDECL __wine_make_process_system(void);
1007 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
1009 /* First, set the current directory to SystemRoot */
1010 int optc;
1011 int end_session = 0, force = 0, init = 0, kill = 0, restart = 0, shutdown = 0, update = 0;
1012 HANDLE event;
1013 SECURITY_ATTRIBUTES sa;
1015 GetWindowsDirectoryW( windowsdir, MAX_PATH );
1016 if( !SetCurrentDirectoryW( windowsdir ) )
1017 WINE_ERR("Cannot set the dir to %s (%d)\n", wine_dbgstr_w(windowsdir), GetLastError() );
1019 while ((optc = getopt_long(argc, argv, short_options, long_options, NULL )) != -1)
1021 switch(optc)
1023 case 'e': end_session = 1; break;
1024 case 'f': force = 1; break;
1025 case 'i': init = 1; break;
1026 case 'k': kill = 1; break;
1027 case 'r': restart = 1; break;
1028 case 's': shutdown = 1; break;
1029 case 'u': update = 1; break;
1030 case 'h': usage(); return 0;
1031 case '?': usage(); return 1;
1035 if (end_session)
1037 if (!shutdown_close_windows( force )) return 1;
1040 if (kill) kill_processes( shutdown );
1042 if (shutdown) return 0;
1044 sa.nLength = sizeof(sa);
1045 sa.lpSecurityDescriptor = NULL;
1046 sa.bInheritHandle = TRUE; /* so that services.exe inherits it */
1047 event = CreateEventW( &sa, TRUE, FALSE, wineboot_eventW );
1049 ResetEvent( event ); /* in case this is a restart */
1051 create_hardware_registry_keys();
1052 create_environment_registry_keys();
1053 wininit();
1054 pendingRename();
1056 ProcessWindowsFileProtection();
1057 ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICESONCE], TRUE, FALSE );
1059 if (init || (kill && !restart))
1061 ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICES], FALSE, FALSE );
1062 start_services_process();
1064 if (init || update) update_wineprefix( update );
1066 create_volatile_environment_registry_key();
1068 ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNONCE], TRUE, TRUE );
1070 if (!init && !restart)
1072 ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUN], FALSE, FALSE );
1073 ProcessRunKeys( HKEY_CURRENT_USER, runkeys_names[RUNKEY_RUN], FALSE, FALSE );
1074 ProcessStartupItems();
1077 WINE_TRACE("Operation done\n");
1079 SetEvent( event );
1080 return 0;