kernel32: On process entry store PEB address in %ebx.
[wine.git] / programs / wineboot / wineboot.c
blobac0b04d6d8114f76b2e05a4df2e0bedb0793c2ec
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 <intrin.h>
61 #include <sys/stat.h>
62 #include <unistd.h>
63 #include <windows.h>
64 #include <winternl.h>
65 #include <sddl.h>
66 #include <wine/svcctl.h>
67 #include <wine/asm.h>
68 #include <wine/debug.h>
70 #include <shlobj.h>
71 #include <shobjidl.h>
72 #include <shlwapi.h>
73 #include <shellapi.h>
74 #include <setupapi.h>
75 #include <newdev.h>
76 #include "resource.h"
78 WINE_DEFAULT_DEBUG_CHANNEL(wineboot);
80 extern BOOL shutdown_close_windows( BOOL force );
81 extern BOOL shutdown_all_desktops( BOOL force );
82 extern void kill_processes( BOOL kill_desktop );
84 static WCHAR windowsdir[MAX_PATH];
85 static const BOOL is_64bit = sizeof(void *) > sizeof(int);
87 static const WCHAR winebuilddirW[] = {'W','I','N','E','B','U','I','L','D','D','I','R',0};
88 static const WCHAR winedatadirW[] = {'W','I','N','E','D','A','T','A','D','I','R',0};
89 static const WCHAR wineconfigdirW[] = {'W','I','N','E','C','O','N','F','I','G','D','I','R',0};
91 /* retrieve the path to the wine.inf file */
92 static WCHAR *get_wine_inf_path(void)
94 static const WCHAR loaderW[] = {'\\','l','o','a','d','e','r',0};
95 static const WCHAR wine_infW[] = {'\\','w','i','n','e','.','i','n','f',0};
96 WCHAR *dir, *name = NULL;
98 if ((dir = _wgetenv( winebuilddirW )))
100 if (!(name = HeapAlloc( GetProcessHeap(), 0,
101 sizeof(loaderW) + sizeof(wine_infW) + lstrlenW(dir) * sizeof(WCHAR) )))
102 return NULL;
103 lstrcpyW( name, dir );
104 lstrcatW( name, loaderW );
106 else if ((dir = _wgetenv( winedatadirW )))
108 if (!(name = HeapAlloc( GetProcessHeap(), 0, sizeof(wine_infW) + lstrlenW(dir) * sizeof(WCHAR) )))
109 return NULL;
110 lstrcpyW( name, dir );
112 else return NULL;
114 lstrcatW( name, wine_infW );
115 name[1] = '\\'; /* change \??\ to \\?\ */
116 return name;
119 /* update the timestamp if different from the reference time */
120 static BOOL update_timestamp( const WCHAR *config_dir, unsigned long timestamp )
122 static const WCHAR timestampW[] = {'\\','.','u','p','d','a','t','e','-','t','i','m','e','s','t','a','m','p',0};
123 BOOL ret = FALSE;
124 int fd, count;
125 char buffer[100];
126 WCHAR *file = HeapAlloc( GetProcessHeap(), 0, lstrlenW(config_dir) * sizeof(WCHAR) + sizeof(timestampW) );
128 if (!file) return FALSE;
129 lstrcpyW( file, config_dir );
130 lstrcatW( file, timestampW );
132 if ((fd = _wopen( file, O_RDWR )) != -1)
134 if ((count = read( fd, buffer, sizeof(buffer) - 1 )) >= 0)
136 buffer[count] = 0;
137 if (!strncmp( buffer, "disable", sizeof("disable")-1 )) goto done;
138 if (timestamp == strtoul( buffer, NULL, 10 )) goto done;
140 lseek( fd, 0, SEEK_SET );
141 chsize( fd, 0 );
143 else
145 if (errno != ENOENT) goto done;
146 if ((fd = _wopen( file, O_WRONLY | O_CREAT | O_TRUNC, 0666 )) == -1) goto done;
149 count = sprintf( buffer, "%lu\n", timestamp );
150 if (write( fd, buffer, count ) != count)
152 WINE_WARN( "failed to update timestamp in %s\n", debugstr_w(file) );
153 chsize( fd, 0 );
155 else ret = TRUE;
157 done:
158 if (fd != -1) close( fd );
159 HeapFree( GetProcessHeap(), 0, file );
160 return ret;
163 /* print the config directory in a more Unix-ish way */
164 static const WCHAR *prettyprint_configdir(void)
166 static WCHAR buffer[MAX_PATH];
167 WCHAR *p, *path = _wgetenv( wineconfigdirW );
169 lstrcpynW( buffer, path, ARRAY_SIZE(buffer) );
170 if (lstrlenW( wineconfigdirW ) >= ARRAY_SIZE(buffer) )
171 lstrcpyW( buffer + ARRAY_SIZE(buffer) - 4, L"..." );
173 if (!wcsncmp( buffer, L"\\??\\unix\\", 9 ))
175 for (p = buffer + 9; *p; p++) if (*p == '\\') *p = '/';
176 return buffer + 9;
178 else if (!wcsncmp( buffer, L"\\??\\Z:\\", 7 ))
180 for (p = buffer + 6; *p; p++) if (*p == '\\') *p = '/';
181 return buffer + 6;
183 else return buffer + 4;
186 /* wrapper for RegSetValueExW */
187 static DWORD set_reg_value( HKEY hkey, const WCHAR *name, const WCHAR *value )
189 return RegSetValueExW( hkey, name, 0, REG_SZ, (const BYTE *)value, (lstrlenW(value) + 1) * sizeof(WCHAR) );
192 static DWORD set_reg_value_dword( HKEY hkey, const WCHAR *name, DWORD value )
194 return RegSetValueExW( hkey, name, 0, REG_DWORD, (const BYTE *)&value, sizeof(value) );
197 #if defined(__i386__) || defined(__x86_64__)
199 static void regs_to_str( int *regs, unsigned int len, WCHAR *buffer )
201 unsigned int i;
202 unsigned char *p = (unsigned char *)regs;
204 for (i = 0; i < len; i++) { buffer[i] = *p++; }
205 buffer[i] = 0;
208 static unsigned int get_model( unsigned int reg0, unsigned int *stepping, unsigned int *family )
210 unsigned int model, family_id = (reg0 & (0x0f << 8)) >> 8;
212 model = (reg0 & (0x0f << 4)) >> 4;
213 if (family_id == 6 || family_id == 15) model |= (reg0 & (0x0f << 16)) >> 12;
215 *family = family_id;
216 if (family_id == 15) *family += (reg0 & (0xff << 20)) >> 20;
218 *stepping = reg0 & 0x0f;
219 return model;
222 static void get_identifier( WCHAR *buf, size_t size, const WCHAR *arch )
224 static const WCHAR fmtW[] = {'%','s',' ','F','a','m','i','l','y',' ','%','u',' ','M','o','d','e','l',
225 ' ','%','u',' ','S','t','e','p','p','i','n','g',' ','%','u',0};
226 unsigned int family, model, stepping;
227 int regs[4] = {0, 0, 0, 0};
229 __cpuid( regs, 1 );
230 model = get_model( regs[0], &stepping, &family );
231 swprintf( buf, size, fmtW, arch, family, model, stepping );
234 static void get_vendorid( WCHAR *buf )
236 int tmp, regs[4] = {0, 0, 0, 0};
238 __cpuid( regs, 0 );
239 tmp = regs[2]; /* swap edx and ecx */
240 regs[2] = regs[3];
241 regs[3] = tmp;
243 regs_to_str( regs + 1, 12, buf );
246 static void get_namestring( WCHAR *buf )
248 int regs[4] = {0, 0, 0, 0};
249 int i;
251 __cpuid( regs, 0x80000000 );
252 if (regs[0] >= 0x80000004)
254 __cpuid( regs, 0x80000002 );
255 regs_to_str( regs, 16, buf );
256 __cpuid( regs, 0x80000003 );
257 regs_to_str( regs, 16, buf + 16 );
258 __cpuid( regs, 0x80000004 );
259 regs_to_str( regs, 16, buf + 32 );
261 for (i = lstrlenW(buf) - 1; i >= 0 && buf[i] == ' '; i--) buf[i] = 0;
264 #else /* __i386__ || __x86_64__ */
266 static void get_identifier( WCHAR *buf, size_t size, const WCHAR *arch ) { }
267 static void get_vendorid( WCHAR *buf ) { }
268 static void get_namestring( WCHAR *buf ) { }
270 #endif /* __i386__ || __x86_64__ */
272 #include "pshpack1.h"
273 struct smbios_prologue
275 BYTE calling_method;
276 BYTE major_version;
277 BYTE minor_version;
278 BYTE revision;
279 DWORD length;
282 enum smbios_type
284 SMBIOS_TYPE_BIOS,
285 SMBIOS_TYPE_SYSTEM,
286 SMBIOS_TYPE_BASEBOARD,
289 struct smbios_header
291 BYTE type;
292 BYTE length;
293 WORD handle;
296 struct smbios_baseboard
298 struct smbios_header hdr;
299 BYTE vendor;
300 BYTE product;
301 BYTE version;
302 BYTE serial;
305 struct smbios_bios
307 struct smbios_header hdr;
308 BYTE vendor;
309 BYTE version;
310 WORD start;
311 BYTE date;
312 BYTE size;
313 UINT64 characteristics;
314 BYTE characteristics_ext[2];
315 BYTE system_bios_major_release;
316 BYTE system_bios_minor_release;
317 BYTE ec_firmware_major_release;
318 BYTE ec_firmware_minor_release;
321 struct smbios_system
323 struct smbios_header hdr;
324 BYTE vendor;
325 BYTE product;
326 BYTE version;
327 BYTE serial;
328 BYTE uuid[16];
329 BYTE wake_up_type;
330 BYTE sku;
331 BYTE family;
333 #include "poppack.h"
335 #define RSMB (('R' << 24) | ('S' << 16) | ('M' << 8) | 'B')
337 static const struct smbios_header *find_smbios_entry( enum smbios_type type, const char *buf, UINT len )
339 const char *ptr, *start;
340 const struct smbios_prologue *prologue;
341 const struct smbios_header *hdr;
343 if (len < sizeof(struct smbios_prologue)) return NULL;
344 prologue = (const struct smbios_prologue *)buf;
345 if (prologue->length > len - sizeof(*prologue) || prologue->length < sizeof(*hdr)) return NULL;
347 start = (const char *)(prologue + 1);
348 hdr = (const struct smbios_header *)start;
350 for (;;)
352 if ((const char *)hdr - start >= prologue->length - sizeof(*hdr)) return NULL;
354 if (!hdr->length)
356 WARN( "invalid entry\n" );
357 return NULL;
360 if (hdr->type == type)
362 if ((const char *)hdr - start + hdr->length > prologue->length) return NULL;
363 break;
365 else /* skip other entries and their strings */
367 for (ptr = (const char *)hdr + hdr->length; ptr - buf < len && *ptr; ptr++)
369 for (; ptr - buf < len; ptr++) if (!*ptr) break;
371 if (ptr == (const char *)hdr + hdr->length) ptr++;
372 hdr = (const struct smbios_header *)(ptr + 1);
376 return hdr;
379 static inline WCHAR *heap_strdupAW( const char *src )
381 int len;
382 WCHAR *dst;
383 if (!src) return NULL;
384 len = MultiByteToWideChar( CP_ACP, 0, src, -1, NULL, 0 );
385 if ((dst = HeapAlloc( GetProcessHeap(), 0, len * sizeof(*dst) ))) MultiByteToWideChar( CP_ACP, 0, src, -1, dst, len );
386 return dst;
389 static WCHAR *get_smbios_string( BYTE id, const char *buf, UINT offset, UINT buflen )
391 const char *ptr = buf + offset;
392 UINT i = 0;
394 if (!id || offset >= buflen) return NULL;
395 for (ptr = buf + offset; ptr - buf < buflen && *ptr; ptr++)
397 if (++i == id) return heap_strdupAW( ptr );
398 for (; ptr - buf < buflen; ptr++) if (!*ptr) break;
400 return NULL;
403 static void set_value_from_smbios_string( HKEY key, const WCHAR *value, BYTE id, const char *buf, UINT offset, UINT buflen )
405 WCHAR *str;
406 str = get_smbios_string( id, buf, offset, buflen );
407 set_reg_value( key, value, str ? str : L"" );
408 HeapFree( GetProcessHeap(), 0, str );
411 static void create_bios_baseboard_values( HKEY bios_key, const char *buf, UINT len )
413 const struct smbios_header *hdr;
414 const struct smbios_baseboard *baseboard;
415 UINT offset;
417 if (!(hdr = find_smbios_entry( SMBIOS_TYPE_BASEBOARD, buf, len ))) return;
418 baseboard = (const struct smbios_baseboard *)hdr;
419 offset = (const char *)baseboard - buf + baseboard->hdr.length;
421 set_value_from_smbios_string( bios_key, L"BaseBoardManufacturer", baseboard->vendor, buf, offset, len );
422 set_value_from_smbios_string( bios_key, L"BaseBoardProduct", baseboard->product, buf, offset, len );
423 set_value_from_smbios_string( bios_key, L"BaseBoardVersion", baseboard->version, buf, offset, len );
426 static void create_bios_bios_values( HKEY bios_key, const char *buf, UINT len )
428 const struct smbios_header *hdr;
429 const struct smbios_bios *bios;
430 UINT offset;
432 if (!(hdr = find_smbios_entry( SMBIOS_TYPE_BIOS, buf, len ))) return;
433 bios = (const struct smbios_bios *)hdr;
434 offset = (const char *)bios - buf + bios->hdr.length;
436 set_value_from_smbios_string( bios_key, L"BIOSVendor", bios->vendor, buf, offset, len );
437 set_value_from_smbios_string( bios_key, L"BIOSVersion", bios->version, buf, offset, len );
438 set_value_from_smbios_string( bios_key, L"BIOSReleaseDate", bios->date, buf, offset, len );
440 if (bios->hdr.length >= 0x18)
442 set_reg_value_dword( bios_key, L"BiosMajorRelease", bios->system_bios_major_release );
443 set_reg_value_dword( bios_key, L"BiosMinorRelease", bios->system_bios_minor_release );
444 set_reg_value_dword( bios_key, L"ECFirmwareMajorVersion", bios->ec_firmware_major_release );
445 set_reg_value_dword( bios_key, L"ECFirmwareMinorVersion", bios->ec_firmware_minor_release );
447 else
449 set_reg_value_dword( bios_key, L"BiosMajorRelease", 0xFF );
450 set_reg_value_dword( bios_key, L"BiosMinorRelease", 0xFF );
451 set_reg_value_dword( bios_key, L"ECFirmwareMajorVersion", 0xFF );
452 set_reg_value_dword( bios_key, L"ECFirmwareMinorVersion", 0xFF );
456 static void create_bios_system_values( HKEY bios_key, const char *buf, UINT len )
458 const struct smbios_header *hdr;
459 const struct smbios_system *system;
460 UINT offset;
462 if (!(hdr = find_smbios_entry( SMBIOS_TYPE_SYSTEM, buf, len ))) return;
463 system = (const struct smbios_system *)hdr;
464 offset = (const char *)system - buf + system->hdr.length;
466 set_value_from_smbios_string( bios_key, L"SystemManufacturer", system->vendor, buf, offset, len );
467 set_value_from_smbios_string( bios_key, L"SystemProductName", system->product, buf, offset, len );
468 set_value_from_smbios_string( bios_key, L"SystemVersion", system->version, buf, offset, len );
470 if (system->hdr.length >= 0x1B)
472 set_value_from_smbios_string( bios_key, L"SystemSKU", system->sku, buf, offset, len );
473 set_value_from_smbios_string( bios_key, L"SystemFamily", system->family, buf, offset, len );
475 else
477 set_value_from_smbios_string( bios_key, L"SystemSKU", 0, buf, offset, len );
478 set_value_from_smbios_string( bios_key, L"SystemFamily", 0, buf, offset, len );
482 static void create_bios_key( HKEY system_key )
484 HKEY bios_key;
485 UINT len;
486 char *buf;
488 if (RegCreateKeyExW( system_key, L"BIOS", 0, NULL, REG_OPTION_VOLATILE,
489 KEY_ALL_ACCESS, NULL, &bios_key, NULL ))
490 return;
492 len = GetSystemFirmwareTable( RSMB, 0, NULL, 0 );
493 if (!(buf = HeapAlloc( GetProcessHeap(), 0, len ))) goto done;
494 len = GetSystemFirmwareTable( RSMB, 0, buf, len );
496 create_bios_baseboard_values( bios_key, buf, len );
497 create_bios_bios_values( bios_key, buf, len );
498 create_bios_system_values( bios_key, buf, len );
500 done:
501 HeapFree( GetProcessHeap(), 0, buf );
502 RegCloseKey( bios_key );
505 /* create the volatile hardware registry keys */
506 static void create_hardware_registry_keys(void)
508 static const WCHAR SystemW[] = {'H','a','r','d','w','a','r','e','\\','D','e','s','c','r','i','p','t','i','o','n','\\',
509 'S','y','s','t','e','m',0};
510 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};
511 static const WCHAR cpuW[] = {'C','e','n','t','r','a','l','P','r','o','c','e','s','s','o','r',0};
512 static const WCHAR FeatureSetW[] = {'F','e','a','t','u','r','e','S','e','t',0};
513 static const WCHAR IdentifierW[] = {'I','d','e','n','t','i','f','i','e','r',0};
514 static const WCHAR ProcessorNameStringW[] = {'P','r','o','c','e','s','s','o','r','N','a','m','e','S','t','r','i','n','g',0};
515 static const WCHAR SysidW[] = {'A','T',' ','c','o','m','p','a','t','i','b','l','e',0};
516 static const WCHAR ARMSysidW[] = {'A','R','M',' ','p','r','o','c','e','s','s','o','r',' ','f','a','m','i','l','y',0};
517 static const WCHAR mhzKeyW[] = {'~','M','H','z',0};
518 static const WCHAR VendorIdentifierW[] = {'V','e','n','d','o','r','I','d','e','n','t','i','f','i','e','r',0};
519 static const WCHAR PercentDW[] = {'%','d',0};
520 static const WCHAR ARMCpuDescrW[] = {'A','R','M',' ','F','a','m','i','l','y',' ','%','d',' ','M','o','d','e','l',' ','%','d',
521 ' ','R','e','v','i','s','i','o','n',' ','%','d',0};
522 static const WCHAR x86W[] = {'x','8','6',0};
523 static const WCHAR intel64W[] = {'I','n','t','e','l','6','4',0};
524 static const WCHAR amd64W[] = {'A','M','D','6','4',0};
525 static const WCHAR authenticamdW[] = {'A','u','t','h','e','n','t','i','c','A','M','D',0};
526 unsigned int i;
527 HKEY hkey, system_key, cpu_key, fpu_key;
528 SYSTEM_CPU_INFORMATION sci;
529 PROCESSOR_POWER_INFORMATION* power_info;
530 ULONG sizeof_power_info = sizeof(PROCESSOR_POWER_INFORMATION) * NtCurrentTeb()->Peb->NumberOfProcessors;
531 WCHAR id[60], namestr[49], vendorid[13];
533 get_namestring( namestr );
534 get_vendorid( vendorid );
535 NtQuerySystemInformation( SystemCpuInformation, &sci, sizeof(sci), NULL );
537 power_info = HeapAlloc( GetProcessHeap(), 0, sizeof_power_info );
538 if (power_info == NULL)
539 return;
540 if (NtPowerInformation( ProcessorInformation, NULL, 0, power_info, sizeof_power_info ))
541 memset( power_info, 0, sizeof_power_info );
543 switch (sci.Architecture)
545 case PROCESSOR_ARCHITECTURE_ARM:
546 case PROCESSOR_ARCHITECTURE_ARM64:
547 swprintf( id, ARRAY_SIZE(id), ARMCpuDescrW, sci.Level, HIBYTE(sci.Revision), LOBYTE(sci.Revision) );
548 break;
550 case PROCESSOR_ARCHITECTURE_AMD64:
551 get_identifier( id, ARRAY_SIZE(id), !wcscmp(vendorid, authenticamdW) ? amd64W : intel64W );
552 break;
554 case PROCESSOR_ARCHITECTURE_INTEL:
555 default:
556 get_identifier( id, ARRAY_SIZE(id), x86W );
557 break;
560 if (RegCreateKeyExW( HKEY_LOCAL_MACHINE, SystemW, 0, NULL, REG_OPTION_VOLATILE,
561 KEY_ALL_ACCESS, NULL, &system_key, NULL ))
563 HeapFree( GetProcessHeap(), 0, power_info );
564 return;
567 switch (sci.Architecture)
569 case PROCESSOR_ARCHITECTURE_ARM:
570 case PROCESSOR_ARCHITECTURE_ARM64:
571 set_reg_value( system_key, IdentifierW, ARMSysidW );
572 break;
574 case PROCESSOR_ARCHITECTURE_INTEL:
575 case PROCESSOR_ARCHITECTURE_AMD64:
576 default:
577 set_reg_value( system_key, IdentifierW, SysidW );
578 break;
581 if (sci.Architecture == PROCESSOR_ARCHITECTURE_ARM ||
582 sci.Architecture == PROCESSOR_ARCHITECTURE_ARM64 ||
583 RegCreateKeyExW( system_key, fpuW, 0, NULL, REG_OPTION_VOLATILE,
584 KEY_ALL_ACCESS, NULL, &fpu_key, NULL ))
585 fpu_key = 0;
586 if (RegCreateKeyExW( system_key, cpuW, 0, NULL, REG_OPTION_VOLATILE,
587 KEY_ALL_ACCESS, NULL, &cpu_key, NULL ))
588 cpu_key = 0;
590 for (i = 0; i < NtCurrentTeb()->Peb->NumberOfProcessors; i++)
592 WCHAR numW[10];
594 swprintf( numW, ARRAY_SIZE(numW), PercentDW, i );
595 if (!RegCreateKeyExW( cpu_key, numW, 0, NULL, REG_OPTION_VOLATILE,
596 KEY_ALL_ACCESS, NULL, &hkey, NULL ))
598 RegSetValueExW( hkey, FeatureSetW, 0, REG_DWORD, (BYTE *)&sci.FeatureSet, sizeof(DWORD) );
599 set_reg_value( hkey, IdentifierW, id );
600 /* TODO: report ARM properly */
601 set_reg_value( hkey, ProcessorNameStringW, namestr );
602 set_reg_value( hkey, VendorIdentifierW, vendorid );
603 RegSetValueExW( hkey, mhzKeyW, 0, REG_DWORD, (BYTE *)&power_info[i].MaxMhz, sizeof(DWORD) );
604 RegCloseKey( hkey );
606 if (sci.Architecture != PROCESSOR_ARCHITECTURE_ARM &&
607 sci.Architecture != PROCESSOR_ARCHITECTURE_ARM64 &&
608 !RegCreateKeyExW( fpu_key, numW, 0, NULL, REG_OPTION_VOLATILE,
609 KEY_ALL_ACCESS, NULL, &hkey, NULL ))
611 set_reg_value( hkey, IdentifierW, id );
612 RegCloseKey( hkey );
616 create_bios_key( system_key );
618 RegCloseKey( fpu_key );
619 RegCloseKey( cpu_key );
620 RegCloseKey( system_key );
621 HeapFree( GetProcessHeap(), 0, power_info );
625 /* create the DynData registry keys */
626 static void create_dynamic_registry_keys(void)
628 static const WCHAR StatDataW[] = {'P','e','r','f','S','t','a','t','s','\\',
629 'S','t','a','t','D','a','t','a',0};
630 static const WCHAR ConfigManagerW[] = {'C','o','n','f','i','g',' ','M','a','n','a','g','e','r','\\',
631 'E','n','u','m',0};
632 HKEY key;
634 if (!RegCreateKeyExW( HKEY_DYN_DATA, StatDataW, 0, NULL, 0, KEY_WRITE, NULL, &key, NULL ))
635 RegCloseKey( key );
636 if (!RegCreateKeyExW( HKEY_DYN_DATA, ConfigManagerW, 0, NULL, 0, KEY_WRITE, NULL, &key, NULL ))
637 RegCloseKey( key );
640 /* create the platform-specific environment registry keys */
641 static void create_environment_registry_keys( void )
643 static const WCHAR EnvironW[] = {'S','y','s','t','e','m','\\',
644 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
645 'C','o','n','t','r','o','l','\\',
646 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
647 'E','n','v','i','r','o','n','m','e','n','t',0};
648 static const WCHAR NumProcW[] = {'N','U','M','B','E','R','_','O','F','_','P','R','O','C','E','S','S','O','R','S',0};
649 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};
650 static const WCHAR x86W[] = {'x','8','6',0};
651 static const WCHAR intel64W[] = {'I','n','t','e','l','6','4',0};
652 static const WCHAR amd64W[] = {'A','M','D','6','4',0};
653 static const WCHAR authenticamdW[] = {'A','u','t','h','e','n','t','i','c','A','M','D',0};
654 static const WCHAR commaW[] = {',',' ',0};
655 static const WCHAR ProcIdW[] = {'P','R','O','C','E','S','S','O','R','_','I','D','E','N','T','I','F','I','E','R',0};
656 static const WCHAR ProcLvlW[] = {'P','R','O','C','E','S','S','O','R','_','L','E','V','E','L',0};
657 static const WCHAR ProcRevW[] = {'P','R','O','C','E','S','S','O','R','_','R','E','V','I','S','I','O','N',0};
658 static const WCHAR PercentDW[] = {'%','d',0};
659 static const WCHAR Percent04XW[] = {'%','0','4','x',0};
660 static const WCHAR ARMCpuDescrW[] = {'A','R','M',' ','F','a','m','i','l','y',' ','%','d',' ','M','o','d','e','l',' ','%','d',
661 ' ','R','e','v','i','s','i','o','n',' ','%','d',0};
662 HKEY env_key;
663 SYSTEM_CPU_INFORMATION sci;
664 WCHAR buffer[60], vendorid[13];
665 const WCHAR *arch, *parch;
667 if (RegCreateKeyW( HKEY_LOCAL_MACHINE, EnvironW, &env_key )) return;
669 get_vendorid( vendorid );
670 NtQuerySystemInformation( SystemCpuInformation, &sci, sizeof(sci), NULL );
672 swprintf( buffer, ARRAY_SIZE(buffer), PercentDW, NtCurrentTeb()->Peb->NumberOfProcessors );
673 set_reg_value( env_key, NumProcW, buffer );
675 switch (sci.Architecture)
677 case PROCESSOR_ARCHITECTURE_AMD64:
678 arch = amd64W;
679 parch = !wcscmp(vendorid, authenticamdW) ? amd64W : intel64W;
680 break;
682 case PROCESSOR_ARCHITECTURE_INTEL:
683 default:
684 arch = parch = x86W;
685 break;
687 set_reg_value( env_key, ProcArchW, arch );
689 switch (sci.Architecture)
691 case PROCESSOR_ARCHITECTURE_ARM:
692 case PROCESSOR_ARCHITECTURE_ARM64:
693 swprintf( buffer, ARRAY_SIZE(buffer), ARMCpuDescrW,
694 sci.Level, HIBYTE(sci.Revision), LOBYTE(sci.Revision) );
695 break;
697 case PROCESSOR_ARCHITECTURE_AMD64:
698 case PROCESSOR_ARCHITECTURE_INTEL:
699 default:
700 get_identifier( buffer, ARRAY_SIZE(buffer), parch );
701 lstrcatW( buffer, commaW );
702 lstrcatW( buffer, vendorid );
703 break;
705 set_reg_value( env_key, ProcIdW, buffer );
707 swprintf( buffer, ARRAY_SIZE(buffer), PercentDW, sci.Level );
708 set_reg_value( env_key, ProcLvlW, buffer );
710 swprintf( buffer, ARRAY_SIZE(buffer), Percent04XW, sci.Revision );
711 set_reg_value( env_key, ProcRevW, buffer );
713 RegCloseKey( env_key );
716 static void create_volatile_environment_registry_key(void)
718 static const WCHAR VolatileEnvW[] = {'V','o','l','a','t','i','l','e',' ','E','n','v','i','r','o','n','m','e','n','t',0};
719 static const WCHAR AppDataW[] = {'A','P','P','D','A','T','A',0};
720 static const WCHAR ClientNameW[] = {'C','L','I','E','N','T','N','A','M','E',0};
721 static const WCHAR HomeDriveW[] = {'H','O','M','E','D','R','I','V','E',0};
722 static const WCHAR HomePathW[] = {'H','O','M','E','P','A','T','H',0};
723 static const WCHAR HomeShareW[] = {'H','O','M','E','S','H','A','R','E',0};
724 static const WCHAR LocalAppDataW[] = {'L','O','C','A','L','A','P','P','D','A','T','A',0};
725 static const WCHAR LogonServerW[] = {'L','O','G','O','N','S','E','R','V','E','R',0};
726 static const WCHAR SessionNameW[] = {'S','E','S','S','I','O','N','N','A','M','E',0};
727 static const WCHAR UserNameW[] = {'U','S','E','R','N','A','M','E',0};
728 static const WCHAR UserDomainW[] = {'U','S','E','R','D','O','M','A','I','N',0};
729 static const WCHAR UserProfileW[] = {'U','S','E','R','P','R','O','F','I','L','E',0};
730 static const WCHAR ConsoleW[] = {'C','o','n','s','o','l','e',0};
731 static const WCHAR EmptyW[] = {0};
732 WCHAR path[MAX_PATH];
733 WCHAR computername[MAX_COMPUTERNAME_LENGTH + 1 + 2];
734 DWORD size;
735 HKEY hkey;
736 HRESULT hr;
738 if (RegCreateKeyExW( HKEY_CURRENT_USER, VolatileEnvW, 0, NULL, REG_OPTION_VOLATILE,
739 KEY_ALL_ACCESS, NULL, &hkey, NULL ))
740 return;
742 hr = SHGetFolderPathW( NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, path );
743 if (SUCCEEDED(hr)) set_reg_value( hkey, AppDataW, path );
745 set_reg_value( hkey, ClientNameW, ConsoleW );
747 /* Write the profile path's drive letter and directory components into
748 * HOMEDRIVE and HOMEPATH respectively. */
749 hr = SHGetFolderPathW( NULL, CSIDL_PROFILE | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, path );
750 if (SUCCEEDED(hr))
752 set_reg_value( hkey, UserProfileW, path );
753 set_reg_value( hkey, HomePathW, path + 2 );
754 path[2] = '\0';
755 set_reg_value( hkey, HomeDriveW, path );
758 size = ARRAY_SIZE(path);
759 if (GetUserNameW( path, &size )) set_reg_value( hkey, UserNameW, path );
761 set_reg_value( hkey, HomeShareW, EmptyW );
763 hr = SHGetFolderPathW( NULL, CSIDL_LOCAL_APPDATA | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, path );
764 if (SUCCEEDED(hr))
765 set_reg_value( hkey, LocalAppDataW, path );
767 size = ARRAY_SIZE(computername) - 2;
768 if (GetComputerNameW(&computername[2], &size))
770 set_reg_value( hkey, UserDomainW, &computername[2] );
771 computername[0] = computername[1] = '\\';
772 set_reg_value( hkey, LogonServerW, computername );
775 set_reg_value( hkey, SessionNameW, ConsoleW );
776 RegCloseKey( hkey );
779 /* Performs the rename operations dictated in %SystemRoot%\Wininit.ini.
780 * Returns FALSE if there was an error, or otherwise if all is ok.
782 static BOOL wininit(void)
784 static const WCHAR nulW[] = {'N','U','L',0};
785 static const WCHAR renameW[] = {'r','e','n','a','m','e',0};
786 static const WCHAR wininitW[] = {'w','i','n','i','n','i','t','.','i','n','i',0};
787 static const WCHAR wininitbakW[] = {'w','i','n','i','n','i','t','.','b','a','k',0};
788 WCHAR initial_buffer[1024];
789 WCHAR *str, *buffer = initial_buffer;
790 DWORD size = ARRAY_SIZE(initial_buffer);
791 DWORD res;
793 for (;;)
795 if (!(res = GetPrivateProfileSectionW( renameW, buffer, size, wininitW ))) return TRUE;
796 if (res < size - 2) break;
797 if (buffer != initial_buffer) HeapFree( GetProcessHeap(), 0, buffer );
798 size *= 2;
799 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return FALSE;
802 for (str = buffer; *str; str += lstrlenW(str) + 1)
804 WCHAR *value;
806 if (*str == ';') continue; /* comment */
807 if (!(value = wcschr( str, '=' ))) continue;
809 /* split the line into key and value */
810 *value++ = 0;
812 if (!lstrcmpiW( nulW, str ))
814 WINE_TRACE("Deleting file %s\n", wine_dbgstr_w(value) );
815 if( !DeleteFileW( value ) )
816 WINE_WARN("Error deleting file %s\n", wine_dbgstr_w(value) );
818 else
820 WINE_TRACE("Renaming file %s to %s\n", wine_dbgstr_w(value), wine_dbgstr_w(str) );
822 if( !MoveFileExW(value, str, MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) )
823 WINE_WARN("Error renaming %s to %s\n", wine_dbgstr_w(value), wine_dbgstr_w(str) );
825 str = value;
828 if (buffer != initial_buffer) HeapFree( GetProcessHeap(), 0, buffer );
830 if( !MoveFileExW( wininitW, wininitbakW, MOVEFILE_REPLACE_EXISTING) )
832 WINE_ERR("Couldn't rename wininit.ini, error %d\n", GetLastError() );
834 return FALSE;
837 return TRUE;
840 static BOOL pendingRename(void)
842 static const WCHAR ValueName[] = {'P','e','n','d','i','n','g',
843 'F','i','l','e','R','e','n','a','m','e',
844 'O','p','e','r','a','t','i','o','n','s',0};
845 static const WCHAR SessionW[] = { 'S','y','s','t','e','m','\\',
846 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
847 'C','o','n','t','r','o','l','\\',
848 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
849 WCHAR *buffer=NULL;
850 const WCHAR *src=NULL, *dst=NULL;
851 DWORD dataLength=0;
852 HKEY hSession=NULL;
853 DWORD res;
855 WINE_TRACE("Entered\n");
857 if( (res=RegOpenKeyExW( HKEY_LOCAL_MACHINE, SessionW, 0, KEY_ALL_ACCESS, &hSession ))
858 !=ERROR_SUCCESS )
860 WINE_TRACE("The key was not found - skipping\n");
861 return TRUE;
864 res=RegQueryValueExW( hSession, ValueName, NULL, NULL /* The value type does not really interest us, as it is not
865 truly a REG_MULTI_SZ anyways */,
866 NULL, &dataLength );
867 if( res==ERROR_FILE_NOT_FOUND )
869 /* No value - nothing to do. Great! */
870 WINE_TRACE("Value not present - nothing to rename\n");
871 res=TRUE;
872 goto end;
875 if( res!=ERROR_SUCCESS )
877 WINE_ERR("Couldn't query value's length (%d)\n", res );
878 res=FALSE;
879 goto end;
882 buffer=HeapAlloc( GetProcessHeap(),0,dataLength );
883 if( buffer==NULL )
885 WINE_ERR("Couldn't allocate %u bytes for the value\n", dataLength );
886 res=FALSE;
887 goto end;
890 res=RegQueryValueExW( hSession, ValueName, NULL, NULL, (LPBYTE)buffer, &dataLength );
891 if( res!=ERROR_SUCCESS )
893 WINE_ERR("Couldn't query value after successfully querying before (%u),\n"
894 "please report to wine-devel@winehq.org\n", res);
895 res=FALSE;
896 goto end;
899 /* Make sure that the data is long enough and ends with two NULLs. This
900 * simplifies the code later on.
902 if( dataLength<2*sizeof(buffer[0]) ||
903 buffer[dataLength/sizeof(buffer[0])-1]!='\0' ||
904 buffer[dataLength/sizeof(buffer[0])-2]!='\0' )
906 WINE_ERR("Improper value format - doesn't end with NULL\n");
907 res=FALSE;
908 goto end;
911 for( src=buffer; (src-buffer)*sizeof(src[0])<dataLength && *src!='\0';
912 src=dst+lstrlenW(dst)+1 )
914 DWORD dwFlags=0;
916 WINE_TRACE("processing next command\n");
918 dst=src+lstrlenW(src)+1;
920 /* We need to skip the \??\ header */
921 if( src[0]=='\\' && src[1]=='?' && src[2]=='?' && src[3]=='\\' )
922 src+=4;
924 if( dst[0]=='!' )
926 dwFlags|=MOVEFILE_REPLACE_EXISTING;
927 dst++;
930 if( dst[0]=='\\' && dst[1]=='?' && dst[2]=='?' && dst[3]=='\\' )
931 dst+=4;
933 if( *dst!='\0' )
935 /* Rename the file */
936 MoveFileExW( src, dst, dwFlags );
937 } else
939 /* Delete the file or directory */
940 if (!RemoveDirectoryW( src ) && GetLastError() == ERROR_DIRECTORY) DeleteFileW( src );
944 if((res=RegDeleteValueW(hSession, ValueName))!=ERROR_SUCCESS )
946 WINE_ERR("Error deleting the value (%u)\n", GetLastError() );
947 res=FALSE;
948 } else
949 res=TRUE;
951 end:
952 HeapFree(GetProcessHeap(), 0, buffer);
954 if( hSession!=NULL )
955 RegCloseKey( hSession );
957 return res;
960 #define INVALID_RUNCMD_RETURN -1
962 * This function runs the specified command in the specified dir.
963 * [in,out] cmdline - the command line to run. The function may change the passed buffer.
964 * [in] dir - the dir to run the command in. If it is NULL, then the current dir is used.
965 * [in] wait - whether to wait for the run program to finish before returning.
966 * [in] minimized - Whether to ask the program to run minimized.
968 * Returns:
969 * If running the process failed, returns INVALID_RUNCMD_RETURN. Use GetLastError to get the error code.
970 * If wait is FALSE - returns 0 if successful.
971 * If wait is TRUE - returns the program's return value.
973 static DWORD runCmd(LPWSTR cmdline, LPCWSTR dir, BOOL wait, BOOL minimized)
975 STARTUPINFOW si;
976 PROCESS_INFORMATION info;
977 DWORD exit_code=0;
979 memset(&si, 0, sizeof(si));
980 si.cb=sizeof(si);
981 if( minimized )
983 si.dwFlags=STARTF_USESHOWWINDOW;
984 si.wShowWindow=SW_MINIMIZE;
986 memset(&info, 0, sizeof(info));
988 if( !CreateProcessW(NULL, cmdline, NULL, NULL, FALSE, 0, NULL, dir, &si, &info) )
990 WINE_WARN("Failed to run command %s (%d)\n", wine_dbgstr_w(cmdline), GetLastError() );
991 return INVALID_RUNCMD_RETURN;
994 WINE_TRACE("Successfully ran command %s - Created process handle %p\n",
995 wine_dbgstr_w(cmdline), info.hProcess );
997 if(wait)
998 { /* wait for the process to exit */
999 WaitForSingleObject(info.hProcess, INFINITE);
1000 GetExitCodeProcess(info.hProcess, &exit_code);
1003 CloseHandle( info.hThread );
1004 CloseHandle( info.hProcess );
1006 return exit_code;
1009 static void process_run_key( HKEY key, const WCHAR *keyname, BOOL delete, BOOL synchronous )
1011 HKEY runkey;
1012 LONG res;
1013 DWORD disp, i, max_cmdline = 0, max_value = 0;
1014 WCHAR *cmdline = NULL, *value = NULL;
1016 if (RegCreateKeyExW( key, keyname, 0, NULL, 0, delete ? KEY_ALL_ACCESS : KEY_READ, NULL, &runkey, &disp ))
1017 return;
1019 if (disp == REG_CREATED_NEW_KEY)
1020 goto end;
1022 if (RegQueryInfoKeyW( runkey, NULL, NULL, NULL, NULL, NULL, NULL, &i, &max_value, &max_cmdline, NULL, NULL ))
1023 goto end;
1025 if (!i)
1027 WINE_TRACE( "No commands to execute.\n" );
1028 goto end;
1030 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, max_cmdline )))
1032 WINE_ERR( "Couldn't allocate memory for the commands to be executed.\n" );
1033 goto end;
1035 if (!(value = HeapAlloc( GetProcessHeap(), 0, ++max_value * sizeof(*value) )))
1037 WINE_ERR( "Couldn't allocate memory for the value names.\n" );
1038 goto end;
1041 while (i)
1043 DWORD len = max_value, len_data = max_cmdline, type;
1045 if ((res = RegEnumValueW( runkey, --i, value, &len, 0, &type, (BYTE *)cmdline, &len_data )))
1047 WINE_ERR( "Couldn't read value %u (%d).\n", i, res );
1048 continue;
1050 if (delete && (res = RegDeleteValueW( runkey, value )))
1052 WINE_ERR( "Couldn't delete value %u (%d). Running command anyways.\n", i, res );
1054 if (type != REG_SZ)
1056 WINE_ERR( "Incorrect type of value %u (%u).\n", i, type );
1057 continue;
1059 if (runCmd( cmdline, NULL, synchronous, FALSE ) == INVALID_RUNCMD_RETURN)
1061 WINE_ERR( "Error running cmd %s (%u).\n", wine_dbgstr_w(cmdline), GetLastError() );
1063 WINE_TRACE( "Done processing cmd %u.\n", i );
1066 end:
1067 HeapFree( GetProcessHeap(), 0, value );
1068 HeapFree( GetProcessHeap(), 0, cmdline );
1069 RegCloseKey( runkey );
1070 WINE_TRACE( "Done.\n" );
1074 * Process a "Run" type registry key.
1075 * hkRoot is the HKEY from which "Software\Microsoft\Windows\CurrentVersion" is
1076 * opened.
1077 * szKeyName is the key holding the actual entries.
1078 * bDelete tells whether we should delete each value right before executing it.
1079 * bSynchronous tells whether we should wait for the prog to complete before
1080 * going on to the next prog.
1082 static void ProcessRunKeys( HKEY root, const WCHAR *keyname, BOOL delete, BOOL synchronous )
1084 static const WCHAR keypathW[] =
1085 {'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\',
1086 'W','i','n','d','o','w','s','\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
1087 HKEY key;
1089 if (root == HKEY_LOCAL_MACHINE)
1091 WINE_TRACE( "Processing %s entries under HKLM.\n", wine_dbgstr_w(keyname) );
1092 if (!RegCreateKeyExW( root, keypathW, 0, NULL, 0, KEY_READ, NULL, &key, NULL ))
1094 process_run_key( key, keyname, delete, synchronous );
1095 RegCloseKey( key );
1097 if (is_64bit && !RegCreateKeyExW( root, keypathW, 0, NULL, 0, KEY_READ|KEY_WOW64_32KEY, NULL, &key, NULL ))
1099 process_run_key( key, keyname, delete, synchronous );
1100 RegCloseKey( key );
1103 else
1105 WINE_TRACE( "Processing %s entries under HKCU.\n", wine_dbgstr_w(keyname) );
1106 if (!RegCreateKeyExW( root, keypathW, 0, NULL, 0, KEY_READ, NULL, &key, NULL ))
1108 process_run_key( key, keyname, delete, synchronous );
1109 RegCloseKey( key );
1115 * WFP is Windows File Protection, in NT5 and Windows 2000 it maintains a cache
1116 * of known good dlls and scans through and replaces corrupted DLLs with these
1117 * known good versions. The only programs that should install into this dll
1118 * cache are Windows Updates and IE (which is treated like a Windows Update)
1120 * Implementing this allows installing ie in win2k mode to actually install the
1121 * system dlls that we expect and need
1123 static int ProcessWindowsFileProtection(void)
1125 static const WCHAR winlogonW[] = {'S','o','f','t','w','a','r','e','\\',
1126 'M','i','c','r','o','s','o','f','t','\\',
1127 'W','i','n','d','o','w','s',' ','N','T','\\',
1128 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
1129 'W','i','n','l','o','g','o','n',0};
1130 static const WCHAR cachedirW[] = {'S','F','C','D','l','l','C','a','c','h','e','D','i','r',0};
1131 static const WCHAR dllcacheW[] = {'\\','d','l','l','c','a','c','h','e','\\','*',0};
1132 static const WCHAR wildcardW[] = {'\\','*',0};
1133 WIN32_FIND_DATAW finddata;
1134 HANDLE find_handle;
1135 BOOL find_rc;
1136 DWORD rc;
1137 HKEY hkey;
1138 LPWSTR dllcache = NULL;
1140 if (!RegOpenKeyW( HKEY_LOCAL_MACHINE, winlogonW, &hkey ))
1142 DWORD sz = 0;
1143 if (!RegQueryValueExW( hkey, cachedirW, 0, NULL, NULL, &sz))
1145 sz += sizeof(WCHAR);
1146 dllcache = HeapAlloc(GetProcessHeap(),0,sz + sizeof(wildcardW));
1147 RegQueryValueExW( hkey, cachedirW, 0, NULL, (LPBYTE)dllcache, &sz);
1148 lstrcatW( dllcache, wildcardW );
1151 RegCloseKey(hkey);
1153 if (!dllcache)
1155 DWORD sz = GetSystemDirectoryW( NULL, 0 );
1156 dllcache = HeapAlloc( GetProcessHeap(), 0, sz * sizeof(WCHAR) + sizeof(dllcacheW));
1157 GetSystemDirectoryW( dllcache, sz );
1158 lstrcatW( dllcache, dllcacheW );
1161 find_handle = FindFirstFileW(dllcache,&finddata);
1162 dllcache[ lstrlenW(dllcache) - 2] = 0; /* strip off wildcard */
1163 find_rc = find_handle != INVALID_HANDLE_VALUE;
1164 while (find_rc)
1166 static const WCHAR dotW[] = {'.',0};
1167 static const WCHAR dotdotW[] = {'.','.',0};
1168 WCHAR targetpath[MAX_PATH];
1169 WCHAR currentpath[MAX_PATH];
1170 UINT sz;
1171 UINT sz2;
1172 WCHAR tempfile[MAX_PATH];
1174 if (wcscmp(finddata.cFileName,dotW) == 0 || wcscmp(finddata.cFileName,dotdotW) == 0)
1176 find_rc = FindNextFileW(find_handle,&finddata);
1177 continue;
1180 sz = MAX_PATH;
1181 sz2 = MAX_PATH;
1182 VerFindFileW(VFFF_ISSHAREDFILE, finddata.cFileName, windowsdir,
1183 windowsdir, currentpath, &sz, targetpath, &sz2);
1184 sz = MAX_PATH;
1185 rc = VerInstallFileW(0, finddata.cFileName, finddata.cFileName,
1186 dllcache, targetpath, currentpath, tempfile, &sz);
1187 if (rc != ERROR_SUCCESS)
1189 WINE_WARN("WFP: %s error 0x%x\n",wine_dbgstr_w(finddata.cFileName),rc);
1190 DeleteFileW(tempfile);
1193 /* now delete the source file so that we don't try to install it over and over again */
1194 lstrcpynW( targetpath, dllcache, MAX_PATH - 1 );
1195 sz = lstrlenW( targetpath );
1196 targetpath[sz++] = '\\';
1197 lstrcpynW( targetpath + sz, finddata.cFileName, MAX_PATH - sz );
1198 if (!DeleteFileW( targetpath ))
1199 WINE_WARN( "failed to delete %s: error %u\n", wine_dbgstr_w(targetpath), GetLastError() );
1201 find_rc = FindNextFileW(find_handle,&finddata);
1203 FindClose(find_handle);
1204 HeapFree(GetProcessHeap(),0,dllcache);
1205 return 1;
1208 static BOOL start_services_process(void)
1210 static const WCHAR svcctl_started_event[] = SVCCTL_STARTED_EVENT;
1211 static const WCHAR services[] = {'\\','s','e','r','v','i','c','e','s','.','e','x','e',0};
1212 PROCESS_INFORMATION pi;
1213 STARTUPINFOW si;
1214 HANDLE wait_handles[2];
1215 WCHAR path[MAX_PATH];
1217 if (!GetSystemDirectoryW(path, MAX_PATH - lstrlenW(services)))
1218 return FALSE;
1219 lstrcatW(path, services);
1220 ZeroMemory(&si, sizeof(si));
1221 si.cb = sizeof(si);
1222 if (!CreateProcessW(path, path, NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &si, &pi))
1224 WINE_ERR("Couldn't start services.exe: error %u\n", GetLastError());
1225 return FALSE;
1227 CloseHandle(pi.hThread);
1229 wait_handles[0] = CreateEventW(NULL, TRUE, FALSE, svcctl_started_event);
1230 wait_handles[1] = pi.hProcess;
1232 /* wait for the event to become available or the process to exit */
1233 if ((WaitForMultipleObjects(2, wait_handles, FALSE, INFINITE)) == WAIT_OBJECT_0 + 1)
1235 DWORD exit_code;
1236 GetExitCodeProcess(pi.hProcess, &exit_code);
1237 WINE_ERR("Unexpected termination of services.exe - exit code %d\n", exit_code);
1238 CloseHandle(pi.hProcess);
1239 CloseHandle(wait_handles[0]);
1240 return FALSE;
1243 CloseHandle(pi.hProcess);
1244 CloseHandle(wait_handles[0]);
1245 return TRUE;
1248 static INT_PTR CALLBACK wait_dlgproc( HWND hwnd, UINT msg, WPARAM wp, LPARAM lp )
1250 switch (msg)
1252 case WM_INITDIALOG:
1254 DWORD len;
1255 WCHAR *buffer, text[1024];
1256 const WCHAR *name = (WCHAR *)lp;
1257 HICON icon = LoadImageW( 0, (LPCWSTR)IDI_WINLOGO, IMAGE_ICON, 48, 48, LR_SHARED );
1258 SendDlgItemMessageW( hwnd, IDC_WAITICON, STM_SETICON, (WPARAM)icon, 0 );
1259 SendDlgItemMessageW( hwnd, IDC_WAITTEXT, WM_GETTEXT, 1024, (LPARAM)text );
1260 len = lstrlenW(text) + lstrlenW(name) + 1;
1261 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
1262 swprintf( buffer, len, text, name );
1263 SendDlgItemMessageW( hwnd, IDC_WAITTEXT, WM_SETTEXT, 0, (LPARAM)buffer );
1264 HeapFree( GetProcessHeap(), 0, buffer );
1266 break;
1268 return 0;
1271 static HWND show_wait_window(void)
1273 HWND hwnd = CreateDialogParamW( GetModuleHandleW(0), MAKEINTRESOURCEW(IDD_WAITDLG), 0,
1274 wait_dlgproc, (LPARAM)prettyprint_configdir() );
1275 ShowWindow( hwnd, SW_SHOWNORMAL );
1276 return hwnd;
1279 static HANDLE start_rundll32( const WCHAR *inf_path, BOOL wow64 )
1281 static const WCHAR rundll[] = {'\\','r','u','n','d','l','l','3','2','.','e','x','e',0};
1282 static const WCHAR setupapi[] = {' ','s','e','t','u','p','a','p','i',',',
1283 'I','n','s','t','a','l','l','H','i','n','f','S','e','c','t','i','o','n',0};
1284 static const WCHAR definstall[] = {' ','D','e','f','a','u','l','t','I','n','s','t','a','l','l',0};
1285 static const WCHAR wowinstall[] = {' ','W','o','w','6','4','I','n','s','t','a','l','l',0};
1286 static const WCHAR flags[] = {' ','1','2','8',' ',0};
1288 WCHAR app[MAX_PATH + ARRAY_SIZE(rundll)];
1289 STARTUPINFOW si;
1290 PROCESS_INFORMATION pi;
1291 WCHAR *buffer;
1292 DWORD len;
1294 memset( &si, 0, sizeof(si) );
1295 si.cb = sizeof(si);
1297 if (wow64)
1299 if (!GetSystemWow64DirectoryW( app, MAX_PATH )) return 0; /* not on 64-bit */
1301 else GetSystemDirectoryW( app, MAX_PATH );
1303 lstrcatW( app, rundll );
1305 len = lstrlenW(app) + ARRAY_SIZE(setupapi) + ARRAY_SIZE(definstall) + ARRAY_SIZE(flags) + lstrlenW(inf_path);
1307 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) ))) return 0;
1309 lstrcpyW( buffer, app );
1310 lstrcatW( buffer, setupapi );
1311 lstrcatW( buffer, wow64 ? wowinstall : definstall );
1312 lstrcatW( buffer, flags );
1313 lstrcatW( buffer, inf_path );
1315 if (CreateProcessW( app, buffer, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ))
1316 CloseHandle( pi.hThread );
1317 else
1318 pi.hProcess = 0;
1320 HeapFree( GetProcessHeap(), 0, buffer );
1321 return pi.hProcess;
1324 static void install_root_pnp_devices(void)
1326 static const struct
1328 const char *name;
1329 const char *hardware_id;
1330 const char *infpath;
1332 root_devices[] =
1334 {"root\\wine\\winebus", "root\\winebus\0", "C:\\windows\\inf\\winebus.inf"},
1335 {"root\\wine\\wineusb", "root\\wineusb\0", "C:\\windows\\inf\\wineusb.inf"},
1337 SP_DEVINFO_DATA device = {sizeof(device)};
1338 unsigned int i;
1339 HDEVINFO set;
1341 if ((set = SetupDiCreateDeviceInfoList( NULL, NULL )) == INVALID_HANDLE_VALUE)
1343 WINE_ERR("Failed to create device info list, error %#x.\n", GetLastError());
1344 return;
1347 for (i = 0; i < ARRAY_SIZE(root_devices); ++i)
1349 if (!SetupDiCreateDeviceInfoA( set, root_devices[i].name, &GUID_NULL, NULL, NULL, 0, &device))
1351 if (GetLastError() != ERROR_DEVINST_ALREADY_EXISTS)
1352 WINE_ERR("Failed to create device %s, error %#x.\n", debugstr_a(root_devices[i].name), GetLastError());
1353 continue;
1356 if (!SetupDiSetDeviceRegistryPropertyA(set, &device, SPDRP_HARDWAREID,
1357 (const BYTE *)root_devices[i].hardware_id, (strlen(root_devices[i].hardware_id) + 2) * sizeof(WCHAR)))
1359 WINE_ERR("Failed to set hardware id for %s, error %#x.\n", debugstr_a(root_devices[i].name), GetLastError());
1360 continue;
1363 if (!SetupDiCallClassInstaller(DIF_REGISTERDEVICE, set, &device))
1365 WINE_ERR("Failed to register device %s, error %#x.\n", debugstr_a(root_devices[i].name), GetLastError());
1366 continue;
1369 if (!UpdateDriverForPlugAndPlayDevicesA(NULL, root_devices[i].hardware_id, root_devices[i].infpath, 0, NULL))
1370 WINE_ERR("Failed to install drivers for %s, error %#x.\n", debugstr_a(root_devices[i].name), GetLastError());
1373 SetupDiDestroyDeviceInfoList(set);
1376 static void update_user_profile(void)
1378 static const WCHAR profile_list[] = {'S','o','f','t','w','a','r','e','\\',
1379 'M','i','c','r','o','s','o','f','t','\\',
1380 'W','i','n','d','o','w','s',' ','N','T','\\',
1381 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
1382 'P','r','o','f','i','l','e','L','i','s','t',0};
1383 static const WCHAR profile_image_path[] = {'P','r','o','f','i','l','e','I','m','a','g','e','P','a','t','h',0};
1384 char token_buf[sizeof(TOKEN_USER) + sizeof(SID) + sizeof(DWORD) * SID_MAX_SUB_AUTHORITIES];
1385 HANDLE token;
1386 WCHAR profile[MAX_PATH], *sid;
1387 DWORD size;
1388 HKEY hkey, profile_hkey;
1390 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token))
1391 return;
1393 size = sizeof(token_buf);
1394 GetTokenInformation(token, TokenUser, token_buf, size, &size);
1395 CloseHandle(token);
1397 ConvertSidToStringSidW(((TOKEN_USER *)token_buf)->User.Sid, &sid);
1399 if (!RegCreateKeyExW(HKEY_LOCAL_MACHINE, profile_list, 0, NULL, 0,
1400 KEY_ALL_ACCESS, NULL, &hkey, NULL))
1402 if (!RegCreateKeyExW(hkey, sid, 0, NULL, 0,
1403 KEY_ALL_ACCESS, NULL, &profile_hkey, NULL))
1405 DWORD flags = 0;
1406 if (SHGetSpecialFolderPathW(NULL, profile, CSIDL_PROFILE, TRUE))
1407 set_reg_value(profile_hkey, profile_image_path, profile);
1408 RegSetValueExW( profile_hkey, L"Flags", 0, REG_DWORD, (const BYTE *)&flags, sizeof(flags) );
1409 RegCloseKey(profile_hkey);
1412 RegCloseKey(hkey);
1415 LocalFree(sid);
1418 /* execute rundll32 on the wine.inf file if necessary */
1419 static void update_wineprefix( BOOL force )
1421 const WCHAR *config_dir = _wgetenv( wineconfigdirW );
1422 WCHAR *inf_path = get_wine_inf_path();
1423 int fd;
1424 struct stat st;
1426 if (!inf_path)
1428 WINE_MESSAGE( "wine: failed to update %s, wine.inf not found\n", debugstr_w( config_dir ));
1429 return;
1431 if ((fd = _wopen( inf_path, O_RDONLY )) == -1)
1433 WINE_MESSAGE( "wine: failed to update %s with %s: %s\n",
1434 debugstr_w(config_dir), debugstr_w(inf_path), strerror(errno) );
1435 goto done;
1437 fstat( fd, &st );
1438 close( fd );
1440 if (update_timestamp( config_dir, st.st_mtime ) || force)
1442 HANDLE process;
1443 DWORD count = 0;
1445 if ((process = start_rundll32( inf_path, FALSE )))
1447 HWND hwnd = show_wait_window();
1448 for (;;)
1450 MSG msg;
1451 DWORD res = MsgWaitForMultipleObjects( 1, &process, FALSE, INFINITE, QS_ALLINPUT );
1452 if (res == WAIT_OBJECT_0)
1454 CloseHandle( process );
1455 if (count++ || !(process = start_rundll32( inf_path, TRUE ))) break;
1457 else while (PeekMessageW( &msg, 0, 0, 0, PM_REMOVE )) DispatchMessageW( &msg );
1459 DestroyWindow( hwnd );
1461 install_root_pnp_devices();
1462 update_user_profile();
1464 WINE_MESSAGE( "wine: configuration in %s has been updated.\n", debugstr_w(prettyprint_configdir()) );
1467 done:
1468 HeapFree( GetProcessHeap(), 0, inf_path );
1471 /* Process items in the StartUp group of the user's Programs under the Start Menu. Some installers put
1472 * shell links here to restart themselves after boot. */
1473 static BOOL ProcessStartupItems(void)
1475 BOOL ret = FALSE;
1476 HRESULT hr;
1477 IShellFolder *psfDesktop = NULL, *psfStartup = NULL;
1478 LPITEMIDLIST pidlStartup = NULL, pidlItem;
1479 ULONG NumPIDLs;
1480 IEnumIDList *iEnumList = NULL;
1481 STRRET strret;
1482 WCHAR wszCommand[MAX_PATH];
1484 WINE_TRACE("Processing items in the StartUp folder.\n");
1486 hr = SHGetDesktopFolder(&psfDesktop);
1487 if (FAILED(hr))
1489 WINE_ERR("Couldn't get desktop folder.\n");
1490 goto done;
1493 hr = SHGetSpecialFolderLocation(NULL, CSIDL_STARTUP, &pidlStartup);
1494 if (FAILED(hr))
1496 WINE_TRACE("Couldn't get StartUp folder location.\n");
1497 goto done;
1500 hr = IShellFolder_BindToObject(psfDesktop, pidlStartup, NULL, &IID_IShellFolder, (LPVOID*)&psfStartup);
1501 if (FAILED(hr))
1503 WINE_TRACE("Couldn't bind IShellFolder to StartUp folder.\n");
1504 goto done;
1507 hr = IShellFolder_EnumObjects(psfStartup, NULL, SHCONTF_NONFOLDERS | SHCONTF_INCLUDEHIDDEN, &iEnumList);
1508 if (FAILED(hr))
1510 WINE_TRACE("Unable to enumerate StartUp objects.\n");
1511 goto done;
1514 while (IEnumIDList_Next(iEnumList, 1, &pidlItem, &NumPIDLs) == S_OK &&
1515 (NumPIDLs) == 1)
1517 hr = IShellFolder_GetDisplayNameOf(psfStartup, pidlItem, SHGDN_FORPARSING, &strret);
1518 if (FAILED(hr))
1519 WINE_TRACE("Unable to get display name of enumeration item.\n");
1520 else
1522 hr = StrRetToBufW(&strret, pidlItem, wszCommand, MAX_PATH);
1523 if (FAILED(hr))
1524 WINE_TRACE("Unable to parse display name.\n");
1525 else
1527 HINSTANCE hinst;
1529 hinst = ShellExecuteW(NULL, NULL, wszCommand, NULL, NULL, SW_SHOWNORMAL);
1530 if (PtrToUlong(hinst) <= 32)
1531 WINE_WARN("Error %p executing command %s.\n", hinst, wine_dbgstr_w(wszCommand));
1535 ILFree(pidlItem);
1538 /* Return success */
1539 ret = TRUE;
1541 done:
1542 if (iEnumList) IEnumIDList_Release(iEnumList);
1543 if (psfStartup) IShellFolder_Release(psfStartup);
1544 if (pidlStartup) ILFree(pidlStartup);
1546 return ret;
1549 static void usage( int status )
1551 WINE_MESSAGE( "Usage: wineboot [options]\n" );
1552 WINE_MESSAGE( "Options;\n" );
1553 WINE_MESSAGE( " -h,--help Display this help message\n" );
1554 WINE_MESSAGE( " -e,--end-session End the current session cleanly\n" );
1555 WINE_MESSAGE( " -f,--force Force exit for processes that don't exit cleanly\n" );
1556 WINE_MESSAGE( " -i,--init Perform initialization for first Wine instance\n" );
1557 WINE_MESSAGE( " -k,--kill Kill running processes without any cleanup\n" );
1558 WINE_MESSAGE( " -r,--restart Restart only, don't do normal startup operations\n" );
1559 WINE_MESSAGE( " -s,--shutdown Shutdown only, don't reboot\n" );
1560 WINE_MESSAGE( " -u,--update Update the wineprefix directory\n" );
1561 exit( status );
1564 int __cdecl main( int argc, char *argv[] )
1566 static const WCHAR RunW[] = {'R','u','n',0};
1567 static const WCHAR RunOnceW[] = {'R','u','n','O','n','c','e',0};
1568 static const WCHAR RunServicesW[] = {'R','u','n','S','e','r','v','i','c','e','s',0};
1569 static const WCHAR RunServicesOnceW[] = {'R','u','n','S','e','r','v','i','c','e','s','O','n','c','e',0};
1570 static const WCHAR wineboot_eventW[] = {'\\','K','e','r','n','e','l','O','b','j','e','c','t','s',
1571 '\\','_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
1573 /* First, set the current directory to SystemRoot */
1574 int i, j;
1575 BOOL end_session, force, init, kill, restart, shutdown, update;
1576 HANDLE event;
1577 OBJECT_ATTRIBUTES attr;
1578 UNICODE_STRING nameW;
1579 BOOL is_wow64;
1581 end_session = force = init = kill = restart = shutdown = update = FALSE;
1582 GetWindowsDirectoryW( windowsdir, MAX_PATH );
1583 if( !SetCurrentDirectoryW( windowsdir ) )
1584 WINE_ERR("Cannot set the dir to %s (%d)\n", wine_dbgstr_w(windowsdir), GetLastError() );
1586 if (IsWow64Process( GetCurrentProcess(), &is_wow64 ) && is_wow64)
1588 STARTUPINFOW si;
1589 PROCESS_INFORMATION pi;
1590 WCHAR filename[MAX_PATH];
1591 void *redir;
1592 DWORD exit_code;
1594 memset( &si, 0, sizeof(si) );
1595 si.cb = sizeof(si);
1596 GetModuleFileNameW( 0, filename, MAX_PATH );
1598 Wow64DisableWow64FsRedirection( &redir );
1599 if (CreateProcessW( filename, GetCommandLineW(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ))
1601 WINE_TRACE( "restarting %s\n", wine_dbgstr_w(filename) );
1602 WaitForSingleObject( pi.hProcess, INFINITE );
1603 GetExitCodeProcess( pi.hProcess, &exit_code );
1604 ExitProcess( exit_code );
1606 else WINE_ERR( "failed to restart 64-bit %s, err %d\n", wine_dbgstr_w(filename), GetLastError() );
1607 Wow64RevertWow64FsRedirection( redir );
1610 for (i = 1; i < argc; i++)
1612 if (argv[i][0] != '-') continue;
1613 if (argv[i][1] == '-')
1615 if (!strcmp( argv[i], "--help" )) usage( 0 );
1616 else if (!strcmp( argv[i], "--end-session" )) end_session = TRUE;
1617 else if (!strcmp( argv[i], "--force" )) force = TRUE;
1618 else if (!strcmp( argv[i], "--init" )) init = TRUE;
1619 else if (!strcmp( argv[i], "--kill" )) kill = TRUE;
1620 else if (!strcmp( argv[i], "--restart" )) restart = TRUE;
1621 else if (!strcmp( argv[i], "--shutdown" )) shutdown = TRUE;
1622 else if (!strcmp( argv[i], "--update" )) update = TRUE;
1623 else usage( 1 );
1624 continue;
1626 for (j = 1; argv[i][j]; j++)
1628 switch (argv[i][j])
1630 case 'e': end_session = TRUE; break;
1631 case 'f': force = TRUE; break;
1632 case 'i': init = TRUE; break;
1633 case 'k': kill = TRUE; break;
1634 case 'r': restart = TRUE; break;
1635 case 's': shutdown = TRUE; break;
1636 case 'u': update = TRUE; break;
1637 case 'h': usage(0); break;
1638 default: usage(1); break;
1643 if (end_session)
1645 if (kill)
1647 if (!shutdown_all_desktops( force )) return 1;
1649 else if (!shutdown_close_windows( force )) return 1;
1652 if (kill) kill_processes( shutdown );
1654 if (shutdown) return 0;
1656 /* create event to be inherited by services.exe */
1657 InitializeObjectAttributes( &attr, &nameW, OBJ_OPENIF | OBJ_INHERIT, 0, NULL );
1658 RtlInitUnicodeString( &nameW, wineboot_eventW );
1659 NtCreateEvent( &event, EVENT_ALL_ACCESS, &attr, NotificationEvent, 0 );
1661 ResetEvent( event ); /* in case this is a restart */
1663 create_hardware_registry_keys();
1664 create_dynamic_registry_keys();
1665 create_environment_registry_keys();
1666 wininit();
1667 pendingRename();
1669 ProcessWindowsFileProtection();
1670 ProcessRunKeys( HKEY_LOCAL_MACHINE, RunServicesOnceW, TRUE, FALSE );
1672 if (init || (kill && !restart))
1674 ProcessRunKeys( HKEY_LOCAL_MACHINE, RunServicesW, FALSE, FALSE );
1675 start_services_process();
1677 if (init || update) update_wineprefix( update );
1679 create_volatile_environment_registry_key();
1681 ProcessRunKeys( HKEY_LOCAL_MACHINE, RunOnceW, TRUE, TRUE );
1683 if (!init && !restart)
1685 ProcessRunKeys( HKEY_LOCAL_MACHINE, RunW, FALSE, FALSE );
1686 ProcessRunKeys( HKEY_CURRENT_USER, RunW, FALSE, FALSE );
1687 ProcessStartupItems();
1690 WINE_TRACE("Operation done\n");
1692 SetEvent( event );
1693 return 0;