Release 4.20.
[wine.git] / programs / wineboot / wineboot.c
blobcd5c9505b3f1dd4f8f7be569f0bd9d9b4ae4300b
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 #define COBJMACROS
56 #include <errno.h>
57 #include <fcntl.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <sys/stat.h>
61 #include <unistd.h>
62 #include <windows.h>
63 #include <winternl.h>
64 #include <wine/svcctl.h>
65 #include <wine/asm.h>
66 #include <wine/debug.h>
68 #include <shlobj.h>
69 #include <shobjidl.h>
70 #include <shlwapi.h>
71 #include <shellapi.h>
72 #include <setupapi.h>
73 #include <newdev.h>
74 #include "resource.h"
76 WINE_DEFAULT_DEBUG_CHANNEL(wineboot);
78 extern BOOL shutdown_close_windows( BOOL force );
79 extern BOOL shutdown_all_desktops( BOOL force );
80 extern void kill_processes( BOOL kill_desktop );
82 static WCHAR windowsdir[MAX_PATH];
83 static const BOOL is_64bit = sizeof(void *) > sizeof(int);
85 static const WCHAR winebuilddirW[] = {'W','I','N','E','B','U','I','L','D','D','I','R',0};
86 static const WCHAR winedatadirW[] = {'W','I','N','E','D','A','T','A','D','I','R',0};
87 static const WCHAR wineconfigdirW[] = {'W','I','N','E','C','O','N','F','I','G','D','I','R',0};
89 /* retrieve the path to the wine.inf file */
90 static WCHAR *get_wine_inf_path(void)
92 static const WCHAR loaderW[] = {'\\','l','o','a','d','e','r',0};
93 static const WCHAR wine_infW[] = {'\\','w','i','n','e','.','i','n','f',0};
94 WCHAR *dir, *name = NULL;
96 if ((dir = _wgetenv( winebuilddirW )))
98 if (!(name = HeapAlloc( GetProcessHeap(), 0,
99 sizeof(loaderW) + sizeof(wine_infW) + lstrlenW(dir) * sizeof(WCHAR) )))
100 return NULL;
101 lstrcpyW( name, dir );
102 lstrcatW( name, loaderW );
104 else if ((dir = _wgetenv( winedatadirW )))
106 if (!(name = HeapAlloc( GetProcessHeap(), 0, sizeof(wine_infW) + lstrlenW(dir) * sizeof(WCHAR) )))
107 return NULL;
108 lstrcpyW( name, dir );
110 else return NULL;
112 lstrcatW( name, wine_infW );
113 name[1] = '\\'; /* change \??\ to \\?\ */
114 return name;
117 /* update the timestamp if different from the reference time */
118 static BOOL update_timestamp( const WCHAR *config_dir, unsigned long timestamp )
120 static const WCHAR timestampW[] = {'\\','.','u','p','d','a','t','e','-','t','i','m','e','s','t','a','m','p',0};
121 BOOL ret = FALSE;
122 int fd, count;
123 char buffer[100];
124 WCHAR *file = HeapAlloc( GetProcessHeap(), 0, lstrlenW(config_dir) * sizeof(WCHAR) + sizeof(timestampW) );
126 if (!file) return FALSE;
127 lstrcpyW( file, config_dir );
128 lstrcatW( file, timestampW );
130 if ((fd = _wopen( 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 chsize( fd, 0 );
141 else
143 if (errno != ENOENT) goto done;
144 if ((fd = _wopen( 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", debugstr_w(file) );
151 chsize( fd, 0 );
153 else ret = TRUE;
155 done:
156 if (fd != -1) close( fd );
157 HeapFree( GetProcessHeap(), 0, file );
158 return ret;
161 /* print the config directory in a more Unix-ish way */
162 static const char *prettyprint_configdir(void)
164 static char buffer[MAX_PATH];
165 WCHAR *path = _wgetenv( wineconfigdirW );
166 char *p;
168 if (!WideCharToMultiByte( CP_UNIXCP, 0, path, -1, buffer, ARRAY_SIZE(buffer), NULL, NULL ))
169 strcpy( buffer + ARRAY_SIZE(buffer) - 4, "..." );
171 if (!strncmp( buffer, "\\??\\unix\\", 9 ))
173 for (p = buffer + 9; *p; p++) if (*p == '\\') *p = '/';
174 return buffer + 9;
176 else if (!strncmp( buffer, "\\??\\Z:\\", 7 ))
178 for (p = buffer + 6; *p; p++) if (*p == '\\') *p = '/';
179 return buffer + 6;
181 else return buffer + 4;
184 /* wrapper for RegSetValueExW */
185 static DWORD set_reg_value( HKEY hkey, const WCHAR *name, const WCHAR *value )
187 return RegSetValueExW( hkey, name, 0, REG_SZ, (const BYTE *)value, (lstrlenW(value) + 1) * sizeof(WCHAR) );
190 #if defined(__i386__) || defined(__x86_64__)
192 #if defined(_MSC_VER)
193 static void do_cpuid( unsigned int ax, unsigned int *p )
195 __cpuid( p, ax );
197 #elif defined(__i386__)
198 extern void __cdecl do_cpuid( unsigned int ax, unsigned int *p );
199 __ASM_GLOBAL_FUNC( do_cpuid,
200 "pushl %esi\n\t"
201 "pushl %ebx\n\t"
202 "movl 12(%esp),%eax\n\t"
203 "movl 16(%esp),%esi\n\t"
204 "cpuid\n\t"
205 "movl %eax,(%esi)\n\t"
206 "movl %ebx,4(%esi)\n\t"
207 "movl %ecx,8(%esi)\n\t"
208 "movl %edx,12(%esi)\n\t"
209 "popl %ebx\n\t"
210 "popl %esi\n\t"
211 "ret" )
212 #else
213 extern void __cdecl do_cpuid( unsigned int ax, unsigned int *p );
214 __ASM_GLOBAL_FUNC( do_cpuid,
215 "pushq %rsi\n\t"
216 "pushq %rbx\n\t"
217 "movq %rcx,%rax\n\t"
218 "movq %rdx,%rsi\n\t"
219 "cpuid\n\t"
220 "movl %eax,(%rsi)\n\t"
221 "movl %ebx,4(%rsi)\n\t"
222 "movl %ecx,8(%rsi)\n\t"
223 "movl %edx,12(%rsi)\n\t"
224 "popq %rbx\n\t"
225 "popq %rsi\n\t"
226 "ret" )
227 #endif
229 static void regs_to_str( unsigned int *regs, unsigned int len, WCHAR *buffer )
231 unsigned int i;
232 unsigned char *p = (unsigned char *)regs;
234 for (i = 0; i < len; i++) { buffer[i] = *p++; }
235 buffer[i] = 0;
238 static unsigned int get_model( unsigned int reg0, unsigned int *stepping, unsigned int *family )
240 unsigned int model, family_id = (reg0 & (0x0f << 8)) >> 8;
242 model = (reg0 & (0x0f << 4)) >> 4;
243 if (family_id == 6 || family_id == 15) model |= (reg0 & (0x0f << 16)) >> 12;
245 *family = family_id;
246 if (family_id == 15) *family += (reg0 & (0xff << 20)) >> 20;
248 *stepping = reg0 & 0x0f;
249 return model;
252 static void get_identifier( WCHAR *buf, size_t size, const WCHAR *arch )
254 static const WCHAR fmtW[] = {'%','s',' ','F','a','m','i','l','y',' ','%','u',' ','M','o','d','e','l',
255 ' ','%','u',' ','S','t','e','p','p','i','n','g',' ','%','u',0};
256 unsigned int regs[4] = {0, 0, 0, 0}, family, model, stepping;
258 do_cpuid( 1, regs );
259 model = get_model( regs[0], &stepping, &family );
260 swprintf( buf, size, fmtW, arch, family, model, stepping );
263 static void get_vendorid( WCHAR *buf )
265 unsigned int tmp, regs[4] = {0, 0, 0, 0};
267 do_cpuid( 0, regs );
268 tmp = regs[2]; /* swap edx and ecx */
269 regs[2] = regs[3];
270 regs[3] = tmp;
272 regs_to_str( regs + 1, 12, buf );
275 static void get_namestring( WCHAR *buf )
277 unsigned int regs[4] = {0, 0, 0, 0};
278 int i;
280 do_cpuid( 0x80000000, regs );
281 if (regs[0] >= 0x80000004)
283 do_cpuid( 0x80000002, regs );
284 regs_to_str( regs, 16, buf );
285 do_cpuid( 0x80000003, regs );
286 regs_to_str( regs, 16, buf + 16 );
287 do_cpuid( 0x80000004, regs );
288 regs_to_str( regs, 16, buf + 32 );
290 for (i = lstrlenW(buf) - 1; i >= 0 && buf[i] == ' '; i--) buf[i] = 0;
293 #else /* __i386__ || __x86_64__ */
295 static void get_identifier( WCHAR *buf, size_t size, const WCHAR *arch ) { }
296 static void get_vendorid( WCHAR *buf ) { }
297 static void get_namestring( WCHAR *buf ) { }
299 #endif /* __i386__ || __x86_64__ */
301 /* create the volatile hardware registry keys */
302 static void create_hardware_registry_keys(void)
304 static const WCHAR SystemW[] = {'H','a','r','d','w','a','r','e','\\','D','e','s','c','r','i','p','t','i','o','n','\\',
305 'S','y','s','t','e','m',0};
306 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};
307 static const WCHAR cpuW[] = {'C','e','n','t','r','a','l','P','r','o','c','e','s','s','o','r',0};
308 static const WCHAR FeatureSetW[] = {'F','e','a','t','u','r','e','S','e','t',0};
309 static const WCHAR IdentifierW[] = {'I','d','e','n','t','i','f','i','e','r',0};
310 static const WCHAR ProcessorNameStringW[] = {'P','r','o','c','e','s','s','o','r','N','a','m','e','S','t','r','i','n','g',0};
311 static const WCHAR SysidW[] = {'A','T',' ','c','o','m','p','a','t','i','b','l','e',0};
312 static const WCHAR ARMSysidW[] = {'A','R','M',' ','p','r','o','c','e','s','s','o','r',' ','f','a','m','i','l','y',0};
313 static const WCHAR mhzKeyW[] = {'~','M','H','z',0};
314 static const WCHAR VendorIdentifierW[] = {'V','e','n','d','o','r','I','d','e','n','t','i','f','i','e','r',0};
315 static const WCHAR PercentDW[] = {'%','d',0};
316 static const WCHAR ARMCpuDescrW[] = {'A','R','M',' ','F','a','m','i','l','y',' ','%','d',' ','M','o','d','e','l',' ','%','d',
317 ' ','R','e','v','i','s','i','o','n',' ','%','d',0};
318 static const WCHAR x86W[] = {'x','8','6',0};
319 static const WCHAR intel64W[] = {'I','n','t','e','l','6','4',0};
320 static const WCHAR amd64W[] = {'A','M','D','6','4',0};
321 static const WCHAR authenticamdW[] = {'A','u','t','h','e','n','t','i','c','A','M','D',0};
322 unsigned int i;
323 HKEY hkey, system_key, cpu_key, fpu_key;
324 SYSTEM_CPU_INFORMATION sci;
325 PROCESSOR_POWER_INFORMATION* power_info;
326 ULONG sizeof_power_info = sizeof(PROCESSOR_POWER_INFORMATION) * NtCurrentTeb()->Peb->NumberOfProcessors;
327 WCHAR id[60], namestr[49], vendorid[13];
329 get_namestring( namestr );
330 get_vendorid( vendorid );
331 NtQuerySystemInformation( SystemCpuInformation, &sci, sizeof(sci), NULL );
333 power_info = HeapAlloc( GetProcessHeap(), 0, sizeof_power_info );
334 if (power_info == NULL)
335 return;
336 if (NtPowerInformation( ProcessorInformation, NULL, 0, power_info, sizeof_power_info ))
337 memset( power_info, 0, sizeof_power_info );
339 switch (sci.Architecture)
341 case PROCESSOR_ARCHITECTURE_ARM:
342 case PROCESSOR_ARCHITECTURE_ARM64:
343 swprintf( id, ARRAY_SIZE(id), ARMCpuDescrW, sci.Level, HIBYTE(sci.Revision), LOBYTE(sci.Revision) );
344 break;
346 case PROCESSOR_ARCHITECTURE_AMD64:
347 get_identifier( id, ARRAY_SIZE(id), !wcscmp(vendorid, authenticamdW) ? amd64W : intel64W );
348 break;
350 case PROCESSOR_ARCHITECTURE_INTEL:
351 default:
352 get_identifier( id, ARRAY_SIZE(id), x86W );
353 break;
356 if (RegCreateKeyExW( HKEY_LOCAL_MACHINE, SystemW, 0, NULL, REG_OPTION_VOLATILE,
357 KEY_ALL_ACCESS, NULL, &system_key, NULL ))
359 HeapFree( GetProcessHeap(), 0, power_info );
360 return;
363 switch (sci.Architecture)
365 case PROCESSOR_ARCHITECTURE_ARM:
366 case PROCESSOR_ARCHITECTURE_ARM64:
367 set_reg_value( system_key, IdentifierW, ARMSysidW );
368 break;
370 case PROCESSOR_ARCHITECTURE_INTEL:
371 case PROCESSOR_ARCHITECTURE_AMD64:
372 default:
373 set_reg_value( system_key, IdentifierW, SysidW );
374 break;
377 if (sci.Architecture == PROCESSOR_ARCHITECTURE_ARM ||
378 sci.Architecture == PROCESSOR_ARCHITECTURE_ARM64 ||
379 RegCreateKeyExW( system_key, fpuW, 0, NULL, REG_OPTION_VOLATILE,
380 KEY_ALL_ACCESS, NULL, &fpu_key, NULL ))
381 fpu_key = 0;
382 if (RegCreateKeyExW( system_key, cpuW, 0, NULL, REG_OPTION_VOLATILE,
383 KEY_ALL_ACCESS, NULL, &cpu_key, NULL ))
384 cpu_key = 0;
386 for (i = 0; i < NtCurrentTeb()->Peb->NumberOfProcessors; i++)
388 WCHAR numW[10];
390 swprintf( numW, ARRAY_SIZE(numW), PercentDW, i );
391 if (!RegCreateKeyExW( cpu_key, numW, 0, NULL, REG_OPTION_VOLATILE,
392 KEY_ALL_ACCESS, NULL, &hkey, NULL ))
394 RegSetValueExW( hkey, FeatureSetW, 0, REG_DWORD, (BYTE *)&sci.FeatureSet, sizeof(DWORD) );
395 set_reg_value( hkey, IdentifierW, id );
396 /* TODO: report ARM properly */
397 set_reg_value( hkey, ProcessorNameStringW, namestr );
398 set_reg_value( hkey, VendorIdentifierW, vendorid );
399 RegSetValueExW( hkey, mhzKeyW, 0, REG_DWORD, (BYTE *)&power_info[i].MaxMhz, sizeof(DWORD) );
400 RegCloseKey( hkey );
402 if (sci.Architecture != PROCESSOR_ARCHITECTURE_ARM &&
403 sci.Architecture != PROCESSOR_ARCHITECTURE_ARM64 &&
404 !RegCreateKeyExW( fpu_key, numW, 0, NULL, REG_OPTION_VOLATILE,
405 KEY_ALL_ACCESS, NULL, &hkey, NULL ))
407 set_reg_value( hkey, IdentifierW, id );
408 RegCloseKey( hkey );
411 RegCloseKey( fpu_key );
412 RegCloseKey( cpu_key );
413 RegCloseKey( system_key );
414 HeapFree( GetProcessHeap(), 0, power_info );
418 /* create the DynData registry keys */
419 static void create_dynamic_registry_keys(void)
421 static const WCHAR StatDataW[] = {'P','e','r','f','S','t','a','t','s','\\',
422 'S','t','a','t','D','a','t','a',0};
423 static const WCHAR ConfigManagerW[] = {'C','o','n','f','i','g',' ','M','a','n','a','g','e','r','\\',
424 'E','n','u','m',0};
425 HKEY key;
427 if (!RegCreateKeyExW( HKEY_DYN_DATA, StatDataW, 0, NULL, 0, KEY_WRITE, NULL, &key, NULL ))
428 RegCloseKey( key );
429 if (!RegCreateKeyExW( HKEY_DYN_DATA, ConfigManagerW, 0, NULL, 0, KEY_WRITE, NULL, &key, NULL ))
430 RegCloseKey( key );
433 /* create the platform-specific environment registry keys */
434 static void create_environment_registry_keys( void )
436 static const WCHAR EnvironW[] = {'S','y','s','t','e','m','\\',
437 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
438 'C','o','n','t','r','o','l','\\',
439 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
440 'E','n','v','i','r','o','n','m','e','n','t',0};
441 static const WCHAR NumProcW[] = {'N','U','M','B','E','R','_','O','F','_','P','R','O','C','E','S','S','O','R','S',0};
442 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};
443 static const WCHAR x86W[] = {'x','8','6',0};
444 static const WCHAR intel64W[] = {'I','n','t','e','l','6','4',0};
445 static const WCHAR amd64W[] = {'A','M','D','6','4',0};
446 static const WCHAR authenticamdW[] = {'A','u','t','h','e','n','t','i','c','A','M','D',0};
447 static const WCHAR commaW[] = {',',' ',0};
448 static const WCHAR ProcIdW[] = {'P','R','O','C','E','S','S','O','R','_','I','D','E','N','T','I','F','I','E','R',0};
449 static const WCHAR ProcLvlW[] = {'P','R','O','C','E','S','S','O','R','_','L','E','V','E','L',0};
450 static const WCHAR ProcRevW[] = {'P','R','O','C','E','S','S','O','R','_','R','E','V','I','S','I','O','N',0};
451 static const WCHAR PercentDW[] = {'%','d',0};
452 static const WCHAR Percent04XW[] = {'%','0','4','x',0};
453 static const WCHAR ARMCpuDescrW[] = {'A','R','M',' ','F','a','m','i','l','y',' ','%','d',' ','M','o','d','e','l',' ','%','d',
454 ' ','R','e','v','i','s','i','o','n',' ','%','d',0};
455 HKEY env_key;
456 SYSTEM_CPU_INFORMATION sci;
457 WCHAR buffer[60], vendorid[13];
458 const WCHAR *arch, *parch;
460 if (RegCreateKeyW( HKEY_LOCAL_MACHINE, EnvironW, &env_key )) return;
462 get_vendorid( vendorid );
463 NtQuerySystemInformation( SystemCpuInformation, &sci, sizeof(sci), NULL );
465 swprintf( buffer, ARRAY_SIZE(buffer), PercentDW, NtCurrentTeb()->Peb->NumberOfProcessors );
466 set_reg_value( env_key, NumProcW, buffer );
468 switch (sci.Architecture)
470 case PROCESSOR_ARCHITECTURE_AMD64:
471 arch = amd64W;
472 parch = !wcscmp(vendorid, authenticamdW) ? amd64W : intel64W;
473 break;
475 case PROCESSOR_ARCHITECTURE_INTEL:
476 default:
477 arch = parch = x86W;
478 break;
480 set_reg_value( env_key, ProcArchW, arch );
482 switch (sci.Architecture)
484 case PROCESSOR_ARCHITECTURE_ARM:
485 case PROCESSOR_ARCHITECTURE_ARM64:
486 swprintf( buffer, ARRAY_SIZE(buffer), ARMCpuDescrW,
487 sci.Level, HIBYTE(sci.Revision), LOBYTE(sci.Revision) );
488 break;
490 case PROCESSOR_ARCHITECTURE_AMD64:
491 case PROCESSOR_ARCHITECTURE_INTEL:
492 default:
493 get_identifier( buffer, ARRAY_SIZE(buffer), parch );
494 lstrcatW( buffer, commaW );
495 lstrcatW( buffer, vendorid );
496 break;
498 set_reg_value( env_key, ProcIdW, buffer );
500 swprintf( buffer, ARRAY_SIZE(buffer), PercentDW, sci.Level );
501 set_reg_value( env_key, ProcLvlW, buffer );
503 swprintf( buffer, ARRAY_SIZE(buffer), Percent04XW, sci.Revision );
504 set_reg_value( env_key, ProcRevW, buffer );
506 RegCloseKey( env_key );
509 static void create_volatile_environment_registry_key(void)
511 static const WCHAR VolatileEnvW[] = {'V','o','l','a','t','i','l','e',' ','E','n','v','i','r','o','n','m','e','n','t',0};
512 static const WCHAR AppDataW[] = {'A','P','P','D','A','T','A',0};
513 static const WCHAR ClientNameW[] = {'C','L','I','E','N','T','N','A','M','E',0};
514 static const WCHAR HomeDriveW[] = {'H','O','M','E','D','R','I','V','E',0};
515 static const WCHAR HomePathW[] = {'H','O','M','E','P','A','T','H',0};
516 static const WCHAR HomeShareW[] = {'H','O','M','E','S','H','A','R','E',0};
517 static const WCHAR LocalAppDataW[] = {'L','O','C','A','L','A','P','P','D','A','T','A',0};
518 static const WCHAR LogonServerW[] = {'L','O','G','O','N','S','E','R','V','E','R',0};
519 static const WCHAR SessionNameW[] = {'S','E','S','S','I','O','N','N','A','M','E',0};
520 static const WCHAR UserNameW[] = {'U','S','E','R','N','A','M','E',0};
521 static const WCHAR UserDomainW[] = {'U','S','E','R','D','O','M','A','I','N',0};
522 static const WCHAR UserProfileW[] = {'U','S','E','R','P','R','O','F','I','L','E',0};
523 static const WCHAR ConsoleW[] = {'C','o','n','s','o','l','e',0};
524 static const WCHAR EmptyW[] = {0};
525 WCHAR path[MAX_PATH];
526 WCHAR computername[MAX_COMPUTERNAME_LENGTH + 1 + 2];
527 DWORD size;
528 HKEY hkey;
529 HRESULT hr;
531 if (RegCreateKeyExW( HKEY_CURRENT_USER, VolatileEnvW, 0, NULL, REG_OPTION_VOLATILE,
532 KEY_ALL_ACCESS, NULL, &hkey, NULL ))
533 return;
535 hr = SHGetFolderPathW( NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, path );
536 if (SUCCEEDED(hr)) set_reg_value( hkey, AppDataW, path );
538 set_reg_value( hkey, ClientNameW, ConsoleW );
540 /* Write the profile path's drive letter and directory components into
541 * HOMEDRIVE and HOMEPATH respectively. */
542 hr = SHGetFolderPathW( NULL, CSIDL_PROFILE | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, path );
543 if (SUCCEEDED(hr))
545 set_reg_value( hkey, UserProfileW, path );
546 set_reg_value( hkey, HomePathW, path + 2 );
547 path[2] = '\0';
548 set_reg_value( hkey, HomeDriveW, path );
551 size = ARRAY_SIZE(path);
552 if (GetUserNameW( path, &size )) set_reg_value( hkey, UserNameW, path );
554 set_reg_value( hkey, HomeShareW, EmptyW );
556 hr = SHGetFolderPathW( NULL, CSIDL_LOCAL_APPDATA | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, path );
557 if (SUCCEEDED(hr))
558 set_reg_value( hkey, LocalAppDataW, path );
560 size = ARRAY_SIZE(computername) - 2;
561 if (GetComputerNameW(&computername[2], &size))
563 set_reg_value( hkey, UserDomainW, &computername[2] );
564 computername[0] = computername[1] = '\\';
565 set_reg_value( hkey, LogonServerW, computername );
568 set_reg_value( hkey, SessionNameW, ConsoleW );
569 RegCloseKey( hkey );
572 /* Performs the rename operations dictated in %SystemRoot%\Wininit.ini.
573 * Returns FALSE if there was an error, or otherwise if all is ok.
575 static BOOL wininit(void)
577 static const WCHAR nulW[] = {'N','U','L',0};
578 static const WCHAR renameW[] = {'r','e','n','a','m','e',0};
579 static const WCHAR wininitW[] = {'w','i','n','i','n','i','t','.','i','n','i',0};
580 static const WCHAR wininitbakW[] = {'w','i','n','i','n','i','t','.','b','a','k',0};
581 WCHAR initial_buffer[1024];
582 WCHAR *str, *buffer = initial_buffer;
583 DWORD size = ARRAY_SIZE(initial_buffer);
584 DWORD res;
586 for (;;)
588 if (!(res = GetPrivateProfileSectionW( renameW, buffer, size, wininitW ))) return TRUE;
589 if (res < size - 2) break;
590 if (buffer != initial_buffer) HeapFree( GetProcessHeap(), 0, buffer );
591 size *= 2;
592 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return FALSE;
595 for (str = buffer; *str; str += lstrlenW(str) + 1)
597 WCHAR *value;
599 if (*str == ';') continue; /* comment */
600 if (!(value = wcschr( str, '=' ))) continue;
602 /* split the line into key and value */
603 *value++ = 0;
605 if (!lstrcmpiW( nulW, str ))
607 WINE_TRACE("Deleting file %s\n", wine_dbgstr_w(value) );
608 if( !DeleteFileW( value ) )
609 WINE_WARN("Error deleting file %s\n", wine_dbgstr_w(value) );
611 else
613 WINE_TRACE("Renaming file %s to %s\n", wine_dbgstr_w(value), wine_dbgstr_w(str) );
615 if( !MoveFileExW(value, str, MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) )
616 WINE_WARN("Error renaming %s to %s\n", wine_dbgstr_w(value), wine_dbgstr_w(str) );
618 str = value;
621 if (buffer != initial_buffer) HeapFree( GetProcessHeap(), 0, buffer );
623 if( !MoveFileExW( wininitW, wininitbakW, MOVEFILE_REPLACE_EXISTING) )
625 WINE_ERR("Couldn't rename wininit.ini, error %d\n", GetLastError() );
627 return FALSE;
630 return TRUE;
633 static BOOL pendingRename(void)
635 static const WCHAR ValueName[] = {'P','e','n','d','i','n','g',
636 'F','i','l','e','R','e','n','a','m','e',
637 'O','p','e','r','a','t','i','o','n','s',0};
638 static const WCHAR SessionW[] = { 'S','y','s','t','e','m','\\',
639 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
640 'C','o','n','t','r','o','l','\\',
641 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
642 WCHAR *buffer=NULL;
643 const WCHAR *src=NULL, *dst=NULL;
644 DWORD dataLength=0;
645 HKEY hSession=NULL;
646 DWORD res;
648 WINE_TRACE("Entered\n");
650 if( (res=RegOpenKeyExW( HKEY_LOCAL_MACHINE, SessionW, 0, KEY_ALL_ACCESS, &hSession ))
651 !=ERROR_SUCCESS )
653 WINE_TRACE("The key was not found - skipping\n");
654 return TRUE;
657 res=RegQueryValueExW( hSession, ValueName, NULL, NULL /* The value type does not really interest us, as it is not
658 truly a REG_MULTI_SZ anyways */,
659 NULL, &dataLength );
660 if( res==ERROR_FILE_NOT_FOUND )
662 /* No value - nothing to do. Great! */
663 WINE_TRACE("Value not present - nothing to rename\n");
664 res=TRUE;
665 goto end;
668 if( res!=ERROR_SUCCESS )
670 WINE_ERR("Couldn't query value's length (%d)\n", res );
671 res=FALSE;
672 goto end;
675 buffer=HeapAlloc( GetProcessHeap(),0,dataLength );
676 if( buffer==NULL )
678 WINE_ERR("Couldn't allocate %u bytes for the value\n", dataLength );
679 res=FALSE;
680 goto end;
683 res=RegQueryValueExW( hSession, ValueName, NULL, NULL, (LPBYTE)buffer, &dataLength );
684 if( res!=ERROR_SUCCESS )
686 WINE_ERR("Couldn't query value after successfully querying before (%u),\n"
687 "please report to wine-devel@winehq.org\n", res);
688 res=FALSE;
689 goto end;
692 /* Make sure that the data is long enough and ends with two NULLs. This
693 * simplifies the code later on.
695 if( dataLength<2*sizeof(buffer[0]) ||
696 buffer[dataLength/sizeof(buffer[0])-1]!='\0' ||
697 buffer[dataLength/sizeof(buffer[0])-2]!='\0' )
699 WINE_ERR("Improper value format - doesn't end with NULL\n");
700 res=FALSE;
701 goto end;
704 for( src=buffer; (src-buffer)*sizeof(src[0])<dataLength && *src!='\0';
705 src=dst+lstrlenW(dst)+1 )
707 DWORD dwFlags=0;
709 WINE_TRACE("processing next command\n");
711 dst=src+lstrlenW(src)+1;
713 /* We need to skip the \??\ header */
714 if( src[0]=='\\' && src[1]=='?' && src[2]=='?' && src[3]=='\\' )
715 src+=4;
717 if( dst[0]=='!' )
719 dwFlags|=MOVEFILE_REPLACE_EXISTING;
720 dst++;
723 if( dst[0]=='\\' && dst[1]=='?' && dst[2]=='?' && dst[3]=='\\' )
724 dst+=4;
726 if( *dst!='\0' )
728 /* Rename the file */
729 MoveFileExW( src, dst, dwFlags );
730 } else
732 /* Delete the file or directory */
733 if (!RemoveDirectoryW( src ) && GetLastError() == ERROR_DIRECTORY) DeleteFileW( src );
737 if((res=RegDeleteValueW(hSession, ValueName))!=ERROR_SUCCESS )
739 WINE_ERR("Error deleting the value (%u)\n", GetLastError() );
740 res=FALSE;
741 } else
742 res=TRUE;
744 end:
745 HeapFree(GetProcessHeap(), 0, buffer);
747 if( hSession!=NULL )
748 RegCloseKey( hSession );
750 return res;
753 #define INVALID_RUNCMD_RETURN -1
755 * This function runs the specified command in the specified dir.
756 * [in,out] cmdline - the command line to run. The function may change the passed buffer.
757 * [in] dir - the dir to run the command in. If it is NULL, then the current dir is used.
758 * [in] wait - whether to wait for the run program to finish before returning.
759 * [in] minimized - Whether to ask the program to run minimized.
761 * Returns:
762 * If running the process failed, returns INVALID_RUNCMD_RETURN. Use GetLastError to get the error code.
763 * If wait is FALSE - returns 0 if successful.
764 * If wait is TRUE - returns the program's return value.
766 static DWORD runCmd(LPWSTR cmdline, LPCWSTR dir, BOOL wait, BOOL minimized)
768 STARTUPINFOW si;
769 PROCESS_INFORMATION info;
770 DWORD exit_code=0;
772 memset(&si, 0, sizeof(si));
773 si.cb=sizeof(si);
774 if( minimized )
776 si.dwFlags=STARTF_USESHOWWINDOW;
777 si.wShowWindow=SW_MINIMIZE;
779 memset(&info, 0, sizeof(info));
781 if( !CreateProcessW(NULL, cmdline, NULL, NULL, FALSE, 0, NULL, dir, &si, &info) )
783 WINE_WARN("Failed to run command %s (%d)\n", wine_dbgstr_w(cmdline), GetLastError() );
784 return INVALID_RUNCMD_RETURN;
787 WINE_TRACE("Successfully ran command %s - Created process handle %p\n",
788 wine_dbgstr_w(cmdline), info.hProcess );
790 if(wait)
791 { /* wait for the process to exit */
792 WaitForSingleObject(info.hProcess, INFINITE);
793 GetExitCodeProcess(info.hProcess, &exit_code);
796 CloseHandle( info.hThread );
797 CloseHandle( info.hProcess );
799 return exit_code;
802 static void process_run_key( HKEY key, const WCHAR *keyname, BOOL delete, BOOL synchronous )
804 HKEY runkey;
805 LONG res;
806 DWORD disp, i, max_cmdline = 0, max_value = 0;
807 WCHAR *cmdline = NULL, *value = NULL;
809 if (RegCreateKeyExW( key, keyname, 0, NULL, 0, delete ? KEY_ALL_ACCESS : KEY_READ, NULL, &runkey, &disp ))
810 return;
812 if (disp == REG_CREATED_NEW_KEY)
813 goto end;
815 if (RegQueryInfoKeyW( runkey, NULL, NULL, NULL, NULL, NULL, NULL, &i, &max_value, &max_cmdline, NULL, NULL ))
816 goto end;
818 if (!i)
820 WINE_TRACE( "No commands to execute.\n" );
821 goto end;
823 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, max_cmdline )))
825 WINE_ERR( "Couldn't allocate memory for the commands to be executed.\n" );
826 goto end;
828 if (!(value = HeapAlloc( GetProcessHeap(), 0, ++max_value * sizeof(*value) )))
830 WINE_ERR( "Couldn't allocate memory for the value names.\n" );
831 goto end;
834 while (i)
836 DWORD len = max_value, len_data = max_cmdline, type;
838 if ((res = RegEnumValueW( runkey, --i, value, &len, 0, &type, (BYTE *)cmdline, &len_data )))
840 WINE_ERR( "Couldn't read value %u (%d).\n", i, res );
841 continue;
843 if (delete && (res = RegDeleteValueW( runkey, value )))
845 WINE_ERR( "Couldn't delete value %u (%d). Running command anyways.\n", i, res );
847 if (type != REG_SZ)
849 WINE_ERR( "Incorrect type of value %u (%u).\n", i, type );
850 continue;
852 if (runCmd( cmdline, NULL, synchronous, FALSE ) == INVALID_RUNCMD_RETURN)
854 WINE_ERR( "Error running cmd %s (%u).\n", wine_dbgstr_w(cmdline), GetLastError() );
856 WINE_TRACE( "Done processing cmd %u.\n", i );
859 end:
860 HeapFree( GetProcessHeap(), 0, value );
861 HeapFree( GetProcessHeap(), 0, cmdline );
862 RegCloseKey( runkey );
863 WINE_TRACE( "Done.\n" );
867 * Process a "Run" type registry key.
868 * hkRoot is the HKEY from which "Software\Microsoft\Windows\CurrentVersion" is
869 * opened.
870 * szKeyName is the key holding the actual entries.
871 * bDelete tells whether we should delete each value right before executing it.
872 * bSynchronous tells whether we should wait for the prog to complete before
873 * going on to the next prog.
875 static void ProcessRunKeys( HKEY root, const WCHAR *keyname, BOOL delete, BOOL synchronous )
877 static const WCHAR keypathW[] =
878 {'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\',
879 'W','i','n','d','o','w','s','\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
880 HKEY key;
882 if (root == HKEY_LOCAL_MACHINE)
884 WINE_TRACE( "Processing %s entries under HKLM.\n", wine_dbgstr_w(keyname) );
885 if (!RegCreateKeyExW( root, keypathW, 0, NULL, 0, KEY_READ, NULL, &key, NULL ))
887 process_run_key( key, keyname, delete, synchronous );
888 RegCloseKey( key );
890 if (is_64bit && !RegCreateKeyExW( root, keypathW, 0, NULL, 0, KEY_READ|KEY_WOW64_32KEY, NULL, &key, NULL ))
892 process_run_key( key, keyname, delete, synchronous );
893 RegCloseKey( key );
896 else
898 WINE_TRACE( "Processing %s entries under HKCU.\n", wine_dbgstr_w(keyname) );
899 if (!RegCreateKeyExW( root, keypathW, 0, NULL, 0, KEY_READ, NULL, &key, NULL ))
901 process_run_key( key, keyname, delete, synchronous );
902 RegCloseKey( key );
908 * WFP is Windows File Protection, in NT5 and Windows 2000 it maintains a cache
909 * of known good dlls and scans through and replaces corrupted DLLs with these
910 * known good versions. The only programs that should install into this dll
911 * cache are Windows Updates and IE (which is treated like a Windows Update)
913 * Implementing this allows installing ie in win2k mode to actually install the
914 * system dlls that we expect and need
916 static int ProcessWindowsFileProtection(void)
918 static const WCHAR winlogonW[] = {'S','o','f','t','w','a','r','e','\\',
919 'M','i','c','r','o','s','o','f','t','\\',
920 'W','i','n','d','o','w','s',' ','N','T','\\',
921 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
922 'W','i','n','l','o','g','o','n',0};
923 static const WCHAR cachedirW[] = {'S','F','C','D','l','l','C','a','c','h','e','D','i','r',0};
924 static const WCHAR dllcacheW[] = {'\\','d','l','l','c','a','c','h','e','\\','*',0};
925 static const WCHAR wildcardW[] = {'\\','*',0};
926 WIN32_FIND_DATAW finddata;
927 HANDLE find_handle;
928 BOOL find_rc;
929 DWORD rc;
930 HKEY hkey;
931 LPWSTR dllcache = NULL;
933 if (!RegOpenKeyW( HKEY_LOCAL_MACHINE, winlogonW, &hkey ))
935 DWORD sz = 0;
936 if (!RegQueryValueExW( hkey, cachedirW, 0, NULL, NULL, &sz))
938 sz += sizeof(WCHAR);
939 dllcache = HeapAlloc(GetProcessHeap(),0,sz + sizeof(wildcardW));
940 RegQueryValueExW( hkey, cachedirW, 0, NULL, (LPBYTE)dllcache, &sz);
941 lstrcatW( dllcache, wildcardW );
944 RegCloseKey(hkey);
946 if (!dllcache)
948 DWORD sz = GetSystemDirectoryW( NULL, 0 );
949 dllcache = HeapAlloc( GetProcessHeap(), 0, sz * sizeof(WCHAR) + sizeof(dllcacheW));
950 GetSystemDirectoryW( dllcache, sz );
951 lstrcatW( dllcache, dllcacheW );
954 find_handle = FindFirstFileW(dllcache,&finddata);
955 dllcache[ lstrlenW(dllcache) - 2] = 0; /* strip off wildcard */
956 find_rc = find_handle != INVALID_HANDLE_VALUE;
957 while (find_rc)
959 static const WCHAR dotW[] = {'.',0};
960 static const WCHAR dotdotW[] = {'.','.',0};
961 WCHAR targetpath[MAX_PATH];
962 WCHAR currentpath[MAX_PATH];
963 UINT sz;
964 UINT sz2;
965 WCHAR tempfile[MAX_PATH];
967 if (wcscmp(finddata.cFileName,dotW) == 0 || wcscmp(finddata.cFileName,dotdotW) == 0)
969 find_rc = FindNextFileW(find_handle,&finddata);
970 continue;
973 sz = MAX_PATH;
974 sz2 = MAX_PATH;
975 VerFindFileW(VFFF_ISSHAREDFILE, finddata.cFileName, windowsdir,
976 windowsdir, currentpath, &sz, targetpath, &sz2);
977 sz = MAX_PATH;
978 rc = VerInstallFileW(0, finddata.cFileName, finddata.cFileName,
979 dllcache, targetpath, currentpath, tempfile, &sz);
980 if (rc != ERROR_SUCCESS)
982 WINE_WARN("WFP: %s error 0x%x\n",wine_dbgstr_w(finddata.cFileName),rc);
983 DeleteFileW(tempfile);
986 /* now delete the source file so that we don't try to install it over and over again */
987 lstrcpynW( targetpath, dllcache, MAX_PATH - 1 );
988 sz = lstrlenW( targetpath );
989 targetpath[sz++] = '\\';
990 lstrcpynW( targetpath + sz, finddata.cFileName, MAX_PATH - sz );
991 if (!DeleteFileW( targetpath ))
992 WINE_WARN( "failed to delete %s: error %u\n", wine_dbgstr_w(targetpath), GetLastError() );
994 find_rc = FindNextFileW(find_handle,&finddata);
996 FindClose(find_handle);
997 HeapFree(GetProcessHeap(),0,dllcache);
998 return 1;
1001 static BOOL start_services_process(void)
1003 static const WCHAR svcctl_started_event[] = SVCCTL_STARTED_EVENT;
1004 static const WCHAR services[] = {'\\','s','e','r','v','i','c','e','s','.','e','x','e',0};
1005 PROCESS_INFORMATION pi;
1006 STARTUPINFOW si;
1007 HANDLE wait_handles[2];
1008 WCHAR path[MAX_PATH];
1010 if (!GetSystemDirectoryW(path, MAX_PATH - lstrlenW(services)))
1011 return FALSE;
1012 lstrcatW(path, services);
1013 ZeroMemory(&si, sizeof(si));
1014 si.cb = sizeof(si);
1015 if (!CreateProcessW(path, path, NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &si, &pi))
1017 WINE_ERR("Couldn't start services.exe: error %u\n", GetLastError());
1018 return FALSE;
1020 CloseHandle(pi.hThread);
1022 wait_handles[0] = CreateEventW(NULL, TRUE, FALSE, svcctl_started_event);
1023 wait_handles[1] = pi.hProcess;
1025 /* wait for the event to become available or the process to exit */
1026 if ((WaitForMultipleObjects(2, wait_handles, FALSE, INFINITE)) == WAIT_OBJECT_0 + 1)
1028 DWORD exit_code;
1029 GetExitCodeProcess(pi.hProcess, &exit_code);
1030 WINE_ERR("Unexpected termination of services.exe - exit code %d\n", exit_code);
1031 CloseHandle(pi.hProcess);
1032 CloseHandle(wait_handles[0]);
1033 return FALSE;
1036 CloseHandle(pi.hProcess);
1037 CloseHandle(wait_handles[0]);
1038 return TRUE;
1041 static INT_PTR CALLBACK wait_dlgproc( HWND hwnd, UINT msg, WPARAM wp, LPARAM lp )
1043 switch (msg)
1045 case WM_INITDIALOG:
1047 DWORD len;
1048 WCHAR *buffer, text[1024];
1049 const WCHAR *name = (WCHAR *)lp;
1050 HICON icon = LoadImageW( 0, (LPCWSTR)IDI_WINLOGO, IMAGE_ICON, 48, 48, LR_SHARED );
1051 SendDlgItemMessageW( hwnd, IDC_WAITICON, STM_SETICON, (WPARAM)icon, 0 );
1052 SendDlgItemMessageW( hwnd, IDC_WAITTEXT, WM_GETTEXT, 1024, (LPARAM)text );
1053 len = lstrlenW(text) + lstrlenW(name) + 1;
1054 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
1055 swprintf( buffer, len, text, name );
1056 SendDlgItemMessageW( hwnd, IDC_WAITTEXT, WM_SETTEXT, 0, (LPARAM)buffer );
1057 HeapFree( GetProcessHeap(), 0, buffer );
1059 break;
1061 return 0;
1064 static HWND show_wait_window(void)
1066 const char *config_dir = prettyprint_configdir();
1067 WCHAR *name;
1068 HWND hwnd;
1069 DWORD len;
1071 len = MultiByteToWideChar( CP_UNIXCP, 0, config_dir, -1, NULL, 0 );
1072 name = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
1073 MultiByteToWideChar( CP_UNIXCP, 0, config_dir, -1, name, len );
1074 hwnd = CreateDialogParamW( GetModuleHandleW(0), MAKEINTRESOURCEW(IDD_WAITDLG), 0,
1075 wait_dlgproc, (LPARAM)name );
1076 ShowWindow( hwnd, SW_SHOWNORMAL );
1077 HeapFree( GetProcessHeap(), 0, name );
1078 return hwnd;
1081 static HANDLE start_rundll32( const WCHAR *inf_path, BOOL wow64 )
1083 static const WCHAR rundll[] = {'\\','r','u','n','d','l','l','3','2','.','e','x','e',0};
1084 static const WCHAR setupapi[] = {' ','s','e','t','u','p','a','p','i',',',
1085 'I','n','s','t','a','l','l','H','i','n','f','S','e','c','t','i','o','n',0};
1086 static const WCHAR definstall[] = {' ','D','e','f','a','u','l','t','I','n','s','t','a','l','l',0};
1087 static const WCHAR wowinstall[] = {' ','W','o','w','6','4','I','n','s','t','a','l','l',0};
1088 static const WCHAR flags[] = {' ','1','2','8',' ',0};
1090 WCHAR app[MAX_PATH + ARRAY_SIZE(rundll)];
1091 STARTUPINFOW si;
1092 PROCESS_INFORMATION pi;
1093 WCHAR *buffer;
1094 DWORD len;
1096 memset( &si, 0, sizeof(si) );
1097 si.cb = sizeof(si);
1099 if (wow64)
1101 if (!GetSystemWow64DirectoryW( app, MAX_PATH )) return 0; /* not on 64-bit */
1103 else GetSystemDirectoryW( app, MAX_PATH );
1105 lstrcatW( app, rundll );
1107 len = lstrlenW(app) + ARRAY_SIZE(setupapi) + ARRAY_SIZE(definstall) + ARRAY_SIZE(flags) + lstrlenW(inf_path);
1109 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) ))) return 0;
1111 lstrcpyW( buffer, app );
1112 lstrcatW( buffer, setupapi );
1113 lstrcatW( buffer, wow64 ? wowinstall : definstall );
1114 lstrcatW( buffer, flags );
1115 lstrcatW( buffer, inf_path );
1117 if (CreateProcessW( app, buffer, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ))
1118 CloseHandle( pi.hThread );
1119 else
1120 pi.hProcess = 0;
1122 HeapFree( GetProcessHeap(), 0, buffer );
1123 return pi.hProcess;
1126 static void install_root_pnp_devices(void)
1128 static const struct
1130 const char *name;
1131 const char *hardware_id;
1132 const char *infpath;
1134 root_devices[] =
1136 {"root\\wine\\winebus", "root\\winebus\0", "C:\\windows\\inf\\winebus.inf"},
1138 SP_DEVINFO_DATA device = {sizeof(device)};
1139 unsigned int i;
1140 HDEVINFO set;
1142 if ((set = SetupDiCreateDeviceInfoList( NULL, NULL )) == INVALID_HANDLE_VALUE)
1144 WINE_ERR("Failed to create device info list, error %#x.\n", GetLastError());
1145 return;
1148 for (i = 0; i < ARRAY_SIZE(root_devices); ++i)
1150 if (!SetupDiCreateDeviceInfoA( set, root_devices[i].name, &GUID_NULL, NULL, NULL, 0, &device))
1152 if (GetLastError() != ERROR_DEVINST_ALREADY_EXISTS)
1153 WINE_ERR("Failed to create device %s, error %#x.\n", debugstr_a(root_devices[i].name), GetLastError());
1154 continue;
1157 if (!SetupDiSetDeviceRegistryPropertyA(set, &device, SPDRP_HARDWAREID,
1158 (const BYTE *)root_devices[i].hardware_id, (strlen(root_devices[i].hardware_id) + 2) * sizeof(WCHAR)))
1160 WINE_ERR("Failed to set hardware id for %s, error %#x.\n", debugstr_a(root_devices[i].name), GetLastError());
1161 continue;
1164 if (!SetupDiCallClassInstaller(DIF_REGISTERDEVICE, set, &device))
1166 WINE_ERR("Failed to register device %s, error %#x.\n", debugstr_a(root_devices[i].name), GetLastError());
1167 continue;
1170 if (!UpdateDriverForPlugAndPlayDevicesA(NULL, root_devices[i].hardware_id, root_devices[i].infpath, 0, NULL))
1171 WINE_ERR("Failed to install drivers for %s, error %#x.\n", debugstr_a(root_devices[i].name), GetLastError());
1174 SetupDiDestroyDeviceInfoList(set);
1177 /* execute rundll32 on the wine.inf file if necessary */
1178 static void update_wineprefix( BOOL force )
1180 const WCHAR *config_dir = _wgetenv( wineconfigdirW );
1181 WCHAR *inf_path = get_wine_inf_path();
1182 int fd;
1183 struct stat st;
1185 if (!inf_path)
1187 WINE_MESSAGE( "wine: failed to update %s, wine.inf not found\n", prettyprint_configdir() );
1188 return;
1190 if ((fd = _wopen( inf_path, O_RDONLY )) == -1)
1192 WINE_MESSAGE( "wine: failed to update %s with %s: %s\n",
1193 prettyprint_configdir(), debugstr_w(inf_path), strerror(errno) );
1194 goto done;
1196 fstat( fd, &st );
1197 close( fd );
1199 if (update_timestamp( config_dir, st.st_mtime ) || force)
1201 HANDLE process;
1202 DWORD count = 0;
1204 if ((process = start_rundll32( inf_path, FALSE )))
1206 HWND hwnd = show_wait_window();
1207 for (;;)
1209 MSG msg;
1210 DWORD res = MsgWaitForMultipleObjects( 1, &process, FALSE, INFINITE, QS_ALLINPUT );
1211 if (res == WAIT_OBJECT_0)
1213 CloseHandle( process );
1214 if (count++ || !(process = start_rundll32( inf_path, TRUE ))) break;
1216 else while (PeekMessageW( &msg, 0, 0, 0, PM_REMOVE )) DispatchMessageW( &msg );
1218 DestroyWindow( hwnd );
1220 install_root_pnp_devices();
1222 WINE_MESSAGE( "wine: configuration in '%s' has been updated.\n", prettyprint_configdir() );
1225 done:
1226 HeapFree( GetProcessHeap(), 0, inf_path );
1229 /* Process items in the StartUp group of the user's Programs under the Start Menu. Some installers put
1230 * shell links here to restart themselves after boot. */
1231 static BOOL ProcessStartupItems(void)
1233 BOOL ret = FALSE;
1234 HRESULT hr;
1235 IMalloc *ppM = NULL;
1236 IShellFolder *psfDesktop = NULL, *psfStartup = NULL;
1237 LPITEMIDLIST pidlStartup = NULL, pidlItem;
1238 ULONG NumPIDLs;
1239 IEnumIDList *iEnumList = NULL;
1240 STRRET strret;
1241 WCHAR wszCommand[MAX_PATH];
1243 WINE_TRACE("Processing items in the StartUp folder.\n");
1245 hr = SHGetMalloc(&ppM);
1246 if (FAILED(hr))
1248 WINE_ERR("Couldn't get IMalloc object.\n");
1249 goto done;
1252 hr = SHGetDesktopFolder(&psfDesktop);
1253 if (FAILED(hr))
1255 WINE_ERR("Couldn't get desktop folder.\n");
1256 goto done;
1259 hr = SHGetSpecialFolderLocation(NULL, CSIDL_STARTUP, &pidlStartup);
1260 if (FAILED(hr))
1262 WINE_TRACE("Couldn't get StartUp folder location.\n");
1263 goto done;
1266 hr = IShellFolder_BindToObject(psfDesktop, pidlStartup, NULL, &IID_IShellFolder, (LPVOID*)&psfStartup);
1267 if (FAILED(hr))
1269 WINE_TRACE("Couldn't bind IShellFolder to StartUp folder.\n");
1270 goto done;
1273 hr = IShellFolder_EnumObjects(psfStartup, NULL, SHCONTF_NONFOLDERS | SHCONTF_INCLUDEHIDDEN, &iEnumList);
1274 if (FAILED(hr))
1276 WINE_TRACE("Unable to enumerate StartUp objects.\n");
1277 goto done;
1280 while (IEnumIDList_Next(iEnumList, 1, &pidlItem, &NumPIDLs) == S_OK &&
1281 (NumPIDLs) == 1)
1283 hr = IShellFolder_GetDisplayNameOf(psfStartup, pidlItem, SHGDN_FORPARSING, &strret);
1284 if (FAILED(hr))
1285 WINE_TRACE("Unable to get display name of enumeration item.\n");
1286 else
1288 hr = StrRetToBufW(&strret, pidlItem, wszCommand, MAX_PATH);
1289 if (FAILED(hr))
1290 WINE_TRACE("Unable to parse display name.\n");
1291 else
1293 HINSTANCE hinst;
1295 hinst = ShellExecuteW(NULL, NULL, wszCommand, NULL, NULL, SW_SHOWNORMAL);
1296 if (PtrToUlong(hinst) <= 32)
1297 WINE_WARN("Error %p executing command %s.\n", hinst, wine_dbgstr_w(wszCommand));
1301 IMalloc_Free(ppM, pidlItem);
1304 /* Return success */
1305 ret = TRUE;
1307 done:
1308 if (iEnumList) IEnumIDList_Release(iEnumList);
1309 if (psfStartup) IShellFolder_Release(psfStartup);
1310 if (pidlStartup) IMalloc_Free(ppM, pidlStartup);
1312 return ret;
1315 static void usage( int status )
1317 WINE_MESSAGE( "Usage: wineboot [options]\n" );
1318 WINE_MESSAGE( "Options;\n" );
1319 WINE_MESSAGE( " -h,--help Display this help message\n" );
1320 WINE_MESSAGE( " -e,--end-session End the current session cleanly\n" );
1321 WINE_MESSAGE( " -f,--force Force exit for processes that don't exit cleanly\n" );
1322 WINE_MESSAGE( " -i,--init Perform initialization for first Wine instance\n" );
1323 WINE_MESSAGE( " -k,--kill Kill running processes without any cleanup\n" );
1324 WINE_MESSAGE( " -r,--restart Restart only, don't do normal startup operations\n" );
1325 WINE_MESSAGE( " -s,--shutdown Shutdown only, don't reboot\n" );
1326 WINE_MESSAGE( " -u,--update Update the wineprefix directory\n" );
1327 exit( status );
1330 int __cdecl main( int argc, char *argv[] )
1332 static const WCHAR RunW[] = {'R','u','n',0};
1333 static const WCHAR RunOnceW[] = {'R','u','n','O','n','c','e',0};
1334 static const WCHAR RunServicesW[] = {'R','u','n','S','e','r','v','i','c','e','s',0};
1335 static const WCHAR RunServicesOnceW[] = {'R','u','n','S','e','r','v','i','c','e','s','O','n','c','e',0};
1336 static const WCHAR wineboot_eventW[] = {'\\','K','e','r','n','e','l','O','b','j','e','c','t','s',
1337 '\\','_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
1339 /* First, set the current directory to SystemRoot */
1340 int i, j;
1341 BOOL end_session, force, init, kill, restart, shutdown, update;
1342 HANDLE event;
1343 OBJECT_ATTRIBUTES attr;
1344 UNICODE_STRING nameW;
1345 BOOL is_wow64;
1347 end_session = force = init = kill = restart = shutdown = update = FALSE;
1348 GetWindowsDirectoryW( windowsdir, MAX_PATH );
1349 if( !SetCurrentDirectoryW( windowsdir ) )
1350 WINE_ERR("Cannot set the dir to %s (%d)\n", wine_dbgstr_w(windowsdir), GetLastError() );
1352 if (IsWow64Process( GetCurrentProcess(), &is_wow64 ) && is_wow64)
1354 STARTUPINFOW si;
1355 PROCESS_INFORMATION pi;
1356 WCHAR filename[MAX_PATH];
1357 void *redir;
1358 DWORD exit_code;
1360 memset( &si, 0, sizeof(si) );
1361 si.cb = sizeof(si);
1362 GetModuleFileNameW( 0, filename, MAX_PATH );
1364 Wow64DisableWow64FsRedirection( &redir );
1365 if (CreateProcessW( filename, GetCommandLineW(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ))
1367 WINE_TRACE( "restarting %s\n", wine_dbgstr_w(filename) );
1368 WaitForSingleObject( pi.hProcess, INFINITE );
1369 GetExitCodeProcess( pi.hProcess, &exit_code );
1370 ExitProcess( exit_code );
1372 else WINE_ERR( "failed to restart 64-bit %s, err %d\n", wine_dbgstr_w(filename), GetLastError() );
1373 Wow64RevertWow64FsRedirection( redir );
1376 for (i = 1; i < argc; i++)
1378 if (argv[i][0] != '-') continue;
1379 if (argv[i][1] == '-')
1381 if (!strcmp( argv[i], "--help" )) usage( 0 );
1382 else if (!strcmp( argv[i], "--end-session" )) end_session = TRUE;
1383 else if (!strcmp( argv[i], "--force" )) force = TRUE;
1384 else if (!strcmp( argv[i], "--init" )) init = TRUE;
1385 else if (!strcmp( argv[i], "--kill" )) kill = TRUE;
1386 else if (!strcmp( argv[i], "--restart" )) restart = TRUE;
1387 else if (!strcmp( argv[i], "--shutdown" )) shutdown = TRUE;
1388 else if (!strcmp( argv[i], "--update" )) update = TRUE;
1389 else usage( 1 );
1390 continue;
1392 for (j = 1; argv[i][j]; j++)
1394 switch (argv[i][j])
1396 case 'e': end_session = TRUE; break;
1397 case 'f': force = TRUE; break;
1398 case 'i': init = TRUE; break;
1399 case 'k': kill = TRUE; break;
1400 case 'r': restart = TRUE; break;
1401 case 's': shutdown = TRUE; break;
1402 case 'u': update = TRUE; break;
1403 case 'h': usage(0); break;
1404 default: usage(1); break;
1409 if (end_session)
1411 if (kill)
1413 if (!shutdown_all_desktops( force )) return 1;
1415 else if (!shutdown_close_windows( force )) return 1;
1418 if (kill) kill_processes( shutdown );
1420 if (shutdown) return 0;
1422 /* create event to be inherited by services.exe */
1423 InitializeObjectAttributes( &attr, &nameW, OBJ_OPENIF | OBJ_INHERIT, 0, NULL );
1424 RtlInitUnicodeString( &nameW, wineboot_eventW );
1425 NtCreateEvent( &event, EVENT_ALL_ACCESS, &attr, NotificationEvent, 0 );
1427 ResetEvent( event ); /* in case this is a restart */
1429 create_hardware_registry_keys();
1430 create_dynamic_registry_keys();
1431 create_environment_registry_keys();
1432 wininit();
1433 pendingRename();
1435 ProcessWindowsFileProtection();
1436 ProcessRunKeys( HKEY_LOCAL_MACHINE, RunServicesOnceW, TRUE, FALSE );
1438 if (init || (kill && !restart))
1440 ProcessRunKeys( HKEY_LOCAL_MACHINE, RunServicesW, FALSE, FALSE );
1441 start_services_process();
1443 if (init || update) update_wineprefix( update );
1445 create_volatile_environment_registry_key();
1447 ProcessRunKeys( HKEY_LOCAL_MACHINE, RunOnceW, TRUE, TRUE );
1449 if (!init && !restart)
1451 ProcessRunKeys( HKEY_LOCAL_MACHINE, RunW, FALSE, FALSE );
1452 ProcessRunKeys( HKEY_CURRENT_USER, RunW, FALSE, FALSE );
1453 ProcessStartupItems();
1456 WINE_TRACE("Operation done\n");
1458 SetEvent( event );
1459 return 0;