msvcrt: Import truncf implementation from musl.
[wine.git] / programs / wineboot / wineboot.c
blob92276fcbe7645e0604cd740099fe6c626b7b5a38
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 <ws2tcpip.h>
68 #include <winternl.h>
69 #include <ddk/wdm.h>
70 #include <sddl.h>
71 #include <wine/svcctl.h>
72 #include <wine/asm.h>
73 #include <wine/debug.h>
75 #include <shlobj.h>
76 #include <shobjidl.h>
77 #include <shlwapi.h>
78 #include <shellapi.h>
79 #include <setupapi.h>
80 #include <newdev.h>
81 #include "resource.h"
83 WINE_DEFAULT_DEBUG_CHANNEL(wineboot);
85 extern BOOL shutdown_close_windows( BOOL force );
86 extern BOOL shutdown_all_desktops( BOOL force );
87 extern void kill_processes( BOOL kill_desktop );
89 static WCHAR windowsdir[MAX_PATH];
90 static const BOOL is_64bit = sizeof(void *) > sizeof(int);
92 /* retrieve the path to the wine.inf file */
93 static WCHAR *get_wine_inf_path(void)
95 WCHAR *dir, *name = NULL;
97 if ((dir = _wgetenv( L"WINEBUILDDIR" )))
99 if (!(name = HeapAlloc( GetProcessHeap(), 0,
100 sizeof(L"\\loader\\wine.inf") + lstrlenW(dir) * sizeof(WCHAR) )))
101 return NULL;
102 lstrcpyW( name, dir );
103 lstrcatW( name, L"\\loader" );
105 else if ((dir = _wgetenv( L"WINEDATADIR" )))
107 if (!(name = HeapAlloc( GetProcessHeap(), 0, sizeof(L"\\wine.inf") + lstrlenW(dir) * sizeof(WCHAR) )))
108 return NULL;
109 lstrcpyW( name, dir );
111 else return NULL;
113 lstrcatW( name, L"\\wine.inf" );
114 name[1] = '\\'; /* change \??\ to \\?\ */
115 return name;
118 /* update the timestamp if different from the reference time */
119 static BOOL update_timestamp( const WCHAR *config_dir, unsigned long timestamp )
121 BOOL ret = FALSE;
122 int fd, count;
123 char buffer[100];
124 WCHAR *file = HeapAlloc( GetProcessHeap(), 0, lstrlenW(config_dir) * sizeof(WCHAR) + sizeof(L"\\.update-timestamp") );
126 if (!file) return FALSE;
127 lstrcpyW( file, config_dir );
128 lstrcatW( file, L"\\.update-timestamp" );
130 if ((fd = _wopen( file, O_RDWR )) != -1)
132 if ((count = read( fd, buffer, sizeof(buffer) - 1 )) >= 0)
134 buffer[count] = 0;
135 if (!strncmp( buffer, "disable", sizeof("disable")-1 )) goto done;
136 if (timestamp == strtoul( buffer, NULL, 10 )) goto done;
138 lseek( fd, 0, SEEK_SET );
139 chsize( fd, 0 );
141 else
143 if (errno != ENOENT) goto done;
144 if ((fd = _wopen( file, O_WRONLY | O_CREAT | O_TRUNC, 0666 )) == -1) goto done;
147 count = sprintf( buffer, "%lu\n", timestamp );
148 if (write( fd, buffer, count ) != count)
150 WINE_WARN( "failed to update timestamp in %s\n", debugstr_w(file) );
151 chsize( fd, 0 );
153 else ret = TRUE;
155 done:
156 if (fd != -1) close( fd );
157 HeapFree( GetProcessHeap(), 0, file );
158 return ret;
161 /* print the config directory in a more Unix-ish way */
162 static const WCHAR *prettyprint_configdir(void)
164 static WCHAR buffer[MAX_PATH];
165 WCHAR *p, *path = _wgetenv( L"WINECONFIGDIR" );
167 lstrcpynW( buffer, path, ARRAY_SIZE(buffer) );
168 if (lstrlenW( path ) >= ARRAY_SIZE(buffer) )
169 lstrcpyW( buffer + ARRAY_SIZE(buffer) - 4, L"..." );
171 if (!wcsncmp( buffer, L"\\??\\unix\\", 9 ))
173 for (p = buffer + 9; *p; p++) if (*p == '\\') *p = '/';
174 return buffer + 9;
176 else if (!wcsncmp( buffer, L"\\??\\Z:\\", 7 ))
178 for (p = buffer + 6; *p; p++) if (*p == '\\') *p = '/';
179 return buffer + 6;
181 else return buffer + 4;
184 /* wrapper for RegSetValueExW */
185 static DWORD set_reg_value( HKEY hkey, const WCHAR *name, const WCHAR *value )
187 return RegSetValueExW( hkey, name, 0, REG_SZ, (const BYTE *)value, (lstrlenW(value) + 1) * sizeof(WCHAR) );
190 static DWORD set_reg_value_dword( HKEY hkey, const WCHAR *name, DWORD value )
192 return RegSetValueExW( hkey, name, 0, REG_DWORD, (const BYTE *)&value, sizeof(value) );
195 #if defined(__i386__) || defined(__x86_64__)
197 static void initialize_xstate_features(struct _KUSER_SHARED_DATA *data)
199 XSTATE_CONFIGURATION *xstate = &data->XState;
200 unsigned int i;
201 int regs[4];
203 if (!data->ProcessorFeatures[PF_AVX_INSTRUCTIONS_AVAILABLE])
204 return;
206 __cpuidex(regs, 0, 0);
208 TRACE("Max cpuid level %#x.\n", regs[0]);
209 if (regs[0] < 0xd)
210 return;
212 __cpuidex(regs, 1, 0);
213 TRACE("CPU features %#x, %#x, %#x, %#x.\n", regs[0], regs[1], regs[2], regs[3]);
214 if (!(regs[2] & (0x1 << 27))) /* xsave OS enabled */
215 return;
217 __cpuidex(regs, 0xd, 0);
218 TRACE("XSAVE details %#x, %#x, %#x, %#x.\n", regs[0], regs[1], regs[2], regs[3]);
219 if (!(regs[0] & XSTATE_AVX))
220 return;
222 xstate->EnabledFeatures = (1 << XSTATE_LEGACY_FLOATING_POINT) | (1 << XSTATE_LEGACY_SSE) | (1 << XSTATE_AVX);
223 xstate->EnabledVolatileFeatures = xstate->EnabledFeatures;
224 xstate->Size = sizeof(XSAVE_FORMAT) + sizeof(XSTATE);
225 xstate->AllFeatureSize = regs[1];
226 xstate->AllFeatures[0] = offsetof(XSAVE_FORMAT, XmmRegisters);
227 xstate->AllFeatures[1] = sizeof(M128A) * 16;
228 xstate->AllFeatures[2] = sizeof(YMMCONTEXT);
230 for (i = 0; i < 3; ++i)
231 xstate->Features[i].Size = xstate->AllFeatures[i];
233 xstate->Features[1].Offset = xstate->Features[0].Size;
234 xstate->Features[2].Offset = sizeof(XSAVE_FORMAT) + offsetof(XSTATE, YmmContext);
236 __cpuidex(regs, 0xd, 1);
237 xstate->OptimizedSave = regs[0] & 1;
238 xstate->CompactionEnabled = !!(regs[0] & 2);
240 __cpuidex(regs, 0xd, 2);
241 TRACE("XSAVE feature 2 %#x, %#x, %#x, %#x.\n", regs[0], regs[1], regs[2], regs[3]);
244 #else
246 static void initialize_xstate_features(struct _KUSER_SHARED_DATA *data)
250 #endif
252 static void create_user_shared_data(void)
254 struct _KUSER_SHARED_DATA *data;
255 RTL_OSVERSIONINFOEXW version;
256 SYSTEM_CPU_INFORMATION sci;
257 SYSTEM_BASIC_INFORMATION sbi;
258 BOOLEAN *features;
259 OBJECT_ATTRIBUTES attr = {sizeof(attr)};
260 UNICODE_STRING name;
261 NTSTATUS status;
262 HANDLE handle;
264 RtlInitUnicodeString( &name, L"\\KernelObjects\\__wine_user_shared_data" );
265 InitializeObjectAttributes( &attr, &name, OBJ_OPENIF, NULL, NULL );
266 if ((status = NtOpenSection( &handle, SECTION_ALL_ACCESS, &attr )))
268 ERR( "cannot open __wine_user_shared_data: %x\n", status );
269 return;
271 data = MapViewOfFile( handle, FILE_MAP_WRITE, 0, 0, sizeof(*data) );
272 CloseHandle( handle );
273 if (!data)
275 ERR( "cannot map __wine_user_shared_data\n" );
276 return;
279 version.dwOSVersionInfoSize = sizeof(version);
280 RtlGetVersion( &version );
281 NtQuerySystemInformation( SystemBasicInformation, &sbi, sizeof(sbi), NULL );
282 NtQuerySystemInformation( SystemCpuInformation, &sci, sizeof(sci), NULL );
284 data->TickCountMultiplier = 1 << 24;
285 data->LargePageMinimum = 2 * 1024 * 1024;
286 data->NtBuildNumber = version.dwBuildNumber;
287 data->NtProductType = version.wProductType;
288 data->ProductTypeIsValid = TRUE;
289 data->NativeProcessorArchitecture = sci.ProcessorArchitecture;
290 data->NtMajorVersion = version.dwMajorVersion;
291 data->NtMinorVersion = version.dwMinorVersion;
292 data->SuiteMask = version.wSuiteMask;
293 data->NumberOfPhysicalPages = sbi.MmNumberOfPhysicalPages;
294 data->NXSupportPolicy = NX_SUPPORT_POLICY_OPTIN;
295 wcscpy( data->NtSystemRoot, L"C:\\windows" );
297 features = data->ProcessorFeatures;
298 switch (sci.ProcessorArchitecture)
300 case PROCESSOR_ARCHITECTURE_INTEL:
301 case PROCESSOR_ARCHITECTURE_AMD64:
302 features[PF_COMPARE_EXCHANGE_DOUBLE] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_CX8);
303 features[PF_MMX_INSTRUCTIONS_AVAILABLE] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_MMX);
304 features[PF_XMMI_INSTRUCTIONS_AVAILABLE] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_SSE);
305 features[PF_3DNOW_INSTRUCTIONS_AVAILABLE] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_3DNOW);
306 features[PF_RDTSC_INSTRUCTION_AVAILABLE] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_TSC);
307 features[PF_PAE_ENABLED] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_PAE);
308 features[PF_XMMI64_INSTRUCTIONS_AVAILABLE] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_SSE2);
309 features[PF_SSE3_INSTRUCTIONS_AVAILABLE] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_SSE3);
310 features[PF_SSSE3_INSTRUCTIONS_AVAILABLE] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_SSSE3);
311 features[PF_XSAVE_ENABLED] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_XSAVE);
312 features[PF_COMPARE_EXCHANGE128] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_CX128);
313 features[PF_SSE_DAZ_MODE_AVAILABLE] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_DAZ);
314 features[PF_NX_ENABLED] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_NX);
315 features[PF_SECOND_LEVEL_ADDRESS_TRANSLATION] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_2NDLEV);
316 features[PF_VIRT_FIRMWARE_ENABLED] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_VIRT);
317 features[PF_RDWRFSGSBASE_AVAILABLE] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_RDFS);
318 features[PF_FASTFAIL_AVAILABLE] = TRUE;
319 features[PF_SSE4_1_INSTRUCTIONS_AVAILABLE] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_SSE41);
320 features[PF_SSE4_2_INSTRUCTIONS_AVAILABLE] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_SSE42);
321 features[PF_AVX_INSTRUCTIONS_AVAILABLE] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_AVX);
322 features[PF_AVX2_INSTRUCTIONS_AVAILABLE] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_AVX2);
323 break;
324 case PROCESSOR_ARCHITECTURE_ARM:
325 features[PF_ARM_VFP_32_REGISTERS_AVAILABLE] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_ARM_VFP_32);
326 features[PF_ARM_NEON_INSTRUCTIONS_AVAILABLE] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_ARM_NEON);
327 features[PF_ARM_V8_INSTRUCTIONS_AVAILABLE] = (sci.ProcessorLevel >= 8);
328 break;
329 case PROCESSOR_ARCHITECTURE_ARM64:
330 features[PF_ARM_V8_INSTRUCTIONS_AVAILABLE] = TRUE;
331 features[PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_ARM_V8_CRC32);
332 features[PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE] = !!(sci.ProcessorFeatureBits & CPU_FEATURE_ARM_V8_CRYPTO);
333 break;
335 data->ActiveProcessorCount = NtCurrentTeb()->Peb->NumberOfProcessors;
336 data->ActiveGroupCount = 1;
338 initialize_xstate_features( data );
340 UnmapViewOfFile( data );
343 #if defined(__i386__) || defined(__x86_64__)
345 static void regs_to_str( int *regs, unsigned int len, WCHAR *buffer )
347 unsigned int i;
348 unsigned char *p = (unsigned char *)regs;
350 for (i = 0; i < len; i++) { buffer[i] = *p++; }
351 buffer[i] = 0;
354 static unsigned int get_model( unsigned int reg0, unsigned int *stepping, unsigned int *family )
356 unsigned int model, family_id = (reg0 & (0x0f << 8)) >> 8;
358 model = (reg0 & (0x0f << 4)) >> 4;
359 if (family_id == 6 || family_id == 15) model |= (reg0 & (0x0f << 16)) >> 12;
361 *family = family_id;
362 if (family_id == 15) *family += (reg0 & (0xff << 20)) >> 20;
364 *stepping = reg0 & 0x0f;
365 return model;
368 static void get_identifier( WCHAR *buf, size_t size, const WCHAR *arch )
370 unsigned int family, model, stepping;
371 int regs[4] = {0, 0, 0, 0};
373 __cpuid( regs, 1 );
374 model = get_model( regs[0], &stepping, &family );
375 swprintf( buf, size, L"%s Family %u Model %u Stepping %u", arch, family, model, stepping );
378 static void get_vendorid( WCHAR *buf )
380 int tmp, regs[4] = {0, 0, 0, 0};
382 __cpuid( regs, 0 );
383 tmp = regs[2]; /* swap edx and ecx */
384 regs[2] = regs[3];
385 regs[3] = tmp;
387 regs_to_str( regs + 1, 12, buf );
390 static void get_namestring( WCHAR *buf )
392 int regs[4] = {0, 0, 0, 0};
393 int i;
395 __cpuid( regs, 0x80000000 );
396 if (regs[0] >= 0x80000004)
398 __cpuid( regs, 0x80000002 );
399 regs_to_str( regs, 16, buf );
400 __cpuid( regs, 0x80000003 );
401 regs_to_str( regs, 16, buf + 16 );
402 __cpuid( regs, 0x80000004 );
403 regs_to_str( regs, 16, buf + 32 );
405 for (i = lstrlenW(buf) - 1; i >= 0 && buf[i] == ' '; i--) buf[i] = 0;
408 #else /* __i386__ || __x86_64__ */
410 static void get_identifier( WCHAR *buf, size_t size, const WCHAR *arch ) { }
411 static void get_vendorid( WCHAR *buf ) { }
412 static void get_namestring( WCHAR *buf ) { }
414 #endif /* __i386__ || __x86_64__ */
416 #include "pshpack1.h"
417 struct smbios_prologue
419 BYTE calling_method;
420 BYTE major_version;
421 BYTE minor_version;
422 BYTE revision;
423 DWORD length;
426 enum smbios_type
428 SMBIOS_TYPE_BIOS,
429 SMBIOS_TYPE_SYSTEM,
430 SMBIOS_TYPE_BASEBOARD,
433 struct smbios_header
435 BYTE type;
436 BYTE length;
437 WORD handle;
440 struct smbios_baseboard
442 struct smbios_header hdr;
443 BYTE vendor;
444 BYTE product;
445 BYTE version;
446 BYTE serial;
449 struct smbios_bios
451 struct smbios_header hdr;
452 BYTE vendor;
453 BYTE version;
454 WORD start;
455 BYTE date;
456 BYTE size;
457 UINT64 characteristics;
458 BYTE characteristics_ext[2];
459 BYTE system_bios_major_release;
460 BYTE system_bios_minor_release;
461 BYTE ec_firmware_major_release;
462 BYTE ec_firmware_minor_release;
465 struct smbios_system
467 struct smbios_header hdr;
468 BYTE vendor;
469 BYTE product;
470 BYTE version;
471 BYTE serial;
472 BYTE uuid[16];
473 BYTE wake_up_type;
474 BYTE sku;
475 BYTE family;
477 #include "poppack.h"
479 #define RSMB (('R' << 24) | ('S' << 16) | ('M' << 8) | 'B')
481 static const struct smbios_header *find_smbios_entry( enum smbios_type type, const char *buf, UINT len )
483 const char *ptr, *start;
484 const struct smbios_prologue *prologue;
485 const struct smbios_header *hdr;
487 if (len < sizeof(struct smbios_prologue)) return NULL;
488 prologue = (const struct smbios_prologue *)buf;
489 if (prologue->length > len - sizeof(*prologue) || prologue->length < sizeof(*hdr)) return NULL;
491 start = (const char *)(prologue + 1);
492 hdr = (const struct smbios_header *)start;
494 for (;;)
496 if ((const char *)hdr - start >= prologue->length - sizeof(*hdr)) return NULL;
498 if (!hdr->length)
500 WARN( "invalid entry\n" );
501 return NULL;
504 if (hdr->type == type)
506 if ((const char *)hdr - start + hdr->length > prologue->length) return NULL;
507 break;
509 else /* skip other entries and their strings */
511 for (ptr = (const char *)hdr + hdr->length; ptr - buf < len && *ptr; ptr++)
513 for (; ptr - buf < len; ptr++) if (!*ptr) break;
515 if (ptr == (const char *)hdr + hdr->length) ptr++;
516 hdr = (const struct smbios_header *)(ptr + 1);
520 return hdr;
523 static inline WCHAR *heap_strdupAW( const char *src )
525 int len;
526 WCHAR *dst;
527 if (!src) return NULL;
528 len = MultiByteToWideChar( CP_ACP, 0, src, -1, NULL, 0 );
529 if ((dst = HeapAlloc( GetProcessHeap(), 0, len * sizeof(*dst) ))) MultiByteToWideChar( CP_ACP, 0, src, -1, dst, len );
530 return dst;
533 static WCHAR *get_smbios_string( BYTE id, const char *buf, UINT offset, UINT buflen )
535 const char *ptr = buf + offset;
536 UINT i = 0;
538 if (!id || offset >= buflen) return NULL;
539 for (ptr = buf + offset; ptr - buf < buflen && *ptr; ptr++)
541 if (++i == id) return heap_strdupAW( ptr );
542 for (; ptr - buf < buflen; ptr++) if (!*ptr) break;
544 return NULL;
547 static void set_value_from_smbios_string( HKEY key, const WCHAR *value, BYTE id, const char *buf, UINT offset, UINT buflen )
549 WCHAR *str;
550 str = get_smbios_string( id, buf, offset, buflen );
551 set_reg_value( key, value, str ? str : L"" );
552 HeapFree( GetProcessHeap(), 0, str );
555 static void create_bios_baseboard_values( HKEY bios_key, const char *buf, UINT len )
557 const struct smbios_header *hdr;
558 const struct smbios_baseboard *baseboard;
559 UINT offset;
561 if (!(hdr = find_smbios_entry( SMBIOS_TYPE_BASEBOARD, buf, len ))) return;
562 baseboard = (const struct smbios_baseboard *)hdr;
563 offset = (const char *)baseboard - buf + baseboard->hdr.length;
565 set_value_from_smbios_string( bios_key, L"BaseBoardManufacturer", baseboard->vendor, buf, offset, len );
566 set_value_from_smbios_string( bios_key, L"BaseBoardProduct", baseboard->product, buf, offset, len );
567 set_value_from_smbios_string( bios_key, L"BaseBoardVersion", baseboard->version, buf, offset, len );
570 static void create_bios_bios_values( HKEY bios_key, const char *buf, UINT len )
572 const struct smbios_header *hdr;
573 const struct smbios_bios *bios;
574 UINT offset;
576 if (!(hdr = find_smbios_entry( SMBIOS_TYPE_BIOS, buf, len ))) return;
577 bios = (const struct smbios_bios *)hdr;
578 offset = (const char *)bios - buf + bios->hdr.length;
580 set_value_from_smbios_string( bios_key, L"BIOSVendor", bios->vendor, buf, offset, len );
581 set_value_from_smbios_string( bios_key, L"BIOSVersion", bios->version, buf, offset, len );
582 set_value_from_smbios_string( bios_key, L"BIOSReleaseDate", bios->date, buf, offset, len );
584 if (bios->hdr.length >= 0x18)
586 set_reg_value_dword( bios_key, L"BiosMajorRelease", bios->system_bios_major_release );
587 set_reg_value_dword( bios_key, L"BiosMinorRelease", bios->system_bios_minor_release );
588 set_reg_value_dword( bios_key, L"ECFirmwareMajorVersion", bios->ec_firmware_major_release );
589 set_reg_value_dword( bios_key, L"ECFirmwareMinorVersion", bios->ec_firmware_minor_release );
591 else
593 set_reg_value_dword( bios_key, L"BiosMajorRelease", 0xFF );
594 set_reg_value_dword( bios_key, L"BiosMinorRelease", 0xFF );
595 set_reg_value_dword( bios_key, L"ECFirmwareMajorVersion", 0xFF );
596 set_reg_value_dword( bios_key, L"ECFirmwareMinorVersion", 0xFF );
600 static void create_bios_system_values( HKEY bios_key, const char *buf, UINT len )
602 const struct smbios_header *hdr;
603 const struct smbios_system *system;
604 UINT offset;
606 if (!(hdr = find_smbios_entry( SMBIOS_TYPE_SYSTEM, buf, len ))) return;
607 system = (const struct smbios_system *)hdr;
608 offset = (const char *)system - buf + system->hdr.length;
610 set_value_from_smbios_string( bios_key, L"SystemManufacturer", system->vendor, buf, offset, len );
611 set_value_from_smbios_string( bios_key, L"SystemProductName", system->product, buf, offset, len );
612 set_value_from_smbios_string( bios_key, L"SystemVersion", system->version, buf, offset, len );
614 if (system->hdr.length >= 0x1B)
616 set_value_from_smbios_string( bios_key, L"SystemSKU", system->sku, buf, offset, len );
617 set_value_from_smbios_string( bios_key, L"SystemFamily", system->family, buf, offset, len );
619 else
621 set_value_from_smbios_string( bios_key, L"SystemSKU", 0, buf, offset, len );
622 set_value_from_smbios_string( bios_key, L"SystemFamily", 0, buf, offset, len );
626 static void create_bios_key( HKEY system_key )
628 HKEY bios_key;
629 UINT len;
630 char *buf;
632 if (RegCreateKeyExW( system_key, L"BIOS", 0, NULL, REG_OPTION_VOLATILE,
633 KEY_ALL_ACCESS, NULL, &bios_key, NULL ))
634 return;
636 len = GetSystemFirmwareTable( RSMB, 0, NULL, 0 );
637 if (!(buf = HeapAlloc( GetProcessHeap(), 0, len ))) goto done;
638 len = GetSystemFirmwareTable( RSMB, 0, buf, len );
640 create_bios_baseboard_values( bios_key, buf, len );
641 create_bios_bios_values( bios_key, buf, len );
642 create_bios_system_values( bios_key, buf, len );
644 done:
645 HeapFree( GetProcessHeap(), 0, buf );
646 RegCloseKey( bios_key );
649 /* create the volatile hardware registry keys */
650 static void create_hardware_registry_keys(void)
652 unsigned int i;
653 HKEY hkey, system_key, cpu_key, fpu_key;
654 SYSTEM_CPU_INFORMATION sci;
655 PROCESSOR_POWER_INFORMATION* power_info;
656 ULONG sizeof_power_info = sizeof(PROCESSOR_POWER_INFORMATION) * NtCurrentTeb()->Peb->NumberOfProcessors;
657 WCHAR id[60], namestr[49], vendorid[13];
659 get_namestring( namestr );
660 get_vendorid( vendorid );
661 NtQuerySystemInformation( SystemCpuInformation, &sci, sizeof(sci), NULL );
663 power_info = HeapAlloc( GetProcessHeap(), 0, sizeof_power_info );
664 if (power_info == NULL)
665 return;
666 if (NtPowerInformation( ProcessorInformation, NULL, 0, power_info, sizeof_power_info ))
667 memset( power_info, 0, sizeof_power_info );
669 switch (sci.ProcessorArchitecture)
671 case PROCESSOR_ARCHITECTURE_ARM:
672 case PROCESSOR_ARCHITECTURE_ARM64:
673 swprintf( id, ARRAY_SIZE(id), L"ARM Family %u Model %u Revision %u",
674 sci.ProcessorLevel, HIBYTE(sci.ProcessorRevision), LOBYTE(sci.ProcessorRevision) );
675 break;
677 case PROCESSOR_ARCHITECTURE_AMD64:
678 get_identifier( id, ARRAY_SIZE(id), !wcscmp(vendorid, L"AuthenticAMD") ? L"AMD64" : L"Intel64" );
679 break;
681 case PROCESSOR_ARCHITECTURE_INTEL:
682 default:
683 get_identifier( id, ARRAY_SIZE(id), L"x86" );
684 break;
687 if (RegCreateKeyExW( HKEY_LOCAL_MACHINE, L"Hardware\\Description\\System", 0, NULL,
688 REG_OPTION_VOLATILE, KEY_ALL_ACCESS, NULL, &system_key, NULL ))
690 HeapFree( GetProcessHeap(), 0, power_info );
691 return;
694 switch (sci.ProcessorArchitecture)
696 case PROCESSOR_ARCHITECTURE_ARM:
697 case PROCESSOR_ARCHITECTURE_ARM64:
698 set_reg_value( system_key, L"Identifier", L"ARM processor family" );
699 break;
701 case PROCESSOR_ARCHITECTURE_INTEL:
702 case PROCESSOR_ARCHITECTURE_AMD64:
703 default:
704 set_reg_value( system_key, L"Identifier", L"AT compatible" );
705 break;
708 if (sci.ProcessorArchitecture == PROCESSOR_ARCHITECTURE_ARM ||
709 sci.ProcessorArchitecture == PROCESSOR_ARCHITECTURE_ARM64 ||
710 RegCreateKeyExW( system_key, L"FloatingPointProcessor", 0, NULL, REG_OPTION_VOLATILE,
711 KEY_ALL_ACCESS, NULL, &fpu_key, NULL ))
712 fpu_key = 0;
713 if (RegCreateKeyExW( system_key, L"CentralProcessor", 0, NULL, REG_OPTION_VOLATILE,
714 KEY_ALL_ACCESS, NULL, &cpu_key, NULL ))
715 cpu_key = 0;
717 for (i = 0; i < NtCurrentTeb()->Peb->NumberOfProcessors; i++)
719 WCHAR numW[10];
721 swprintf( numW, ARRAY_SIZE(numW), L"%u", i );
722 if (!RegCreateKeyExW( cpu_key, numW, 0, NULL, REG_OPTION_VOLATILE,
723 KEY_ALL_ACCESS, NULL, &hkey, NULL ))
725 RegSetValueExW( hkey, L"FeatureSet", 0, REG_DWORD, (BYTE *)&sci.ProcessorFeatureBits, sizeof(DWORD) );
726 set_reg_value( hkey, L"Identifier", id );
727 /* TODO: report ARM properly */
728 set_reg_value( hkey, L"ProcessorNameString", namestr );
729 set_reg_value( hkey, L"VendorIdentifier", vendorid );
730 RegSetValueExW( hkey, L"~MHz", 0, REG_DWORD, (BYTE *)&power_info[i].MaxMhz, sizeof(DWORD) );
731 RegCloseKey( hkey );
733 if (sci.ProcessorArchitecture != PROCESSOR_ARCHITECTURE_ARM &&
734 sci.ProcessorArchitecture != PROCESSOR_ARCHITECTURE_ARM64 &&
735 !RegCreateKeyExW( fpu_key, numW, 0, NULL, REG_OPTION_VOLATILE,
736 KEY_ALL_ACCESS, NULL, &hkey, NULL ))
738 set_reg_value( hkey, L"Identifier", id );
739 RegCloseKey( hkey );
743 create_bios_key( system_key );
745 RegCloseKey( fpu_key );
746 RegCloseKey( cpu_key );
747 RegCloseKey( system_key );
748 HeapFree( GetProcessHeap(), 0, power_info );
752 /* create the DynData registry keys */
753 static void create_dynamic_registry_keys(void)
755 HKEY key;
757 if (!RegCreateKeyExW( HKEY_DYN_DATA, L"PerfStats\\StatData", 0, NULL, 0, KEY_WRITE, NULL, &key, NULL ))
758 RegCloseKey( key );
759 if (!RegCreateKeyExW( HKEY_DYN_DATA, L"Config Manager\\Enum", 0, NULL, 0, KEY_WRITE, NULL, &key, NULL ))
760 RegCloseKey( key );
763 /* create the platform-specific environment registry keys */
764 static void create_environment_registry_keys( void )
766 HKEY env_key;
767 SYSTEM_CPU_INFORMATION sci;
768 WCHAR buffer[60], vendorid[13];
769 const WCHAR *arch, *parch;
771 if (RegCreateKeyW( HKEY_LOCAL_MACHINE, L"System\\CurrentControlSet\\Control\\Session Manager\\Environment", &env_key )) return;
773 get_vendorid( vendorid );
774 NtQuerySystemInformation( SystemCpuInformation, &sci, sizeof(sci), NULL );
776 swprintf( buffer, ARRAY_SIZE(buffer), L"%u", NtCurrentTeb()->Peb->NumberOfProcessors );
777 set_reg_value( env_key, L"NUMBER_OF_PROCESSORS", buffer );
779 switch (sci.ProcessorArchitecture)
781 case PROCESSOR_ARCHITECTURE_AMD64:
782 arch = L"AMD64";
783 parch = !wcscmp(vendorid, L"AuthenticAMD") ? L"AMD64" : L"Intel64";
784 break;
786 case PROCESSOR_ARCHITECTURE_INTEL:
787 default:
788 arch = parch = L"x86";
789 break;
791 set_reg_value( env_key, L"PROCESSOR_ARCHITECTURE", arch );
793 switch (sci.ProcessorArchitecture)
795 case PROCESSOR_ARCHITECTURE_ARM:
796 case PROCESSOR_ARCHITECTURE_ARM64:
797 swprintf( buffer, ARRAY_SIZE(buffer), L"ARM Family %u Model %u Revision %u",
798 sci.ProcessorLevel, HIBYTE(sci.ProcessorRevision), LOBYTE(sci.ProcessorRevision) );
799 break;
801 case PROCESSOR_ARCHITECTURE_AMD64:
802 case PROCESSOR_ARCHITECTURE_INTEL:
803 default:
804 get_identifier( buffer, ARRAY_SIZE(buffer), parch );
805 lstrcatW( buffer, L", " );
806 lstrcatW( buffer, vendorid );
807 break;
809 set_reg_value( env_key, L"PROCESSOR_IDENTIFIER", buffer );
811 swprintf( buffer, ARRAY_SIZE(buffer), L"%u", sci.ProcessorLevel );
812 set_reg_value( env_key, L"PROCESSOR_LEVEL", buffer );
814 swprintf( buffer, ARRAY_SIZE(buffer), L"%04x", sci.ProcessorRevision );
815 set_reg_value( env_key, L"PROCESSOR_REVISION", buffer );
817 RegCloseKey( env_key );
820 /* create the ComputerName registry keys */
821 static void create_computer_name_keys(void)
823 struct addrinfo hints = {0}, *res;
824 char *dot, buffer[256], *name = buffer;
825 HKEY key, subkey;
827 if (gethostname( buffer, sizeof(buffer) )) return;
828 hints.ai_flags = AI_CANONNAME;
829 if (!getaddrinfo( buffer, NULL, &hints, &res )) name = res->ai_canonname;
830 dot = strchr( name, '.' );
831 if (dot) *dot++ = 0;
832 else dot = name + strlen(name);
833 SetComputerNameExA( ComputerNamePhysicalDnsDomain, dot );
834 SetComputerNameExA( ComputerNamePhysicalDnsHostname, name );
835 if (name != buffer) freeaddrinfo( res );
837 if (RegOpenKeyW( HKEY_LOCAL_MACHINE, L"System\\CurrentControlSet\\Control\\ComputerName", &key ))
838 return;
840 if (!RegOpenKeyW( key, L"ComputerName", &subkey ))
842 DWORD type, size = sizeof(buffer);
844 if (RegQueryValueExW( subkey, L"ComputerName", NULL, &type, (BYTE *)buffer, &size )) size = 0;
845 RegCloseKey( subkey );
846 if (size && !RegCreateKeyExW( key, L"ActiveComputerName", 0, NULL, REG_OPTION_VOLATILE,
847 KEY_ALL_ACCESS, NULL, &subkey, NULL ))
849 RegSetValueExW( subkey, L"ComputerName", 0, type, (const BYTE *)buffer, size );
850 RegCloseKey( subkey );
853 RegCloseKey( key );
856 static void create_volatile_environment_registry_key(void)
858 WCHAR path[MAX_PATH];
859 WCHAR computername[MAX_COMPUTERNAME_LENGTH + 1 + 2];
860 DWORD size;
861 HKEY hkey;
862 HRESULT hr;
864 if (RegCreateKeyExW( HKEY_CURRENT_USER, L"Volatile Environment", 0, NULL, REG_OPTION_VOLATILE,
865 KEY_ALL_ACCESS, NULL, &hkey, NULL ))
866 return;
868 hr = SHGetFolderPathW( NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, path );
869 if (SUCCEEDED(hr)) set_reg_value( hkey, L"APPDATA", path );
871 set_reg_value( hkey, L"CLIENTNAME", L"Console" );
873 /* Write the profile path's drive letter and directory components into
874 * HOMEDRIVE and HOMEPATH respectively. */
875 hr = SHGetFolderPathW( NULL, CSIDL_PROFILE | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, path );
876 if (SUCCEEDED(hr))
878 set_reg_value( hkey, L"USERPROFILE", path );
879 set_reg_value( hkey, L"HOMEPATH", path + 2 );
880 path[2] = '\0';
881 set_reg_value( hkey, L"HOMEDRIVE", path );
884 size = ARRAY_SIZE(path);
885 if (GetUserNameW( path, &size )) set_reg_value( hkey, L"USERNAME", path );
887 set_reg_value( hkey, L"HOMESHARE", L"" );
889 hr = SHGetFolderPathW( NULL, CSIDL_LOCAL_APPDATA | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, path );
890 if (SUCCEEDED(hr))
891 set_reg_value( hkey, L"LOCALAPPDATA", path );
893 size = ARRAY_SIZE(computername) - 2;
894 if (GetComputerNameW(&computername[2], &size))
896 set_reg_value( hkey, L"USERDOMAIN", &computername[2] );
897 computername[0] = computername[1] = '\\';
898 set_reg_value( hkey, L"LOGONSERVER", computername );
901 set_reg_value( hkey, L"SESSIONNAME", L"Console" );
902 RegCloseKey( hkey );
905 /* Performs the rename operations dictated in %SystemRoot%\Wininit.ini.
906 * Returns FALSE if there was an error, or otherwise if all is ok.
908 static BOOL wininit(void)
910 WCHAR initial_buffer[1024];
911 WCHAR *str, *buffer = initial_buffer;
912 DWORD size = ARRAY_SIZE(initial_buffer);
913 DWORD res;
915 for (;;)
917 if (!(res = GetPrivateProfileSectionW( L"rename", buffer, size, L"wininit.ini" ))) return TRUE;
918 if (res < size - 2) break;
919 if (buffer != initial_buffer) HeapFree( GetProcessHeap(), 0, buffer );
920 size *= 2;
921 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return FALSE;
924 for (str = buffer; *str; str += lstrlenW(str) + 1)
926 WCHAR *value;
928 if (*str == ';') continue; /* comment */
929 if (!(value = wcschr( str, '=' ))) continue;
931 /* split the line into key and value */
932 *value++ = 0;
934 if (!lstrcmpiW( L"NUL", str ))
936 WINE_TRACE("Deleting file %s\n", wine_dbgstr_w(value) );
937 if( !DeleteFileW( value ) )
938 WINE_WARN("Error deleting file %s\n", wine_dbgstr_w(value) );
940 else
942 WINE_TRACE("Renaming file %s to %s\n", wine_dbgstr_w(value), wine_dbgstr_w(str) );
944 if( !MoveFileExW(value, str, MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) )
945 WINE_WARN("Error renaming %s to %s\n", wine_dbgstr_w(value), wine_dbgstr_w(str) );
947 str = value;
950 if (buffer != initial_buffer) HeapFree( GetProcessHeap(), 0, buffer );
952 if( !MoveFileExW( L"wininit.ini", L"wininit.bak", MOVEFILE_REPLACE_EXISTING) )
954 WINE_ERR("Couldn't rename wininit.ini, error %d\n", GetLastError() );
956 return FALSE;
959 return TRUE;
962 static void pendingRename(void)
964 WCHAR *buffer=NULL;
965 const WCHAR *src=NULL, *dst=NULL;
966 DWORD dataLength=0;
967 HKEY hSession;
969 if (RegOpenKeyExW( HKEY_LOCAL_MACHINE, L"System\\CurrentControlSet\\Control\\Session Manager",
970 0, KEY_ALL_ACCESS, &hSession ))
971 return;
973 if (RegQueryValueExW( hSession, L"PendingFileRenameOperations", NULL, NULL, NULL, &dataLength ))
974 goto end;
975 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, dataLength ))) goto end;
977 if (RegQueryValueExW( hSession, L"PendingFileRenameOperations", NULL, NULL,
978 (LPBYTE)buffer, &dataLength ))
979 goto end;
981 /* Make sure that the data is long enough and ends with two NULLs. This
982 * simplifies the code later on.
984 if( dataLength<2*sizeof(buffer[0]) ||
985 buffer[dataLength/sizeof(buffer[0])-1]!='\0' ||
986 buffer[dataLength/sizeof(buffer[0])-2]!='\0' )
987 goto end;
989 for( src=buffer; (src-buffer)*sizeof(src[0])<dataLength && *src!='\0';
990 src=dst+lstrlenW(dst)+1 )
992 DWORD dwFlags=0;
994 dst=src+lstrlenW(src)+1;
996 /* We need to skip the \??\ header */
997 if( src[0]=='\\' && src[1]=='?' && src[2]=='?' && src[3]=='\\' )
998 src+=4;
1000 if( dst[0]=='!' )
1002 dwFlags|=MOVEFILE_REPLACE_EXISTING;
1003 dst++;
1006 if( dst[0]=='\\' && dst[1]=='?' && dst[2]=='?' && dst[3]=='\\' )
1007 dst+=4;
1009 if( *dst!='\0' )
1011 /* Rename the file */
1012 MoveFileExW( src, dst, dwFlags );
1013 } else
1015 /* Delete the file or directory */
1016 if (!RemoveDirectoryW( src ) && GetLastError() == ERROR_DIRECTORY) DeleteFileW( src );
1020 RegDeleteValueW(hSession, L"PendingFileRenameOperations");
1022 end:
1023 HeapFree(GetProcessHeap(), 0, buffer);
1024 RegCloseKey( hSession );
1027 #define INVALID_RUNCMD_RETURN -1
1029 * This function runs the specified command in the specified dir.
1030 * [in,out] cmdline - the command line to run. The function may change the passed buffer.
1031 * [in] dir - the dir to run the command in. If it is NULL, then the current dir is used.
1032 * [in] wait - whether to wait for the run program to finish before returning.
1033 * [in] minimized - Whether to ask the program to run minimized.
1035 * Returns:
1036 * If running the process failed, returns INVALID_RUNCMD_RETURN. Use GetLastError to get the error code.
1037 * If wait is FALSE - returns 0 if successful.
1038 * If wait is TRUE - returns the program's return value.
1040 static DWORD runCmd(LPWSTR cmdline, LPCWSTR dir, BOOL wait, BOOL minimized)
1042 STARTUPINFOW si;
1043 PROCESS_INFORMATION info;
1044 DWORD exit_code=0;
1046 memset(&si, 0, sizeof(si));
1047 si.cb=sizeof(si);
1048 if( minimized )
1050 si.dwFlags=STARTF_USESHOWWINDOW;
1051 si.wShowWindow=SW_MINIMIZE;
1053 memset(&info, 0, sizeof(info));
1055 if( !CreateProcessW(NULL, cmdline, NULL, NULL, FALSE, 0, NULL, dir, &si, &info) )
1057 WINE_WARN("Failed to run command %s (%d)\n", wine_dbgstr_w(cmdline), GetLastError() );
1058 return INVALID_RUNCMD_RETURN;
1061 WINE_TRACE("Successfully ran command %s - Created process handle %p\n",
1062 wine_dbgstr_w(cmdline), info.hProcess );
1064 if(wait)
1065 { /* wait for the process to exit */
1066 WaitForSingleObject(info.hProcess, INFINITE);
1067 GetExitCodeProcess(info.hProcess, &exit_code);
1070 CloseHandle( info.hThread );
1071 CloseHandle( info.hProcess );
1073 return exit_code;
1076 static void process_run_key( HKEY key, const WCHAR *keyname, BOOL delete, BOOL synchronous )
1078 HKEY runkey;
1079 LONG res;
1080 DWORD disp, i, max_cmdline = 0, max_value = 0;
1081 WCHAR *cmdline = NULL, *value = NULL;
1083 if (RegCreateKeyExW( key, keyname, 0, NULL, 0, delete ? KEY_ALL_ACCESS : KEY_READ, NULL, &runkey, &disp ))
1084 return;
1086 if (disp == REG_CREATED_NEW_KEY)
1087 goto end;
1089 if (RegQueryInfoKeyW( runkey, NULL, NULL, NULL, NULL, NULL, NULL, &i, &max_value, &max_cmdline, NULL, NULL ))
1090 goto end;
1092 if (!i)
1094 WINE_TRACE( "No commands to execute.\n" );
1095 goto end;
1097 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, max_cmdline )))
1099 WINE_ERR( "Couldn't allocate memory for the commands to be executed.\n" );
1100 goto end;
1102 if (!(value = HeapAlloc( GetProcessHeap(), 0, ++max_value * sizeof(*value) )))
1104 WINE_ERR( "Couldn't allocate memory for the value names.\n" );
1105 goto end;
1108 while (i)
1110 DWORD len = max_value, len_data = max_cmdline, type;
1112 if ((res = RegEnumValueW( runkey, --i, value, &len, 0, &type, (BYTE *)cmdline, &len_data )))
1114 WINE_ERR( "Couldn't read value %u (%d).\n", i, res );
1115 continue;
1117 if (delete && (res = RegDeleteValueW( runkey, value )))
1119 WINE_ERR( "Couldn't delete value %u (%d). Running command anyways.\n", i, res );
1121 if (type != REG_SZ)
1123 WINE_ERR( "Incorrect type of value %u (%u).\n", i, type );
1124 continue;
1126 if (runCmd( cmdline, NULL, synchronous, FALSE ) == INVALID_RUNCMD_RETURN)
1128 WINE_ERR( "Error running cmd %s (%u).\n", wine_dbgstr_w(cmdline), GetLastError() );
1130 WINE_TRACE( "Done processing cmd %u.\n", i );
1133 end:
1134 HeapFree( GetProcessHeap(), 0, value );
1135 HeapFree( GetProcessHeap(), 0, cmdline );
1136 RegCloseKey( runkey );
1137 WINE_TRACE( "Done.\n" );
1141 * Process a "Run" type registry key.
1142 * hkRoot is the HKEY from which "Software\Microsoft\Windows\CurrentVersion" is
1143 * opened.
1144 * szKeyName is the key holding the actual entries.
1145 * bDelete tells whether we should delete each value right before executing it.
1146 * bSynchronous tells whether we should wait for the prog to complete before
1147 * going on to the next prog.
1149 static void ProcessRunKeys( HKEY root, const WCHAR *keyname, BOOL delete, BOOL synchronous )
1151 HKEY key;
1153 if (root == HKEY_LOCAL_MACHINE)
1155 WINE_TRACE( "Processing %s entries under HKLM.\n", wine_dbgstr_w(keyname) );
1156 if (!RegCreateKeyExW( root, L"Software\\Microsoft\\Windows\\CurrentVersion",
1157 0, NULL, 0, KEY_READ, NULL, &key, NULL ))
1159 process_run_key( key, keyname, delete, synchronous );
1160 RegCloseKey( key );
1162 if (is_64bit && !RegCreateKeyExW( root, L"Software\\Microsoft\\Windows\\CurrentVersion",
1163 0, NULL, 0, KEY_READ|KEY_WOW64_32KEY, NULL, &key, NULL ))
1165 process_run_key( key, keyname, delete, synchronous );
1166 RegCloseKey( key );
1169 else
1171 WINE_TRACE( "Processing %s entries under HKCU.\n", wine_dbgstr_w(keyname) );
1172 if (!RegCreateKeyExW( root, L"Software\\Microsoft\\Windows\\CurrentVersion",
1173 0, NULL, 0, KEY_READ, NULL, &key, NULL ))
1175 process_run_key( key, keyname, delete, synchronous );
1176 RegCloseKey( key );
1182 * WFP is Windows File Protection, in NT5 and Windows 2000 it maintains a cache
1183 * of known good dlls and scans through and replaces corrupted DLLs with these
1184 * known good versions. The only programs that should install into this dll
1185 * cache are Windows Updates and IE (which is treated like a Windows Update)
1187 * Implementing this allows installing ie in win2k mode to actually install the
1188 * system dlls that we expect and need
1190 static int ProcessWindowsFileProtection(void)
1192 WIN32_FIND_DATAW finddata;
1193 HANDLE find_handle;
1194 BOOL find_rc;
1195 DWORD rc;
1196 HKEY hkey;
1197 LPWSTR dllcache = NULL;
1199 if (!RegOpenKeyW( HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", &hkey ))
1201 DWORD sz = 0;
1202 if (!RegQueryValueExW( hkey, L"SFCDllCacheDir", 0, NULL, NULL, &sz))
1204 sz += sizeof(WCHAR);
1205 dllcache = HeapAlloc(GetProcessHeap(),0,sz + sizeof(L"\\*"));
1206 RegQueryValueExW( hkey, L"SFCDllCacheDir", 0, NULL, (LPBYTE)dllcache, &sz);
1207 lstrcatW( dllcache, L"\\*" );
1210 RegCloseKey(hkey);
1212 if (!dllcache)
1214 DWORD sz = GetSystemDirectoryW( NULL, 0 );
1215 dllcache = HeapAlloc( GetProcessHeap(), 0, sz * sizeof(WCHAR) + sizeof(L"\\dllcache\\*"));
1216 GetSystemDirectoryW( dllcache, sz );
1217 lstrcatW( dllcache, L"\\dllcache\\*" );
1220 find_handle = FindFirstFileW(dllcache,&finddata);
1221 dllcache[ lstrlenW(dllcache) - 2] = 0; /* strip off wildcard */
1222 find_rc = find_handle != INVALID_HANDLE_VALUE;
1223 while (find_rc)
1225 WCHAR targetpath[MAX_PATH];
1226 WCHAR currentpath[MAX_PATH];
1227 UINT sz;
1228 UINT sz2;
1229 WCHAR tempfile[MAX_PATH];
1231 if (wcscmp(finddata.cFileName,L".") == 0 || wcscmp(finddata.cFileName,L"..") == 0)
1233 find_rc = FindNextFileW(find_handle,&finddata);
1234 continue;
1237 sz = MAX_PATH;
1238 sz2 = MAX_PATH;
1239 VerFindFileW(VFFF_ISSHAREDFILE, finddata.cFileName, windowsdir,
1240 windowsdir, currentpath, &sz, targetpath, &sz2);
1241 sz = MAX_PATH;
1242 rc = VerInstallFileW(0, finddata.cFileName, finddata.cFileName,
1243 dllcache, targetpath, currentpath, tempfile, &sz);
1244 if (rc != ERROR_SUCCESS)
1246 WINE_WARN("WFP: %s error 0x%x\n",wine_dbgstr_w(finddata.cFileName),rc);
1247 DeleteFileW(tempfile);
1250 /* now delete the source file so that we don't try to install it over and over again */
1251 lstrcpynW( targetpath, dllcache, MAX_PATH - 1 );
1252 sz = lstrlenW( targetpath );
1253 targetpath[sz++] = '\\';
1254 lstrcpynW( targetpath + sz, finddata.cFileName, MAX_PATH - sz );
1255 if (!DeleteFileW( targetpath ))
1256 WINE_WARN( "failed to delete %s: error %u\n", wine_dbgstr_w(targetpath), GetLastError() );
1258 find_rc = FindNextFileW(find_handle,&finddata);
1260 FindClose(find_handle);
1261 HeapFree(GetProcessHeap(),0,dllcache);
1262 return 1;
1265 static BOOL start_services_process(void)
1267 static const WCHAR svcctl_started_event[] = SVCCTL_STARTED_EVENT;
1268 PROCESS_INFORMATION pi;
1269 STARTUPINFOW si = { sizeof(si) };
1270 HANDLE wait_handles[2];
1272 if (!CreateProcessW(L"C:\\windows\\system32\\services.exe", NULL,
1273 NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &si, &pi))
1275 WINE_ERR("Couldn't start services.exe: error %u\n", GetLastError());
1276 return FALSE;
1278 CloseHandle(pi.hThread);
1280 wait_handles[0] = CreateEventW(NULL, TRUE, FALSE, svcctl_started_event);
1281 wait_handles[1] = pi.hProcess;
1283 /* wait for the event to become available or the process to exit */
1284 if ((WaitForMultipleObjects(2, wait_handles, FALSE, INFINITE)) == WAIT_OBJECT_0 + 1)
1286 DWORD exit_code;
1287 GetExitCodeProcess(pi.hProcess, &exit_code);
1288 WINE_ERR("Unexpected termination of services.exe - exit code %d\n", exit_code);
1289 CloseHandle(pi.hProcess);
1290 CloseHandle(wait_handles[0]);
1291 return FALSE;
1294 CloseHandle(pi.hProcess);
1295 CloseHandle(wait_handles[0]);
1296 return TRUE;
1299 static INT_PTR CALLBACK wait_dlgproc( HWND hwnd, UINT msg, WPARAM wp, LPARAM lp )
1301 switch (msg)
1303 case WM_INITDIALOG:
1305 DWORD len;
1306 WCHAR *buffer, text[1024];
1307 const WCHAR *name = (WCHAR *)lp;
1308 HICON icon = LoadImageW( 0, (LPCWSTR)IDI_WINLOGO, IMAGE_ICON, 48, 48, LR_SHARED );
1309 SendDlgItemMessageW( hwnd, IDC_WAITICON, STM_SETICON, (WPARAM)icon, 0 );
1310 SendDlgItemMessageW( hwnd, IDC_WAITTEXT, WM_GETTEXT, 1024, (LPARAM)text );
1311 len = lstrlenW(text) + lstrlenW(name) + 1;
1312 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
1313 swprintf( buffer, len, text, name );
1314 SendDlgItemMessageW( hwnd, IDC_WAITTEXT, WM_SETTEXT, 0, (LPARAM)buffer );
1315 HeapFree( GetProcessHeap(), 0, buffer );
1317 break;
1319 return 0;
1322 static HWND show_wait_window(void)
1324 HWND hwnd = CreateDialogParamW( GetModuleHandleW(0), MAKEINTRESOURCEW(IDD_WAITDLG), 0,
1325 wait_dlgproc, (LPARAM)prettyprint_configdir() );
1326 ShowWindow( hwnd, SW_SHOWNORMAL );
1327 return hwnd;
1330 static HANDLE start_rundll32( const WCHAR *inf_path, WORD machine )
1332 WCHAR app[MAX_PATH + ARRAY_SIZE(L"\\rundll32.exe" )];
1333 STARTUPINFOW si;
1334 PROCESS_INFORMATION pi;
1335 WCHAR *buffer;
1336 DWORD len;
1338 memset( &si, 0, sizeof(si) );
1339 si.cb = sizeof(si);
1341 if (!GetSystemWow64Directory2W( app, MAX_PATH, machine )) return 0;
1342 lstrcatW( app, L"\\rundll32.exe" );
1343 TRACE( "machine %x starting %s\n", machine, debugstr_w(app) );
1345 len = lstrlenW(app) + ARRAY_SIZE(L" setupapi,InstallHinfSection DefaultInstall 128 ") + lstrlenW(inf_path);
1347 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) ))) return 0;
1349 lstrcpyW( buffer, app );
1350 lstrcatW( buffer, L" setupapi,InstallHinfSection" );
1351 lstrcatW( buffer, machine != IMAGE_FILE_MACHINE_TARGET_HOST ? L" Wow64Install" : L" DefaultInstall" );
1352 lstrcatW( buffer, L" 128 " );
1353 lstrcatW( buffer, inf_path );
1355 if (CreateProcessW( app, buffer, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ))
1356 CloseHandle( pi.hThread );
1357 else
1358 pi.hProcess = 0;
1360 HeapFree( GetProcessHeap(), 0, buffer );
1361 return pi.hProcess;
1364 static void install_root_pnp_devices(void)
1366 static const struct
1368 const char *name;
1369 const char *hardware_id;
1370 const char *infpath;
1372 root_devices[] =
1374 {"root\\wine\\winebus", "root\\winebus\0", "C:\\windows\\inf\\winebus.inf"},
1375 {"root\\wine\\wineusb", "root\\wineusb\0", "C:\\windows\\inf\\wineusb.inf"},
1377 SP_DEVINFO_DATA device = {sizeof(device)};
1378 unsigned int i;
1379 HDEVINFO set;
1381 if ((set = SetupDiCreateDeviceInfoList( NULL, NULL )) == INVALID_HANDLE_VALUE)
1383 WINE_ERR("Failed to create device info list, error %#x.\n", GetLastError());
1384 return;
1387 for (i = 0; i < ARRAY_SIZE(root_devices); ++i)
1389 if (!SetupDiCreateDeviceInfoA( set, root_devices[i].name, &GUID_NULL, NULL, NULL, 0, &device))
1391 if (GetLastError() != ERROR_DEVINST_ALREADY_EXISTS)
1392 WINE_ERR("Failed to create device %s, error %#x.\n", debugstr_a(root_devices[i].name), GetLastError());
1393 continue;
1396 if (!SetupDiSetDeviceRegistryPropertyA(set, &device, SPDRP_HARDWAREID,
1397 (const BYTE *)root_devices[i].hardware_id, (strlen(root_devices[i].hardware_id) + 2) * sizeof(WCHAR)))
1399 WINE_ERR("Failed to set hardware id for %s, error %#x.\n", debugstr_a(root_devices[i].name), GetLastError());
1400 continue;
1403 if (!SetupDiCallClassInstaller(DIF_REGISTERDEVICE, set, &device))
1405 WINE_ERR("Failed to register device %s, error %#x.\n", debugstr_a(root_devices[i].name), GetLastError());
1406 continue;
1409 if (!UpdateDriverForPlugAndPlayDevicesA(NULL, root_devices[i].hardware_id, root_devices[i].infpath, 0, NULL))
1410 WINE_ERR("Failed to install drivers for %s, error %#x.\n", debugstr_a(root_devices[i].name), GetLastError());
1413 SetupDiDestroyDeviceInfoList(set);
1416 static void update_user_profile(void)
1418 char token_buf[sizeof(TOKEN_USER) + sizeof(SID) + sizeof(DWORD) * SID_MAX_SUB_AUTHORITIES];
1419 HANDLE token;
1420 WCHAR profile[MAX_PATH], *sid;
1421 DWORD size;
1422 HKEY hkey, profile_hkey;
1424 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token))
1425 return;
1427 size = sizeof(token_buf);
1428 GetTokenInformation(token, TokenUser, token_buf, size, &size);
1429 CloseHandle(token);
1431 ConvertSidToStringSidW(((TOKEN_USER *)token_buf)->User.Sid, &sid);
1433 if (!RegCreateKeyExW(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList",
1434 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hkey, NULL))
1436 if (!RegCreateKeyExW(hkey, sid, 0, NULL, 0,
1437 KEY_ALL_ACCESS, NULL, &profile_hkey, NULL))
1439 DWORD flags = 0;
1440 if (SHGetSpecialFolderPathW(NULL, profile, CSIDL_PROFILE, TRUE))
1441 set_reg_value(profile_hkey, L"ProfileImagePath", profile);
1442 RegSetValueExW( profile_hkey, L"Flags", 0, REG_DWORD, (const BYTE *)&flags, sizeof(flags) );
1443 RegCloseKey(profile_hkey);
1446 RegCloseKey(hkey);
1449 LocalFree(sid);
1452 /* execute rundll32 on the wine.inf file if necessary */
1453 static void update_wineprefix( BOOL force )
1455 const WCHAR *config_dir = _wgetenv( L"WINECONFIGDIR" );
1456 WCHAR *inf_path = get_wine_inf_path();
1457 int fd;
1458 struct stat st;
1460 if (!inf_path)
1462 WINE_MESSAGE( "wine: failed to update %s, wine.inf not found\n", debugstr_w( config_dir ));
1463 return;
1465 if ((fd = _wopen( inf_path, O_RDONLY )) == -1)
1467 WINE_MESSAGE( "wine: failed to update %s with %s: %s\n",
1468 debugstr_w(config_dir), debugstr_w(inf_path), strerror(errno) );
1469 goto done;
1471 fstat( fd, &st );
1472 close( fd );
1474 if (update_timestamp( config_dir, st.st_mtime ) || force)
1476 ULONG machines[8];
1477 HANDLE process = 0;
1478 DWORD count = 0;
1480 if (NtQuerySystemInformationEx( SystemSupportedProcessorArchitectures, &process, sizeof(process),
1481 machines, sizeof(machines), NULL )) machines[0] = 0;
1483 if ((process = start_rundll32( inf_path, IMAGE_FILE_MACHINE_TARGET_HOST )))
1485 HWND hwnd = show_wait_window();
1486 for (;;)
1488 MSG msg;
1489 DWORD res = MsgWaitForMultipleObjects( 1, &process, FALSE, INFINITE, QS_ALLINPUT );
1490 if (res == WAIT_OBJECT_0)
1492 CloseHandle( process );
1493 if (HIWORD(machines[count]) & 4 /* native machine */) count++;
1494 if (!machines[count]) break;
1495 if (!(process = start_rundll32( inf_path, LOWORD(machines[count++]) ))) break;
1497 else while (PeekMessageW( &msg, 0, 0, 0, PM_REMOVE )) DispatchMessageW( &msg );
1499 DestroyWindow( hwnd );
1501 install_root_pnp_devices();
1502 update_user_profile();
1504 WINE_MESSAGE( "wine: configuration in %s has been updated.\n", debugstr_w(prettyprint_configdir()) );
1507 done:
1508 HeapFree( GetProcessHeap(), 0, inf_path );
1511 /* Process items in the StartUp group of the user's Programs under the Start Menu. Some installers put
1512 * shell links here to restart themselves after boot. */
1513 static BOOL ProcessStartupItems(void)
1515 BOOL ret = FALSE;
1516 HRESULT hr;
1517 IShellFolder *psfDesktop = NULL, *psfStartup = NULL;
1518 LPITEMIDLIST pidlStartup = NULL, pidlItem;
1519 ULONG NumPIDLs;
1520 IEnumIDList *iEnumList = NULL;
1521 STRRET strret;
1522 WCHAR wszCommand[MAX_PATH];
1524 WINE_TRACE("Processing items in the StartUp folder.\n");
1526 hr = SHGetDesktopFolder(&psfDesktop);
1527 if (FAILED(hr))
1529 WINE_ERR("Couldn't get desktop folder.\n");
1530 goto done;
1533 hr = SHGetSpecialFolderLocation(NULL, CSIDL_STARTUP, &pidlStartup);
1534 if (FAILED(hr))
1536 WINE_TRACE("Couldn't get StartUp folder location.\n");
1537 goto done;
1540 hr = IShellFolder_BindToObject(psfDesktop, pidlStartup, NULL, &IID_IShellFolder, (LPVOID*)&psfStartup);
1541 if (FAILED(hr))
1543 WINE_TRACE("Couldn't bind IShellFolder to StartUp folder.\n");
1544 goto done;
1547 hr = IShellFolder_EnumObjects(psfStartup, NULL, SHCONTF_NONFOLDERS | SHCONTF_INCLUDEHIDDEN, &iEnumList);
1548 if (FAILED(hr))
1550 WINE_TRACE("Unable to enumerate StartUp objects.\n");
1551 goto done;
1554 while (IEnumIDList_Next(iEnumList, 1, &pidlItem, &NumPIDLs) == S_OK &&
1555 (NumPIDLs) == 1)
1557 hr = IShellFolder_GetDisplayNameOf(psfStartup, pidlItem, SHGDN_FORPARSING, &strret);
1558 if (FAILED(hr))
1559 WINE_TRACE("Unable to get display name of enumeration item.\n");
1560 else
1562 hr = StrRetToBufW(&strret, pidlItem, wszCommand, MAX_PATH);
1563 if (FAILED(hr))
1564 WINE_TRACE("Unable to parse display name.\n");
1565 else
1567 HINSTANCE hinst;
1569 hinst = ShellExecuteW(NULL, NULL, wszCommand, NULL, NULL, SW_SHOWNORMAL);
1570 if (PtrToUlong(hinst) <= 32)
1571 WINE_WARN("Error %p executing command %s.\n", hinst, wine_dbgstr_w(wszCommand));
1575 ILFree(pidlItem);
1578 /* Return success */
1579 ret = TRUE;
1581 done:
1582 if (iEnumList) IEnumIDList_Release(iEnumList);
1583 if (psfStartup) IShellFolder_Release(psfStartup);
1584 if (pidlStartup) ILFree(pidlStartup);
1586 return ret;
1589 static void usage( int status )
1591 WINE_MESSAGE( "Usage: wineboot [options]\n" );
1592 WINE_MESSAGE( "Options;\n" );
1593 WINE_MESSAGE( " -h,--help Display this help message\n" );
1594 WINE_MESSAGE( " -e,--end-session End the current session cleanly\n" );
1595 WINE_MESSAGE( " -f,--force Force exit for processes that don't exit cleanly\n" );
1596 WINE_MESSAGE( " -i,--init Perform initialization for first Wine instance\n" );
1597 WINE_MESSAGE( " -k,--kill Kill running processes without any cleanup\n" );
1598 WINE_MESSAGE( " -r,--restart Restart only, don't do normal startup operations\n" );
1599 WINE_MESSAGE( " -s,--shutdown Shutdown only, don't reboot\n" );
1600 WINE_MESSAGE( " -u,--update Update the wineprefix directory\n" );
1601 exit( status );
1604 int __cdecl main( int argc, char *argv[] )
1606 /* First, set the current directory to SystemRoot */
1607 int i, j;
1608 BOOL end_session, force, init, kill, restart, shutdown, update;
1609 HANDLE event;
1610 OBJECT_ATTRIBUTES attr;
1611 UNICODE_STRING nameW;
1612 BOOL is_wow64;
1614 end_session = force = init = kill = restart = shutdown = update = FALSE;
1615 GetWindowsDirectoryW( windowsdir, MAX_PATH );
1616 if( !SetCurrentDirectoryW( windowsdir ) )
1617 WINE_ERR("Cannot set the dir to %s (%d)\n", wine_dbgstr_w(windowsdir), GetLastError() );
1619 if (IsWow64Process( GetCurrentProcess(), &is_wow64 ) && is_wow64)
1621 STARTUPINFOW si;
1622 PROCESS_INFORMATION pi;
1623 WCHAR filename[MAX_PATH];
1624 void *redir;
1625 DWORD exit_code;
1627 memset( &si, 0, sizeof(si) );
1628 si.cb = sizeof(si);
1629 GetSystemDirectoryW( filename, MAX_PATH );
1630 wcscat( filename, L"\\wineboot.exe" );
1632 Wow64DisableWow64FsRedirection( &redir );
1633 if (CreateProcessW( filename, GetCommandLineW(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ))
1635 WINE_TRACE( "restarting %s\n", wine_dbgstr_w(filename) );
1636 WaitForSingleObject( pi.hProcess, INFINITE );
1637 GetExitCodeProcess( pi.hProcess, &exit_code );
1638 ExitProcess( exit_code );
1640 else WINE_ERR( "failed to restart 64-bit %s, err %d\n", wine_dbgstr_w(filename), GetLastError() );
1641 Wow64RevertWow64FsRedirection( redir );
1644 for (i = 1; i < argc; i++)
1646 if (argv[i][0] != '-') continue;
1647 if (argv[i][1] == '-')
1649 if (!strcmp( argv[i], "--help" )) usage( 0 );
1650 else if (!strcmp( argv[i], "--end-session" )) end_session = TRUE;
1651 else if (!strcmp( argv[i], "--force" )) force = TRUE;
1652 else if (!strcmp( argv[i], "--init" )) init = TRUE;
1653 else if (!strcmp( argv[i], "--kill" )) kill = TRUE;
1654 else if (!strcmp( argv[i], "--restart" )) restart = TRUE;
1655 else if (!strcmp( argv[i], "--shutdown" )) shutdown = TRUE;
1656 else if (!strcmp( argv[i], "--update" )) update = TRUE;
1657 else usage( 1 );
1658 continue;
1660 for (j = 1; argv[i][j]; j++)
1662 switch (argv[i][j])
1664 case 'e': end_session = TRUE; break;
1665 case 'f': force = TRUE; break;
1666 case 'i': init = TRUE; break;
1667 case 'k': kill = TRUE; break;
1668 case 'r': restart = TRUE; break;
1669 case 's': shutdown = TRUE; break;
1670 case 'u': update = TRUE; break;
1671 case 'h': usage(0); break;
1672 default: usage(1); break;
1677 if (end_session)
1679 if (kill)
1681 if (!shutdown_all_desktops( force )) return 1;
1683 else if (!shutdown_close_windows( force )) return 1;
1686 if (kill) kill_processes( shutdown );
1688 if (shutdown) return 0;
1690 /* create event to be inherited by services.exe */
1691 InitializeObjectAttributes( &attr, &nameW, OBJ_OPENIF | OBJ_INHERIT, 0, NULL );
1692 RtlInitUnicodeString( &nameW, L"\\KernelObjects\\__wineboot_event" );
1693 NtCreateEvent( &event, EVENT_ALL_ACCESS, &attr, NotificationEvent, 0 );
1695 ResetEvent( event ); /* in case this is a restart */
1697 create_user_shared_data();
1698 create_hardware_registry_keys();
1699 create_dynamic_registry_keys();
1700 create_environment_registry_keys();
1701 create_computer_name_keys();
1702 wininit();
1703 pendingRename();
1705 ProcessWindowsFileProtection();
1706 ProcessRunKeys( HKEY_LOCAL_MACHINE, L"RunServicesOnce", TRUE, FALSE );
1708 if (init || (kill && !restart))
1710 ProcessRunKeys( HKEY_LOCAL_MACHINE, L"RunServices", FALSE, FALSE );
1711 start_services_process();
1713 if (init || update) update_wineprefix( update );
1715 create_volatile_environment_registry_key();
1717 ProcessRunKeys( HKEY_LOCAL_MACHINE, L"RunOnce", TRUE, TRUE );
1719 if (!init && !restart)
1721 ProcessRunKeys( HKEY_LOCAL_MACHINE, L"Run", FALSE, FALSE );
1722 ProcessRunKeys( HKEY_CURRENT_USER, L"Run", FALSE, FALSE );
1723 ProcessStartupItems();
1726 WINE_TRACE("Operation done\n");
1728 SetEvent( event );
1729 return 0;