ntdll: Report newer vector processor features on x86 / x64.
[wine.git] / programs / wineboot / wineboot.c
blob902f6af042e9fcbe776ef9bc1979db89d4f38437
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>
64 #include <ntstatus.h>
65 #define WIN32_NO_STATUS
66 #include <windows.h>
67 #include <winternl.h>
68 #include <ddk/wdm.h>
69 #include <sddl.h>
70 #include <wine/svcctl.h>
71 #include <wine/asm.h>
72 #include <wine/debug.h>
74 #include <shlobj.h>
75 #include <shobjidl.h>
76 #include <shlwapi.h>
77 #include <shellapi.h>
78 #include <setupapi.h>
79 #include <newdev.h>
80 #include "resource.h"
82 WINE_DEFAULT_DEBUG_CHANNEL(wineboot);
84 extern BOOL shutdown_close_windows( BOOL force );
85 extern BOOL shutdown_all_desktops( BOOL force );
86 extern void kill_processes( BOOL kill_desktop );
88 static WCHAR windowsdir[MAX_PATH];
89 static const BOOL is_64bit = sizeof(void *) > sizeof(int);
91 /* retrieve the path to the wine.inf file */
92 static WCHAR *get_wine_inf_path(void)
94 WCHAR *dir, *name = NULL;
96 if ((dir = _wgetenv( L"WINEBUILDDIR" )))
98 if (!(name = HeapAlloc( GetProcessHeap(), 0,
99 sizeof(L"\\loader\\wine.inf") + lstrlenW(dir) * sizeof(WCHAR) )))
100 return NULL;
101 lstrcpyW( name, dir );
102 lstrcatW( name, L"\\loader" );
104 else if ((dir = _wgetenv( L"WINEDATADIR" )))
106 if (!(name = HeapAlloc( GetProcessHeap(), 0, sizeof(L"\\wine.inf") + lstrlenW(dir) * sizeof(WCHAR) )))
107 return NULL;
108 lstrcpyW( name, dir );
110 else return NULL;
112 lstrcatW( name, L"\\wine.inf" );
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 BOOL ret = FALSE;
121 int fd, count;
122 char buffer[100];
123 WCHAR *file = HeapAlloc( GetProcessHeap(), 0, lstrlenW(config_dir) * sizeof(WCHAR) + sizeof(L"\\.update-timestamp") );
125 if (!file) return FALSE;
126 lstrcpyW( file, config_dir );
127 lstrcatW( file, L"\\.update-timestamp" );
129 if ((fd = _wopen( file, O_RDWR )) != -1)
131 if ((count = read( fd, buffer, sizeof(buffer) - 1 )) >= 0)
133 buffer[count] = 0;
134 if (!strncmp( buffer, "disable", sizeof("disable")-1 )) goto done;
135 if (timestamp == strtoul( buffer, NULL, 10 )) goto done;
137 lseek( fd, 0, SEEK_SET );
138 chsize( fd, 0 );
140 else
142 if (errno != ENOENT) goto done;
143 if ((fd = _wopen( file, O_WRONLY | O_CREAT | O_TRUNC, 0666 )) == -1) goto done;
146 count = sprintf( buffer, "%lu\n", timestamp );
147 if (write( fd, buffer, count ) != count)
149 WINE_WARN( "failed to update timestamp in %s\n", debugstr_w(file) );
150 chsize( fd, 0 );
152 else ret = TRUE;
154 done:
155 if (fd != -1) close( fd );
156 HeapFree( GetProcessHeap(), 0, file );
157 return ret;
160 /* print the config directory in a more Unix-ish way */
161 static const WCHAR *prettyprint_configdir(void)
163 static WCHAR buffer[MAX_PATH];
164 WCHAR *p, *path = _wgetenv( L"WINECONFIGDIR" );
166 lstrcpynW( buffer, path, ARRAY_SIZE(buffer) );
167 if (lstrlenW( path ) >= ARRAY_SIZE(buffer) )
168 lstrcpyW( buffer + ARRAY_SIZE(buffer) - 4, L"..." );
170 if (!wcsncmp( buffer, L"\\??\\unix\\", 9 ))
172 for (p = buffer + 9; *p; p++) if (*p == '\\') *p = '/';
173 return buffer + 9;
175 else if (!wcsncmp( buffer, L"\\??\\Z:\\", 7 ))
177 for (p = buffer + 6; *p; p++) if (*p == '\\') *p = '/';
178 return buffer + 6;
180 else return buffer + 4;
183 /* wrapper for RegSetValueExW */
184 static DWORD set_reg_value( HKEY hkey, const WCHAR *name, const WCHAR *value )
186 return RegSetValueExW( hkey, name, 0, REG_SZ, (const BYTE *)value, (lstrlenW(value) + 1) * sizeof(WCHAR) );
189 static DWORD set_reg_value_dword( HKEY hkey, const WCHAR *name, DWORD value )
191 return RegSetValueExW( hkey, name, 0, REG_DWORD, (const BYTE *)&value, sizeof(value) );
194 static void create_user_shared_data(void)
196 struct _KUSER_SHARED_DATA *data;
197 RTL_OSVERSIONINFOEXW version;
198 SYSTEM_CPU_INFORMATION sci;
199 SYSTEM_BASIC_INFORMATION sbi;
200 BOOLEAN *features;
201 OBJECT_ATTRIBUTES attr = {sizeof(attr)};
202 UNICODE_STRING name;
203 NTSTATUS status;
204 HANDLE handle;
206 RtlInitUnicodeString( &name, L"\\KernelObjects\\__wine_user_shared_data" );
207 InitializeObjectAttributes( &attr, &name, OBJ_OPENIF, NULL, NULL );
208 if ((status = NtOpenSection( &handle, SECTION_ALL_ACCESS, &attr )))
210 ERR( "cannot open __wine_user_shared_data: %x\n", status );
211 return;
213 data = MapViewOfFile( handle, FILE_MAP_WRITE, 0, 0, sizeof(*data) );
214 CloseHandle( handle );
215 if (!data)
217 ERR( "cannot map __wine_user_shared_data\n" );
218 return;
221 version.dwOSVersionInfoSize = sizeof(version);
222 RtlGetVersion( &version );
223 NtQuerySystemInformation( SystemBasicInformation, &sbi, sizeof(sbi), NULL );
224 NtQuerySystemInformation( SystemCpuInformation, &sci, sizeof(sci), NULL );
226 data->TickCountMultiplier = 1 << 24;
227 data->LargePageMinimum = 2 * 1024 * 1024;
228 data->NtBuildNumber = version.dwBuildNumber;
229 data->NtProductType = version.wProductType;
230 data->ProductTypeIsValid = TRUE;
231 data->NativeProcessorArchitecture = sci.Architecture;
232 data->NtMajorVersion = version.dwMajorVersion;
233 data->NtMinorVersion = version.dwMinorVersion;
234 data->SuiteMask = version.wSuiteMask;
235 data->NumberOfPhysicalPages = sbi.MmNumberOfPhysicalPages;
236 wcscpy( data->NtSystemRoot, L"C:\\windows" );
238 features = data->ProcessorFeatures;
239 switch (sci.Architecture)
241 case PROCESSOR_ARCHITECTURE_INTEL:
242 case PROCESSOR_ARCHITECTURE_AMD64:
243 features[PF_COMPARE_EXCHANGE_DOUBLE] = !!(sci.FeatureSet & CPU_FEATURE_CX8);
244 features[PF_MMX_INSTRUCTIONS_AVAILABLE] = !!(sci.FeatureSet & CPU_FEATURE_MMX);
245 features[PF_XMMI_INSTRUCTIONS_AVAILABLE] = !!(sci.FeatureSet & CPU_FEATURE_SSE);
246 features[PF_3DNOW_INSTRUCTIONS_AVAILABLE] = !!(sci.FeatureSet & CPU_FEATURE_3DNOW);
247 features[PF_RDTSC_INSTRUCTION_AVAILABLE] = !!(sci.FeatureSet & CPU_FEATURE_TSC);
248 features[PF_PAE_ENABLED] = !!(sci.FeatureSet & CPU_FEATURE_PAE);
249 features[PF_XMMI64_INSTRUCTIONS_AVAILABLE] = !!(sci.FeatureSet & CPU_FEATURE_SSE2);
250 features[PF_SSE3_INSTRUCTIONS_AVAILABLE] = !!(sci.FeatureSet & CPU_FEATURE_SSE3);
251 features[PF_SSSE3_INSTRUCTIONS_AVAILABLE] = !!(sci.FeatureSet & CPU_FEATURE_SSSE3);
252 features[PF_XSAVE_ENABLED] = !!(sci.FeatureSet & CPU_FEATURE_XSAVE);
253 features[PF_COMPARE_EXCHANGE128] = !!(sci.FeatureSet & CPU_FEATURE_CX128);
254 features[PF_SSE_DAZ_MODE_AVAILABLE] = !!(sci.FeatureSet & CPU_FEATURE_DAZ);
255 features[PF_NX_ENABLED] = !!(sci.FeatureSet & CPU_FEATURE_NX);
256 features[PF_SECOND_LEVEL_ADDRESS_TRANSLATION] = !!(sci.FeatureSet & CPU_FEATURE_2NDLEV);
257 features[PF_VIRT_FIRMWARE_ENABLED] = !!(sci.FeatureSet & CPU_FEATURE_VIRT);
258 features[PF_RDWRFSGSBASE_AVAILABLE] = !!(sci.FeatureSet & CPU_FEATURE_RDFS);
259 features[PF_FASTFAIL_AVAILABLE] = TRUE;
260 features[PF_SSE4_1_INSTRUCTIONS_AVAILABLE] = !!(sci.FeatureSet & CPU_FEATURE_SSE41);
261 features[PF_SSE4_2_INSTRUCTIONS_AVAILABLE] = !!(sci.FeatureSet & CPU_FEATURE_SSE42);
262 features[PF_AVX_INSTRUCTIONS_AVAILABLE] = !!(sci.FeatureSet & CPU_FEATURE_AVX);
263 features[PF_AVX2_INSTRUCTIONS_AVAILABLE] = !!(sci.FeatureSet & CPU_FEATURE_AVX2);
264 break;
265 case PROCESSOR_ARCHITECTURE_ARM:
266 features[PF_ARM_VFP_32_REGISTERS_AVAILABLE] = !!(sci.FeatureSet & CPU_FEATURE_ARM_VFP_32);
267 features[PF_ARM_NEON_INSTRUCTIONS_AVAILABLE] = !!(sci.FeatureSet & CPU_FEATURE_ARM_NEON);
268 features[PF_ARM_V8_INSTRUCTIONS_AVAILABLE] = (sci.Level >= 8);
269 break;
270 case PROCESSOR_ARCHITECTURE_ARM64:
271 features[PF_ARM_V8_INSTRUCTIONS_AVAILABLE] = TRUE;
272 features[PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE] = !!(sci.FeatureSet & CPU_FEATURE_ARM_V8_CRC32);
273 features[PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE] = !!(sci.FeatureSet & CPU_FEATURE_ARM_V8_CRYPTO);
274 break;
276 data->ActiveProcessorCount = NtCurrentTeb()->Peb->NumberOfProcessors;
277 data->ActiveGroupCount = 1;
279 UnmapViewOfFile( data );
282 #if defined(__i386__) || defined(__x86_64__)
284 static void regs_to_str( int *regs, unsigned int len, WCHAR *buffer )
286 unsigned int i;
287 unsigned char *p = (unsigned char *)regs;
289 for (i = 0; i < len; i++) { buffer[i] = *p++; }
290 buffer[i] = 0;
293 static unsigned int get_model( unsigned int reg0, unsigned int *stepping, unsigned int *family )
295 unsigned int model, family_id = (reg0 & (0x0f << 8)) >> 8;
297 model = (reg0 & (0x0f << 4)) >> 4;
298 if (family_id == 6 || family_id == 15) model |= (reg0 & (0x0f << 16)) >> 12;
300 *family = family_id;
301 if (family_id == 15) *family += (reg0 & (0xff << 20)) >> 20;
303 *stepping = reg0 & 0x0f;
304 return model;
307 static void get_identifier( WCHAR *buf, size_t size, const WCHAR *arch )
309 unsigned int family, model, stepping;
310 int regs[4] = {0, 0, 0, 0};
312 __cpuid( regs, 1 );
313 model = get_model( regs[0], &stepping, &family );
314 swprintf( buf, size, L"%s Family %u Model %u Stepping %u", arch, family, model, stepping );
317 static void get_vendorid( WCHAR *buf )
319 int tmp, regs[4] = {0, 0, 0, 0};
321 __cpuid( regs, 0 );
322 tmp = regs[2]; /* swap edx and ecx */
323 regs[2] = regs[3];
324 regs[3] = tmp;
326 regs_to_str( regs + 1, 12, buf );
329 static void get_namestring( WCHAR *buf )
331 int regs[4] = {0, 0, 0, 0};
332 int i;
334 __cpuid( regs, 0x80000000 );
335 if (regs[0] >= 0x80000004)
337 __cpuid( regs, 0x80000002 );
338 regs_to_str( regs, 16, buf );
339 __cpuid( regs, 0x80000003 );
340 regs_to_str( regs, 16, buf + 16 );
341 __cpuid( regs, 0x80000004 );
342 regs_to_str( regs, 16, buf + 32 );
344 for (i = lstrlenW(buf) - 1; i >= 0 && buf[i] == ' '; i--) buf[i] = 0;
347 #else /* __i386__ || __x86_64__ */
349 static void get_identifier( WCHAR *buf, size_t size, const WCHAR *arch ) { }
350 static void get_vendorid( WCHAR *buf ) { }
351 static void get_namestring( WCHAR *buf ) { }
353 #endif /* __i386__ || __x86_64__ */
355 #include "pshpack1.h"
356 struct smbios_prologue
358 BYTE calling_method;
359 BYTE major_version;
360 BYTE minor_version;
361 BYTE revision;
362 DWORD length;
365 enum smbios_type
367 SMBIOS_TYPE_BIOS,
368 SMBIOS_TYPE_SYSTEM,
369 SMBIOS_TYPE_BASEBOARD,
372 struct smbios_header
374 BYTE type;
375 BYTE length;
376 WORD handle;
379 struct smbios_baseboard
381 struct smbios_header hdr;
382 BYTE vendor;
383 BYTE product;
384 BYTE version;
385 BYTE serial;
388 struct smbios_bios
390 struct smbios_header hdr;
391 BYTE vendor;
392 BYTE version;
393 WORD start;
394 BYTE date;
395 BYTE size;
396 UINT64 characteristics;
397 BYTE characteristics_ext[2];
398 BYTE system_bios_major_release;
399 BYTE system_bios_minor_release;
400 BYTE ec_firmware_major_release;
401 BYTE ec_firmware_minor_release;
404 struct smbios_system
406 struct smbios_header hdr;
407 BYTE vendor;
408 BYTE product;
409 BYTE version;
410 BYTE serial;
411 BYTE uuid[16];
412 BYTE wake_up_type;
413 BYTE sku;
414 BYTE family;
416 #include "poppack.h"
418 #define RSMB (('R' << 24) | ('S' << 16) | ('M' << 8) | 'B')
420 static const struct smbios_header *find_smbios_entry( enum smbios_type type, const char *buf, UINT len )
422 const char *ptr, *start;
423 const struct smbios_prologue *prologue;
424 const struct smbios_header *hdr;
426 if (len < sizeof(struct smbios_prologue)) return NULL;
427 prologue = (const struct smbios_prologue *)buf;
428 if (prologue->length > len - sizeof(*prologue) || prologue->length < sizeof(*hdr)) return NULL;
430 start = (const char *)(prologue + 1);
431 hdr = (const struct smbios_header *)start;
433 for (;;)
435 if ((const char *)hdr - start >= prologue->length - sizeof(*hdr)) return NULL;
437 if (!hdr->length)
439 WARN( "invalid entry\n" );
440 return NULL;
443 if (hdr->type == type)
445 if ((const char *)hdr - start + hdr->length > prologue->length) return NULL;
446 break;
448 else /* skip other entries and their strings */
450 for (ptr = (const char *)hdr + hdr->length; ptr - buf < len && *ptr; ptr++)
452 for (; ptr - buf < len; ptr++) if (!*ptr) break;
454 if (ptr == (const char *)hdr + hdr->length) ptr++;
455 hdr = (const struct smbios_header *)(ptr + 1);
459 return hdr;
462 static inline WCHAR *heap_strdupAW( const char *src )
464 int len;
465 WCHAR *dst;
466 if (!src) return NULL;
467 len = MultiByteToWideChar( CP_ACP, 0, src, -1, NULL, 0 );
468 if ((dst = HeapAlloc( GetProcessHeap(), 0, len * sizeof(*dst) ))) MultiByteToWideChar( CP_ACP, 0, src, -1, dst, len );
469 return dst;
472 static WCHAR *get_smbios_string( BYTE id, const char *buf, UINT offset, UINT buflen )
474 const char *ptr = buf + offset;
475 UINT i = 0;
477 if (!id || offset >= buflen) return NULL;
478 for (ptr = buf + offset; ptr - buf < buflen && *ptr; ptr++)
480 if (++i == id) return heap_strdupAW( ptr );
481 for (; ptr - buf < buflen; ptr++) if (!*ptr) break;
483 return NULL;
486 static void set_value_from_smbios_string( HKEY key, const WCHAR *value, BYTE id, const char *buf, UINT offset, UINT buflen )
488 WCHAR *str;
489 str = get_smbios_string( id, buf, offset, buflen );
490 set_reg_value( key, value, str ? str : L"" );
491 HeapFree( GetProcessHeap(), 0, str );
494 static void create_bios_baseboard_values( HKEY bios_key, const char *buf, UINT len )
496 const struct smbios_header *hdr;
497 const struct smbios_baseboard *baseboard;
498 UINT offset;
500 if (!(hdr = find_smbios_entry( SMBIOS_TYPE_BASEBOARD, buf, len ))) return;
501 baseboard = (const struct smbios_baseboard *)hdr;
502 offset = (const char *)baseboard - buf + baseboard->hdr.length;
504 set_value_from_smbios_string( bios_key, L"BaseBoardManufacturer", baseboard->vendor, buf, offset, len );
505 set_value_from_smbios_string( bios_key, L"BaseBoardProduct", baseboard->product, buf, offset, len );
506 set_value_from_smbios_string( bios_key, L"BaseBoardVersion", baseboard->version, buf, offset, len );
509 static void create_bios_bios_values( HKEY bios_key, const char *buf, UINT len )
511 const struct smbios_header *hdr;
512 const struct smbios_bios *bios;
513 UINT offset;
515 if (!(hdr = find_smbios_entry( SMBIOS_TYPE_BIOS, buf, len ))) return;
516 bios = (const struct smbios_bios *)hdr;
517 offset = (const char *)bios - buf + bios->hdr.length;
519 set_value_from_smbios_string( bios_key, L"BIOSVendor", bios->vendor, buf, offset, len );
520 set_value_from_smbios_string( bios_key, L"BIOSVersion", bios->version, buf, offset, len );
521 set_value_from_smbios_string( bios_key, L"BIOSReleaseDate", bios->date, buf, offset, len );
523 if (bios->hdr.length >= 0x18)
525 set_reg_value_dword( bios_key, L"BiosMajorRelease", bios->system_bios_major_release );
526 set_reg_value_dword( bios_key, L"BiosMinorRelease", bios->system_bios_minor_release );
527 set_reg_value_dword( bios_key, L"ECFirmwareMajorVersion", bios->ec_firmware_major_release );
528 set_reg_value_dword( bios_key, L"ECFirmwareMinorVersion", bios->ec_firmware_minor_release );
530 else
532 set_reg_value_dword( bios_key, L"BiosMajorRelease", 0xFF );
533 set_reg_value_dword( bios_key, L"BiosMinorRelease", 0xFF );
534 set_reg_value_dword( bios_key, L"ECFirmwareMajorVersion", 0xFF );
535 set_reg_value_dword( bios_key, L"ECFirmwareMinorVersion", 0xFF );
539 static void create_bios_system_values( HKEY bios_key, const char *buf, UINT len )
541 const struct smbios_header *hdr;
542 const struct smbios_system *system;
543 UINT offset;
545 if (!(hdr = find_smbios_entry( SMBIOS_TYPE_SYSTEM, buf, len ))) return;
546 system = (const struct smbios_system *)hdr;
547 offset = (const char *)system - buf + system->hdr.length;
549 set_value_from_smbios_string( bios_key, L"SystemManufacturer", system->vendor, buf, offset, len );
550 set_value_from_smbios_string( bios_key, L"SystemProductName", system->product, buf, offset, len );
551 set_value_from_smbios_string( bios_key, L"SystemVersion", system->version, buf, offset, len );
553 if (system->hdr.length >= 0x1B)
555 set_value_from_smbios_string( bios_key, L"SystemSKU", system->sku, buf, offset, len );
556 set_value_from_smbios_string( bios_key, L"SystemFamily", system->family, buf, offset, len );
558 else
560 set_value_from_smbios_string( bios_key, L"SystemSKU", 0, buf, offset, len );
561 set_value_from_smbios_string( bios_key, L"SystemFamily", 0, buf, offset, len );
565 static void create_bios_key( HKEY system_key )
567 HKEY bios_key;
568 UINT len;
569 char *buf;
571 if (RegCreateKeyExW( system_key, L"BIOS", 0, NULL, REG_OPTION_VOLATILE,
572 KEY_ALL_ACCESS, NULL, &bios_key, NULL ))
573 return;
575 len = GetSystemFirmwareTable( RSMB, 0, NULL, 0 );
576 if (!(buf = HeapAlloc( GetProcessHeap(), 0, len ))) goto done;
577 len = GetSystemFirmwareTable( RSMB, 0, buf, len );
579 create_bios_baseboard_values( bios_key, buf, len );
580 create_bios_bios_values( bios_key, buf, len );
581 create_bios_system_values( bios_key, buf, len );
583 done:
584 HeapFree( GetProcessHeap(), 0, buf );
585 RegCloseKey( bios_key );
588 /* create the volatile hardware registry keys */
589 static void create_hardware_registry_keys(void)
591 unsigned int i;
592 HKEY hkey, system_key, cpu_key, fpu_key;
593 SYSTEM_CPU_INFORMATION sci;
594 PROCESSOR_POWER_INFORMATION* power_info;
595 ULONG sizeof_power_info = sizeof(PROCESSOR_POWER_INFORMATION) * NtCurrentTeb()->Peb->NumberOfProcessors;
596 WCHAR id[60], namestr[49], vendorid[13];
598 get_namestring( namestr );
599 get_vendorid( vendorid );
600 NtQuerySystemInformation( SystemCpuInformation, &sci, sizeof(sci), NULL );
602 power_info = HeapAlloc( GetProcessHeap(), 0, sizeof_power_info );
603 if (power_info == NULL)
604 return;
605 if (NtPowerInformation( ProcessorInformation, NULL, 0, power_info, sizeof_power_info ))
606 memset( power_info, 0, sizeof_power_info );
608 switch (sci.Architecture)
610 case PROCESSOR_ARCHITECTURE_ARM:
611 case PROCESSOR_ARCHITECTURE_ARM64:
612 swprintf( id, ARRAY_SIZE(id), L"ARM Family %u Model %u Revision %u",
613 sci.Level, HIBYTE(sci.Revision), LOBYTE(sci.Revision) );
614 break;
616 case PROCESSOR_ARCHITECTURE_AMD64:
617 get_identifier( id, ARRAY_SIZE(id), !wcscmp(vendorid, L"AuthenticAMD") ? L"AMD64" : L"Intel64" );
618 break;
620 case PROCESSOR_ARCHITECTURE_INTEL:
621 default:
622 get_identifier( id, ARRAY_SIZE(id), L"x86" );
623 break;
626 if (RegCreateKeyExW( HKEY_LOCAL_MACHINE, L"Hardware\\Description\\System", 0, NULL,
627 REG_OPTION_VOLATILE, KEY_ALL_ACCESS, NULL, &system_key, NULL ))
629 HeapFree( GetProcessHeap(), 0, power_info );
630 return;
633 switch (sci.Architecture)
635 case PROCESSOR_ARCHITECTURE_ARM:
636 case PROCESSOR_ARCHITECTURE_ARM64:
637 set_reg_value( system_key, L"Identifier", L"ARM processor family" );
638 break;
640 case PROCESSOR_ARCHITECTURE_INTEL:
641 case PROCESSOR_ARCHITECTURE_AMD64:
642 default:
643 set_reg_value( system_key, L"Identifier", L"AT compatible" );
644 break;
647 if (sci.Architecture == PROCESSOR_ARCHITECTURE_ARM ||
648 sci.Architecture == PROCESSOR_ARCHITECTURE_ARM64 ||
649 RegCreateKeyExW( system_key, L"FloatingPointProcessor", 0, NULL, REG_OPTION_VOLATILE,
650 KEY_ALL_ACCESS, NULL, &fpu_key, NULL ))
651 fpu_key = 0;
652 if (RegCreateKeyExW( system_key, L"CentralProcessor", 0, NULL, REG_OPTION_VOLATILE,
653 KEY_ALL_ACCESS, NULL, &cpu_key, NULL ))
654 cpu_key = 0;
656 for (i = 0; i < NtCurrentTeb()->Peb->NumberOfProcessors; i++)
658 WCHAR numW[10];
660 swprintf( numW, ARRAY_SIZE(numW), L"%u", i );
661 if (!RegCreateKeyExW( cpu_key, numW, 0, NULL, REG_OPTION_VOLATILE,
662 KEY_ALL_ACCESS, NULL, &hkey, NULL ))
664 RegSetValueExW( hkey, L"FeatureSet", 0, REG_DWORD, (BYTE *)&sci.FeatureSet, sizeof(DWORD) );
665 set_reg_value( hkey, L"Identifier", id );
666 /* TODO: report ARM properly */
667 set_reg_value( hkey, L"ProcessorNameString", namestr );
668 set_reg_value( hkey, L"VendorIdentifier", vendorid );
669 RegSetValueExW( hkey, L"~MHz", 0, REG_DWORD, (BYTE *)&power_info[i].MaxMhz, sizeof(DWORD) );
670 RegCloseKey( hkey );
672 if (sci.Architecture != PROCESSOR_ARCHITECTURE_ARM &&
673 sci.Architecture != PROCESSOR_ARCHITECTURE_ARM64 &&
674 !RegCreateKeyExW( fpu_key, numW, 0, NULL, REG_OPTION_VOLATILE,
675 KEY_ALL_ACCESS, NULL, &hkey, NULL ))
677 set_reg_value( hkey, L"Identifier", id );
678 RegCloseKey( hkey );
682 create_bios_key( system_key );
684 RegCloseKey( fpu_key );
685 RegCloseKey( cpu_key );
686 RegCloseKey( system_key );
687 HeapFree( GetProcessHeap(), 0, power_info );
691 /* create the DynData registry keys */
692 static void create_dynamic_registry_keys(void)
694 HKEY key;
696 if (!RegCreateKeyExW( HKEY_DYN_DATA, L"PerfStats\\StatData", 0, NULL, 0, KEY_WRITE, NULL, &key, NULL ))
697 RegCloseKey( key );
698 if (!RegCreateKeyExW( HKEY_DYN_DATA, L"Config Manager\\Enum", 0, NULL, 0, KEY_WRITE, NULL, &key, NULL ))
699 RegCloseKey( key );
702 /* create the platform-specific environment registry keys */
703 static void create_environment_registry_keys( void )
705 HKEY env_key;
706 SYSTEM_CPU_INFORMATION sci;
707 WCHAR buffer[60], vendorid[13];
708 const WCHAR *arch, *parch;
710 if (RegCreateKeyW( HKEY_LOCAL_MACHINE, L"System\\CurrentControlSet\\Control\\Session Manager\\Environment", &env_key )) return;
712 get_vendorid( vendorid );
713 NtQuerySystemInformation( SystemCpuInformation, &sci, sizeof(sci), NULL );
715 swprintf( buffer, ARRAY_SIZE(buffer), L"%u", NtCurrentTeb()->Peb->NumberOfProcessors );
716 set_reg_value( env_key, L"NUMBER_OF_PROCESSORS", buffer );
718 switch (sci.Architecture)
720 case PROCESSOR_ARCHITECTURE_AMD64:
721 arch = L"AMD64";
722 parch = !wcscmp(vendorid, L"AuthenticAMD") ? L"AMD64" : L"Intel64";
723 break;
725 case PROCESSOR_ARCHITECTURE_INTEL:
726 default:
727 arch = parch = L"x86";
728 break;
730 set_reg_value( env_key, L"PROCESSOR_ARCHITECTURE", arch );
732 switch (sci.Architecture)
734 case PROCESSOR_ARCHITECTURE_ARM:
735 case PROCESSOR_ARCHITECTURE_ARM64:
736 swprintf( buffer, ARRAY_SIZE(buffer), L"ARM Family %u Model %u Revision %u",
737 sci.Level, HIBYTE(sci.Revision), LOBYTE(sci.Revision) );
738 break;
740 case PROCESSOR_ARCHITECTURE_AMD64:
741 case PROCESSOR_ARCHITECTURE_INTEL:
742 default:
743 get_identifier( buffer, ARRAY_SIZE(buffer), parch );
744 lstrcatW( buffer, L", " );
745 lstrcatW( buffer, vendorid );
746 break;
748 set_reg_value( env_key, L"PROCESSOR_IDENTIFIER", buffer );
750 swprintf( buffer, ARRAY_SIZE(buffer), L"%u", sci.Level );
751 set_reg_value( env_key, L"PROCESSOR_LEVEL", buffer );
753 swprintf( buffer, ARRAY_SIZE(buffer), L"%04x", sci.Revision );
754 set_reg_value( env_key, L"PROCESSOR_REVISION", buffer );
756 RegCloseKey( env_key );
759 static void create_volatile_environment_registry_key(void)
761 WCHAR path[MAX_PATH];
762 WCHAR computername[MAX_COMPUTERNAME_LENGTH + 1 + 2];
763 DWORD size;
764 HKEY hkey;
765 HRESULT hr;
767 if (RegCreateKeyExW( HKEY_CURRENT_USER, L"Volatile Environment", 0, NULL, REG_OPTION_VOLATILE,
768 KEY_ALL_ACCESS, NULL, &hkey, NULL ))
769 return;
771 hr = SHGetFolderPathW( NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, path );
772 if (SUCCEEDED(hr)) set_reg_value( hkey, L"APPDATA", path );
774 set_reg_value( hkey, L"CLIENTNAME", L"Console" );
776 /* Write the profile path's drive letter and directory components into
777 * HOMEDRIVE and HOMEPATH respectively. */
778 hr = SHGetFolderPathW( NULL, CSIDL_PROFILE | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, path );
779 if (SUCCEEDED(hr))
781 set_reg_value( hkey, L"USERPROFILE", path );
782 set_reg_value( hkey, L"HOMEPATH", path + 2 );
783 path[2] = '\0';
784 set_reg_value( hkey, L"HOMEDRIVE", path );
787 size = ARRAY_SIZE(path);
788 if (GetUserNameW( path, &size )) set_reg_value( hkey, L"USERNAME", path );
790 set_reg_value( hkey, L"HOMESHARE", L"" );
792 hr = SHGetFolderPathW( NULL, CSIDL_LOCAL_APPDATA | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, path );
793 if (SUCCEEDED(hr))
794 set_reg_value( hkey, L"LOCALAPPDATA", path );
796 size = ARRAY_SIZE(computername) - 2;
797 if (GetComputerNameW(&computername[2], &size))
799 set_reg_value( hkey, L"USERDOMAIN", &computername[2] );
800 computername[0] = computername[1] = '\\';
801 set_reg_value( hkey, L"LOGONSERVER", computername );
804 set_reg_value( hkey, L"SESSIONNAME", L"Console" );
805 RegCloseKey( hkey );
808 /* Performs the rename operations dictated in %SystemRoot%\Wininit.ini.
809 * Returns FALSE if there was an error, or otherwise if all is ok.
811 static BOOL wininit(void)
813 WCHAR initial_buffer[1024];
814 WCHAR *str, *buffer = initial_buffer;
815 DWORD size = ARRAY_SIZE(initial_buffer);
816 DWORD res;
818 for (;;)
820 if (!(res = GetPrivateProfileSectionW( L"rename", buffer, size, L"wininit.ini" ))) return TRUE;
821 if (res < size - 2) break;
822 if (buffer != initial_buffer) HeapFree( GetProcessHeap(), 0, buffer );
823 size *= 2;
824 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return FALSE;
827 for (str = buffer; *str; str += lstrlenW(str) + 1)
829 WCHAR *value;
831 if (*str == ';') continue; /* comment */
832 if (!(value = wcschr( str, '=' ))) continue;
834 /* split the line into key and value */
835 *value++ = 0;
837 if (!lstrcmpiW( L"NUL", str ))
839 WINE_TRACE("Deleting file %s\n", wine_dbgstr_w(value) );
840 if( !DeleteFileW( value ) )
841 WINE_WARN("Error deleting file %s\n", wine_dbgstr_w(value) );
843 else
845 WINE_TRACE("Renaming file %s to %s\n", wine_dbgstr_w(value), wine_dbgstr_w(str) );
847 if( !MoveFileExW(value, str, MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) )
848 WINE_WARN("Error renaming %s to %s\n", wine_dbgstr_w(value), wine_dbgstr_w(str) );
850 str = value;
853 if (buffer != initial_buffer) HeapFree( GetProcessHeap(), 0, buffer );
855 if( !MoveFileExW( L"wininit.ini", L"wininit.bak", MOVEFILE_REPLACE_EXISTING) )
857 WINE_ERR("Couldn't rename wininit.ini, error %d\n", GetLastError() );
859 return FALSE;
862 return TRUE;
865 static void pendingRename(void)
867 WCHAR *buffer=NULL;
868 const WCHAR *src=NULL, *dst=NULL;
869 DWORD dataLength=0;
870 HKEY hSession;
872 if (RegOpenKeyExW( HKEY_LOCAL_MACHINE, L"System\\CurrentControlSet\\Control\\Session Manager",
873 0, KEY_ALL_ACCESS, &hSession ))
874 return;
876 if (RegQueryValueExW( hSession, L"PendingFileRenameOperations", NULL, NULL, NULL, &dataLength ))
877 goto end;
878 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, dataLength ))) goto end;
880 if (RegQueryValueExW( hSession, L"PendingFileRenameOperations", NULL, NULL,
881 (LPBYTE)buffer, &dataLength ))
882 goto end;
884 /* Make sure that the data is long enough and ends with two NULLs. This
885 * simplifies the code later on.
887 if( dataLength<2*sizeof(buffer[0]) ||
888 buffer[dataLength/sizeof(buffer[0])-1]!='\0' ||
889 buffer[dataLength/sizeof(buffer[0])-2]!='\0' )
890 goto end;
892 for( src=buffer; (src-buffer)*sizeof(src[0])<dataLength && *src!='\0';
893 src=dst+lstrlenW(dst)+1 )
895 DWORD dwFlags=0;
897 dst=src+lstrlenW(src)+1;
899 /* We need to skip the \??\ header */
900 if( src[0]=='\\' && src[1]=='?' && src[2]=='?' && src[3]=='\\' )
901 src+=4;
903 if( dst[0]=='!' )
905 dwFlags|=MOVEFILE_REPLACE_EXISTING;
906 dst++;
909 if( dst[0]=='\\' && dst[1]=='?' && dst[2]=='?' && dst[3]=='\\' )
910 dst+=4;
912 if( *dst!='\0' )
914 /* Rename the file */
915 MoveFileExW( src, dst, dwFlags );
916 } else
918 /* Delete the file or directory */
919 if (!RemoveDirectoryW( src ) && GetLastError() == ERROR_DIRECTORY) DeleteFileW( src );
923 RegDeleteValueW(hSession, L"PendingFileRenameOperations");
925 end:
926 HeapFree(GetProcessHeap(), 0, buffer);
927 RegCloseKey( hSession );
930 #define INVALID_RUNCMD_RETURN -1
932 * This function runs the specified command in the specified dir.
933 * [in,out] cmdline - the command line to run. The function may change the passed buffer.
934 * [in] dir - the dir to run the command in. If it is NULL, then the current dir is used.
935 * [in] wait - whether to wait for the run program to finish before returning.
936 * [in] minimized - Whether to ask the program to run minimized.
938 * Returns:
939 * If running the process failed, returns INVALID_RUNCMD_RETURN. Use GetLastError to get the error code.
940 * If wait is FALSE - returns 0 if successful.
941 * If wait is TRUE - returns the program's return value.
943 static DWORD runCmd(LPWSTR cmdline, LPCWSTR dir, BOOL wait, BOOL minimized)
945 STARTUPINFOW si;
946 PROCESS_INFORMATION info;
947 DWORD exit_code=0;
949 memset(&si, 0, sizeof(si));
950 si.cb=sizeof(si);
951 if( minimized )
953 si.dwFlags=STARTF_USESHOWWINDOW;
954 si.wShowWindow=SW_MINIMIZE;
956 memset(&info, 0, sizeof(info));
958 if( !CreateProcessW(NULL, cmdline, NULL, NULL, FALSE, 0, NULL, dir, &si, &info) )
960 WINE_WARN("Failed to run command %s (%d)\n", wine_dbgstr_w(cmdline), GetLastError() );
961 return INVALID_RUNCMD_RETURN;
964 WINE_TRACE("Successfully ran command %s - Created process handle %p\n",
965 wine_dbgstr_w(cmdline), info.hProcess );
967 if(wait)
968 { /* wait for the process to exit */
969 WaitForSingleObject(info.hProcess, INFINITE);
970 GetExitCodeProcess(info.hProcess, &exit_code);
973 CloseHandle( info.hThread );
974 CloseHandle( info.hProcess );
976 return exit_code;
979 static void process_run_key( HKEY key, const WCHAR *keyname, BOOL delete, BOOL synchronous )
981 HKEY runkey;
982 LONG res;
983 DWORD disp, i, max_cmdline = 0, max_value = 0;
984 WCHAR *cmdline = NULL, *value = NULL;
986 if (RegCreateKeyExW( key, keyname, 0, NULL, 0, delete ? KEY_ALL_ACCESS : KEY_READ, NULL, &runkey, &disp ))
987 return;
989 if (disp == REG_CREATED_NEW_KEY)
990 goto end;
992 if (RegQueryInfoKeyW( runkey, NULL, NULL, NULL, NULL, NULL, NULL, &i, &max_value, &max_cmdline, NULL, NULL ))
993 goto end;
995 if (!i)
997 WINE_TRACE( "No commands to execute.\n" );
998 goto end;
1000 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, max_cmdline )))
1002 WINE_ERR( "Couldn't allocate memory for the commands to be executed.\n" );
1003 goto end;
1005 if (!(value = HeapAlloc( GetProcessHeap(), 0, ++max_value * sizeof(*value) )))
1007 WINE_ERR( "Couldn't allocate memory for the value names.\n" );
1008 goto end;
1011 while (i)
1013 DWORD len = max_value, len_data = max_cmdline, type;
1015 if ((res = RegEnumValueW( runkey, --i, value, &len, 0, &type, (BYTE *)cmdline, &len_data )))
1017 WINE_ERR( "Couldn't read value %u (%d).\n", i, res );
1018 continue;
1020 if (delete && (res = RegDeleteValueW( runkey, value )))
1022 WINE_ERR( "Couldn't delete value %u (%d). Running command anyways.\n", i, res );
1024 if (type != REG_SZ)
1026 WINE_ERR( "Incorrect type of value %u (%u).\n", i, type );
1027 continue;
1029 if (runCmd( cmdline, NULL, synchronous, FALSE ) == INVALID_RUNCMD_RETURN)
1031 WINE_ERR( "Error running cmd %s (%u).\n", wine_dbgstr_w(cmdline), GetLastError() );
1033 WINE_TRACE( "Done processing cmd %u.\n", i );
1036 end:
1037 HeapFree( GetProcessHeap(), 0, value );
1038 HeapFree( GetProcessHeap(), 0, cmdline );
1039 RegCloseKey( runkey );
1040 WINE_TRACE( "Done.\n" );
1044 * Process a "Run" type registry key.
1045 * hkRoot is the HKEY from which "Software\Microsoft\Windows\CurrentVersion" is
1046 * opened.
1047 * szKeyName is the key holding the actual entries.
1048 * bDelete tells whether we should delete each value right before executing it.
1049 * bSynchronous tells whether we should wait for the prog to complete before
1050 * going on to the next prog.
1052 static void ProcessRunKeys( HKEY root, const WCHAR *keyname, BOOL delete, BOOL synchronous )
1054 HKEY key;
1056 if (root == HKEY_LOCAL_MACHINE)
1058 WINE_TRACE( "Processing %s entries under HKLM.\n", wine_dbgstr_w(keyname) );
1059 if (!RegCreateKeyExW( root, L"Software\\Microsoft\\Windows\\CurrentVersion",
1060 0, NULL, 0, KEY_READ, NULL, &key, NULL ))
1062 process_run_key( key, keyname, delete, synchronous );
1063 RegCloseKey( key );
1065 if (is_64bit && !RegCreateKeyExW( root, L"Software\\Microsoft\\Windows\\CurrentVersion",
1066 0, NULL, 0, KEY_READ|KEY_WOW64_32KEY, NULL, &key, NULL ))
1068 process_run_key( key, keyname, delete, synchronous );
1069 RegCloseKey( key );
1072 else
1074 WINE_TRACE( "Processing %s entries under HKCU.\n", wine_dbgstr_w(keyname) );
1075 if (!RegCreateKeyExW( root, L"Software\\Microsoft\\Windows\\CurrentVersion",
1076 0, NULL, 0, KEY_READ, NULL, &key, NULL ))
1078 process_run_key( key, keyname, delete, synchronous );
1079 RegCloseKey( key );
1085 * WFP is Windows File Protection, in NT5 and Windows 2000 it maintains a cache
1086 * of known good dlls and scans through and replaces corrupted DLLs with these
1087 * known good versions. The only programs that should install into this dll
1088 * cache are Windows Updates and IE (which is treated like a Windows Update)
1090 * Implementing this allows installing ie in win2k mode to actually install the
1091 * system dlls that we expect and need
1093 static int ProcessWindowsFileProtection(void)
1095 WIN32_FIND_DATAW finddata;
1096 HANDLE find_handle;
1097 BOOL find_rc;
1098 DWORD rc;
1099 HKEY hkey;
1100 LPWSTR dllcache = NULL;
1102 if (!RegOpenKeyW( HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", &hkey ))
1104 DWORD sz = 0;
1105 if (!RegQueryValueExW( hkey, L"SFCDllCacheDir", 0, NULL, NULL, &sz))
1107 sz += sizeof(WCHAR);
1108 dllcache = HeapAlloc(GetProcessHeap(),0,sz + sizeof(L"\\*"));
1109 RegQueryValueExW( hkey, L"SFCDllCacheDir", 0, NULL, (LPBYTE)dllcache, &sz);
1110 lstrcatW( dllcache, L"\\*" );
1113 RegCloseKey(hkey);
1115 if (!dllcache)
1117 DWORD sz = GetSystemDirectoryW( NULL, 0 );
1118 dllcache = HeapAlloc( GetProcessHeap(), 0, sz * sizeof(WCHAR) + sizeof(L"\\dllcache\\*"));
1119 GetSystemDirectoryW( dllcache, sz );
1120 lstrcatW( dllcache, L"\\dllcache\\*" );
1123 find_handle = FindFirstFileW(dllcache,&finddata);
1124 dllcache[ lstrlenW(dllcache) - 2] = 0; /* strip off wildcard */
1125 find_rc = find_handle != INVALID_HANDLE_VALUE;
1126 while (find_rc)
1128 WCHAR targetpath[MAX_PATH];
1129 WCHAR currentpath[MAX_PATH];
1130 UINT sz;
1131 UINT sz2;
1132 WCHAR tempfile[MAX_PATH];
1134 if (wcscmp(finddata.cFileName,L".") == 0 || wcscmp(finddata.cFileName,L"..") == 0)
1136 find_rc = FindNextFileW(find_handle,&finddata);
1137 continue;
1140 sz = MAX_PATH;
1141 sz2 = MAX_PATH;
1142 VerFindFileW(VFFF_ISSHAREDFILE, finddata.cFileName, windowsdir,
1143 windowsdir, currentpath, &sz, targetpath, &sz2);
1144 sz = MAX_PATH;
1145 rc = VerInstallFileW(0, finddata.cFileName, finddata.cFileName,
1146 dllcache, targetpath, currentpath, tempfile, &sz);
1147 if (rc != ERROR_SUCCESS)
1149 WINE_WARN("WFP: %s error 0x%x\n",wine_dbgstr_w(finddata.cFileName),rc);
1150 DeleteFileW(tempfile);
1153 /* now delete the source file so that we don't try to install it over and over again */
1154 lstrcpynW( targetpath, dllcache, MAX_PATH - 1 );
1155 sz = lstrlenW( targetpath );
1156 targetpath[sz++] = '\\';
1157 lstrcpynW( targetpath + sz, finddata.cFileName, MAX_PATH - sz );
1158 if (!DeleteFileW( targetpath ))
1159 WINE_WARN( "failed to delete %s: error %u\n", wine_dbgstr_w(targetpath), GetLastError() );
1161 find_rc = FindNextFileW(find_handle,&finddata);
1163 FindClose(find_handle);
1164 HeapFree(GetProcessHeap(),0,dllcache);
1165 return 1;
1168 static BOOL start_services_process(void)
1170 static const WCHAR svcctl_started_event[] = SVCCTL_STARTED_EVENT;
1171 PROCESS_INFORMATION pi;
1172 STARTUPINFOW si = { sizeof(si) };
1173 HANDLE wait_handles[2];
1175 if (!CreateProcessW(L"C:\\windows\\system32\\services.exe", NULL,
1176 NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &si, &pi))
1178 WINE_ERR("Couldn't start services.exe: error %u\n", GetLastError());
1179 return FALSE;
1181 CloseHandle(pi.hThread);
1183 wait_handles[0] = CreateEventW(NULL, TRUE, FALSE, svcctl_started_event);
1184 wait_handles[1] = pi.hProcess;
1186 /* wait for the event to become available or the process to exit */
1187 if ((WaitForMultipleObjects(2, wait_handles, FALSE, INFINITE)) == WAIT_OBJECT_0 + 1)
1189 DWORD exit_code;
1190 GetExitCodeProcess(pi.hProcess, &exit_code);
1191 WINE_ERR("Unexpected termination of services.exe - exit code %d\n", exit_code);
1192 CloseHandle(pi.hProcess);
1193 CloseHandle(wait_handles[0]);
1194 return FALSE;
1197 CloseHandle(pi.hProcess);
1198 CloseHandle(wait_handles[0]);
1199 return TRUE;
1202 static INT_PTR CALLBACK wait_dlgproc( HWND hwnd, UINT msg, WPARAM wp, LPARAM lp )
1204 switch (msg)
1206 case WM_INITDIALOG:
1208 DWORD len;
1209 WCHAR *buffer, text[1024];
1210 const WCHAR *name = (WCHAR *)lp;
1211 HICON icon = LoadImageW( 0, (LPCWSTR)IDI_WINLOGO, IMAGE_ICON, 48, 48, LR_SHARED );
1212 SendDlgItemMessageW( hwnd, IDC_WAITICON, STM_SETICON, (WPARAM)icon, 0 );
1213 SendDlgItemMessageW( hwnd, IDC_WAITTEXT, WM_GETTEXT, 1024, (LPARAM)text );
1214 len = lstrlenW(text) + lstrlenW(name) + 1;
1215 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
1216 swprintf( buffer, len, text, name );
1217 SendDlgItemMessageW( hwnd, IDC_WAITTEXT, WM_SETTEXT, 0, (LPARAM)buffer );
1218 HeapFree( GetProcessHeap(), 0, buffer );
1220 break;
1222 return 0;
1225 static HWND show_wait_window(void)
1227 HWND hwnd = CreateDialogParamW( GetModuleHandleW(0), MAKEINTRESOURCEW(IDD_WAITDLG), 0,
1228 wait_dlgproc, (LPARAM)prettyprint_configdir() );
1229 ShowWindow( hwnd, SW_SHOWNORMAL );
1230 return hwnd;
1233 static HANDLE start_rundll32( const WCHAR *inf_path, BOOL wow64 )
1235 WCHAR app[MAX_PATH + ARRAY_SIZE(L"\\rundll32.exe" )];
1236 STARTUPINFOW si;
1237 PROCESS_INFORMATION pi;
1238 WCHAR *buffer;
1239 DWORD len;
1241 memset( &si, 0, sizeof(si) );
1242 si.cb = sizeof(si);
1244 if (wow64)
1246 if (!GetSystemWow64DirectoryW( app, MAX_PATH )) return 0; /* not on 64-bit */
1248 else GetSystemDirectoryW( app, MAX_PATH );
1250 lstrcatW( app, L"\\rundll32.exe" );
1252 len = lstrlenW(app) + ARRAY_SIZE(L" setupapi,InstallHinfSection DefaultInstall 128 ") + lstrlenW(inf_path);
1254 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) ))) return 0;
1256 lstrcpyW( buffer, app );
1257 lstrcatW( buffer, L" setupapi,InstallHinfSection" );
1258 lstrcatW( buffer, wow64 ? L" Wow64Install" : L" DefaultInstall" );
1259 lstrcatW( buffer, L" 128 " );
1260 lstrcatW( buffer, inf_path );
1262 if (CreateProcessW( app, buffer, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ))
1263 CloseHandle( pi.hThread );
1264 else
1265 pi.hProcess = 0;
1267 HeapFree( GetProcessHeap(), 0, buffer );
1268 return pi.hProcess;
1271 static void install_root_pnp_devices(void)
1273 static const struct
1275 const char *name;
1276 const char *hardware_id;
1277 const char *infpath;
1279 root_devices[] =
1281 {"root\\wine\\winebus", "root\\winebus\0", "C:\\windows\\inf\\winebus.inf"},
1282 {"root\\wine\\wineusb", "root\\wineusb\0", "C:\\windows\\inf\\wineusb.inf"},
1284 SP_DEVINFO_DATA device = {sizeof(device)};
1285 unsigned int i;
1286 HDEVINFO set;
1288 if ((set = SetupDiCreateDeviceInfoList( NULL, NULL )) == INVALID_HANDLE_VALUE)
1290 WINE_ERR("Failed to create device info list, error %#x.\n", GetLastError());
1291 return;
1294 for (i = 0; i < ARRAY_SIZE(root_devices); ++i)
1296 if (!SetupDiCreateDeviceInfoA( set, root_devices[i].name, &GUID_NULL, NULL, NULL, 0, &device))
1298 if (GetLastError() != ERROR_DEVINST_ALREADY_EXISTS)
1299 WINE_ERR("Failed to create device %s, error %#x.\n", debugstr_a(root_devices[i].name), GetLastError());
1300 continue;
1303 if (!SetupDiSetDeviceRegistryPropertyA(set, &device, SPDRP_HARDWAREID,
1304 (const BYTE *)root_devices[i].hardware_id, (strlen(root_devices[i].hardware_id) + 2) * sizeof(WCHAR)))
1306 WINE_ERR("Failed to set hardware id for %s, error %#x.\n", debugstr_a(root_devices[i].name), GetLastError());
1307 continue;
1310 if (!SetupDiCallClassInstaller(DIF_REGISTERDEVICE, set, &device))
1312 WINE_ERR("Failed to register device %s, error %#x.\n", debugstr_a(root_devices[i].name), GetLastError());
1313 continue;
1316 if (!UpdateDriverForPlugAndPlayDevicesA(NULL, root_devices[i].hardware_id, root_devices[i].infpath, 0, NULL))
1317 WINE_ERR("Failed to install drivers for %s, error %#x.\n", debugstr_a(root_devices[i].name), GetLastError());
1320 SetupDiDestroyDeviceInfoList(set);
1323 static void update_user_profile(void)
1325 char token_buf[sizeof(TOKEN_USER) + sizeof(SID) + sizeof(DWORD) * SID_MAX_SUB_AUTHORITIES];
1326 HANDLE token;
1327 WCHAR profile[MAX_PATH], *sid;
1328 DWORD size;
1329 HKEY hkey, profile_hkey;
1331 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token))
1332 return;
1334 size = sizeof(token_buf);
1335 GetTokenInformation(token, TokenUser, token_buf, size, &size);
1336 CloseHandle(token);
1338 ConvertSidToStringSidW(((TOKEN_USER *)token_buf)->User.Sid, &sid);
1340 if (!RegCreateKeyExW(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList",
1341 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hkey, NULL))
1343 if (!RegCreateKeyExW(hkey, sid, 0, NULL, 0,
1344 KEY_ALL_ACCESS, NULL, &profile_hkey, NULL))
1346 DWORD flags = 0;
1347 if (SHGetSpecialFolderPathW(NULL, profile, CSIDL_PROFILE, TRUE))
1348 set_reg_value(profile_hkey, L"ProfileImagePath", profile);
1349 RegSetValueExW( profile_hkey, L"Flags", 0, REG_DWORD, (const BYTE *)&flags, sizeof(flags) );
1350 RegCloseKey(profile_hkey);
1353 RegCloseKey(hkey);
1356 LocalFree(sid);
1359 /* execute rundll32 on the wine.inf file if necessary */
1360 static void update_wineprefix( BOOL force )
1362 const WCHAR *config_dir = _wgetenv( L"WINECONFIGDIR" );
1363 WCHAR *inf_path = get_wine_inf_path();
1364 int fd;
1365 struct stat st;
1367 if (!inf_path)
1369 WINE_MESSAGE( "wine: failed to update %s, wine.inf not found\n", debugstr_w( config_dir ));
1370 return;
1372 if ((fd = _wopen( inf_path, O_RDONLY )) == -1)
1374 WINE_MESSAGE( "wine: failed to update %s with %s: %s\n",
1375 debugstr_w(config_dir), debugstr_w(inf_path), strerror(errno) );
1376 goto done;
1378 fstat( fd, &st );
1379 close( fd );
1381 if (update_timestamp( config_dir, st.st_mtime ) || force)
1383 HANDLE process;
1384 DWORD count = 0;
1386 if ((process = start_rundll32( inf_path, FALSE )))
1388 HWND hwnd = show_wait_window();
1389 for (;;)
1391 MSG msg;
1392 DWORD res = MsgWaitForMultipleObjects( 1, &process, FALSE, INFINITE, QS_ALLINPUT );
1393 if (res == WAIT_OBJECT_0)
1395 CloseHandle( process );
1396 if (count++ || !(process = start_rundll32( inf_path, TRUE ))) break;
1398 else while (PeekMessageW( &msg, 0, 0, 0, PM_REMOVE )) DispatchMessageW( &msg );
1400 DestroyWindow( hwnd );
1402 install_root_pnp_devices();
1403 update_user_profile();
1405 WINE_MESSAGE( "wine: configuration in %s has been updated.\n", debugstr_w(prettyprint_configdir()) );
1408 done:
1409 HeapFree( GetProcessHeap(), 0, inf_path );
1412 /* Process items in the StartUp group of the user's Programs under the Start Menu. Some installers put
1413 * shell links here to restart themselves after boot. */
1414 static BOOL ProcessStartupItems(void)
1416 BOOL ret = FALSE;
1417 HRESULT hr;
1418 IShellFolder *psfDesktop = NULL, *psfStartup = NULL;
1419 LPITEMIDLIST pidlStartup = NULL, pidlItem;
1420 ULONG NumPIDLs;
1421 IEnumIDList *iEnumList = NULL;
1422 STRRET strret;
1423 WCHAR wszCommand[MAX_PATH];
1425 WINE_TRACE("Processing items in the StartUp folder.\n");
1427 hr = SHGetDesktopFolder(&psfDesktop);
1428 if (FAILED(hr))
1430 WINE_ERR("Couldn't get desktop folder.\n");
1431 goto done;
1434 hr = SHGetSpecialFolderLocation(NULL, CSIDL_STARTUP, &pidlStartup);
1435 if (FAILED(hr))
1437 WINE_TRACE("Couldn't get StartUp folder location.\n");
1438 goto done;
1441 hr = IShellFolder_BindToObject(psfDesktop, pidlStartup, NULL, &IID_IShellFolder, (LPVOID*)&psfStartup);
1442 if (FAILED(hr))
1444 WINE_TRACE("Couldn't bind IShellFolder to StartUp folder.\n");
1445 goto done;
1448 hr = IShellFolder_EnumObjects(psfStartup, NULL, SHCONTF_NONFOLDERS | SHCONTF_INCLUDEHIDDEN, &iEnumList);
1449 if (FAILED(hr))
1451 WINE_TRACE("Unable to enumerate StartUp objects.\n");
1452 goto done;
1455 while (IEnumIDList_Next(iEnumList, 1, &pidlItem, &NumPIDLs) == S_OK &&
1456 (NumPIDLs) == 1)
1458 hr = IShellFolder_GetDisplayNameOf(psfStartup, pidlItem, SHGDN_FORPARSING, &strret);
1459 if (FAILED(hr))
1460 WINE_TRACE("Unable to get display name of enumeration item.\n");
1461 else
1463 hr = StrRetToBufW(&strret, pidlItem, wszCommand, MAX_PATH);
1464 if (FAILED(hr))
1465 WINE_TRACE("Unable to parse display name.\n");
1466 else
1468 HINSTANCE hinst;
1470 hinst = ShellExecuteW(NULL, NULL, wszCommand, NULL, NULL, SW_SHOWNORMAL);
1471 if (PtrToUlong(hinst) <= 32)
1472 WINE_WARN("Error %p executing command %s.\n", hinst, wine_dbgstr_w(wszCommand));
1476 ILFree(pidlItem);
1479 /* Return success */
1480 ret = TRUE;
1482 done:
1483 if (iEnumList) IEnumIDList_Release(iEnumList);
1484 if (psfStartup) IShellFolder_Release(psfStartup);
1485 if (pidlStartup) ILFree(pidlStartup);
1487 return ret;
1490 static void usage( int status )
1492 WINE_MESSAGE( "Usage: wineboot [options]\n" );
1493 WINE_MESSAGE( "Options;\n" );
1494 WINE_MESSAGE( " -h,--help Display this help message\n" );
1495 WINE_MESSAGE( " -e,--end-session End the current session cleanly\n" );
1496 WINE_MESSAGE( " -f,--force Force exit for processes that don't exit cleanly\n" );
1497 WINE_MESSAGE( " -i,--init Perform initialization for first Wine instance\n" );
1498 WINE_MESSAGE( " -k,--kill Kill running processes without any cleanup\n" );
1499 WINE_MESSAGE( " -r,--restart Restart only, don't do normal startup operations\n" );
1500 WINE_MESSAGE( " -s,--shutdown Shutdown only, don't reboot\n" );
1501 WINE_MESSAGE( " -u,--update Update the wineprefix directory\n" );
1502 exit( status );
1505 int __cdecl main( int argc, char *argv[] )
1507 /* First, set the current directory to SystemRoot */
1508 int i, j;
1509 BOOL end_session, force, init, kill, restart, shutdown, update;
1510 HANDLE event;
1511 OBJECT_ATTRIBUTES attr;
1512 UNICODE_STRING nameW;
1513 BOOL is_wow64;
1515 end_session = force = init = kill = restart = shutdown = update = FALSE;
1516 GetWindowsDirectoryW( windowsdir, MAX_PATH );
1517 if( !SetCurrentDirectoryW( windowsdir ) )
1518 WINE_ERR("Cannot set the dir to %s (%d)\n", wine_dbgstr_w(windowsdir), GetLastError() );
1520 if (IsWow64Process( GetCurrentProcess(), &is_wow64 ) && is_wow64)
1522 STARTUPINFOW si;
1523 PROCESS_INFORMATION pi;
1524 WCHAR filename[MAX_PATH];
1525 void *redir;
1526 DWORD exit_code;
1528 memset( &si, 0, sizeof(si) );
1529 si.cb = sizeof(si);
1530 GetModuleFileNameW( 0, filename, MAX_PATH );
1532 Wow64DisableWow64FsRedirection( &redir );
1533 if (CreateProcessW( filename, GetCommandLineW(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ))
1535 WINE_TRACE( "restarting %s\n", wine_dbgstr_w(filename) );
1536 WaitForSingleObject( pi.hProcess, INFINITE );
1537 GetExitCodeProcess( pi.hProcess, &exit_code );
1538 ExitProcess( exit_code );
1540 else WINE_ERR( "failed to restart 64-bit %s, err %d\n", wine_dbgstr_w(filename), GetLastError() );
1541 Wow64RevertWow64FsRedirection( redir );
1544 for (i = 1; i < argc; i++)
1546 if (argv[i][0] != '-') continue;
1547 if (argv[i][1] == '-')
1549 if (!strcmp( argv[i], "--help" )) usage( 0 );
1550 else if (!strcmp( argv[i], "--end-session" )) end_session = TRUE;
1551 else if (!strcmp( argv[i], "--force" )) force = TRUE;
1552 else if (!strcmp( argv[i], "--init" )) init = TRUE;
1553 else if (!strcmp( argv[i], "--kill" )) kill = TRUE;
1554 else if (!strcmp( argv[i], "--restart" )) restart = TRUE;
1555 else if (!strcmp( argv[i], "--shutdown" )) shutdown = TRUE;
1556 else if (!strcmp( argv[i], "--update" )) update = TRUE;
1557 else usage( 1 );
1558 continue;
1560 for (j = 1; argv[i][j]; j++)
1562 switch (argv[i][j])
1564 case 'e': end_session = TRUE; break;
1565 case 'f': force = TRUE; break;
1566 case 'i': init = TRUE; break;
1567 case 'k': kill = TRUE; break;
1568 case 'r': restart = TRUE; break;
1569 case 's': shutdown = TRUE; break;
1570 case 'u': update = TRUE; break;
1571 case 'h': usage(0); break;
1572 default: usage(1); break;
1577 if (end_session)
1579 if (kill)
1581 if (!shutdown_all_desktops( force )) return 1;
1583 else if (!shutdown_close_windows( force )) return 1;
1586 if (kill) kill_processes( shutdown );
1588 if (shutdown) return 0;
1590 /* create event to be inherited by services.exe */
1591 InitializeObjectAttributes( &attr, &nameW, OBJ_OPENIF | OBJ_INHERIT, 0, NULL );
1592 RtlInitUnicodeString( &nameW, L"\\KernelObjects\\__wineboot_event" );
1593 NtCreateEvent( &event, EVENT_ALL_ACCESS, &attr, NotificationEvent, 0 );
1595 ResetEvent( event ); /* in case this is a restart */
1597 create_user_shared_data();
1598 create_hardware_registry_keys();
1599 create_dynamic_registry_keys();
1600 create_environment_registry_keys();
1601 wininit();
1602 pendingRename();
1604 ProcessWindowsFileProtection();
1605 ProcessRunKeys( HKEY_LOCAL_MACHINE, L"RunServicesOnce", TRUE, FALSE );
1607 if (init || (kill && !restart))
1609 ProcessRunKeys( HKEY_LOCAL_MACHINE, L"RunServices", FALSE, FALSE );
1610 start_services_process();
1612 if (init || update) update_wineprefix( update );
1614 create_volatile_environment_registry_key();
1616 ProcessRunKeys( HKEY_LOCAL_MACHINE, L"RunOnce", TRUE, TRUE );
1618 if (!init && !restart)
1620 ProcessRunKeys( HKEY_LOCAL_MACHINE, L"Run", FALSE, FALSE );
1621 ProcessRunKeys( HKEY_CURRENT_USER, L"Run", FALSE, FALSE );
1622 ProcessStartupItems();
1625 WINE_TRACE("Operation done\n");
1627 SetEvent( event );
1628 return 0;