VirtualBox

source: vbox/trunk/src/VBox/Runtime/r3/win/init-win.cpp@ 96407

Last change on this file since 96407 was 96407, checked in by vboxsync, 22 months ago

scm copyright and license note update

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 39.0 KB
Line 
1/* $Id: init-win.cpp 96407 2022-08-22 17:43:14Z vboxsync $ */
2/** @file
3 * IPRT - Init Ring-3, Windows Specific Code.
4 */
5
6/*
7 * Copyright (C) 2006-2022 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * The contents of this file may alternatively be used under the terms
26 * of the Common Development and Distribution License Version 1.0
27 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
28 * in the VirtualBox distribution, in which case the provisions of the
29 * CDDL are applicable instead of those of the GPL.
30 *
31 * You may elect to license modified versions of this file under the
32 * terms and conditions of either the GPL or the CDDL or both.
33 *
34 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
35 */
36
37
38/*********************************************************************************************************************************
39* Header Files *
40*********************************************************************************************************************************/
41#define LOG_GROUP RTLOGGROUP_DEFAULT
42#include <iprt/nt/nt-and-windows.h>
43#ifndef LOAD_LIBRARY_SEARCH_APPLICATION_DIR
44# define LOAD_LIBRARY_SEARCH_APPLICATION_DIR 0x200
45# define LOAD_LIBRARY_SEARCH_SYSTEM32 0x800
46#endif
47
48#include "internal-r3-win.h"
49#include <iprt/initterm.h>
50#include <iprt/assert.h>
51#include <iprt/err.h>
52#include <iprt/ldr.h>
53#include <iprt/log.h>
54#include <iprt/param.h>
55#include <iprt/process.h>
56#include <iprt/string.h>
57#include <iprt/thread.h>
58#include "../init.h"
59
60
61/*********************************************************************************************************************************
62* Structures and Typedefs *
63*********************************************************************************************************************************/
64typedef VOID (WINAPI *PFNGETCURRENTTHREADSTACKLIMITS)(PULONG_PTR puLow, PULONG_PTR puHigh);
65typedef LPTOP_LEVEL_EXCEPTION_FILTER (WINAPI * PFNSETUNHANDLEDEXCEPTIONFILTER)(LPTOP_LEVEL_EXCEPTION_FILTER);
66
67
68/*********************************************************************************************************************************
69* Global Variables *
70*********************************************************************************************************************************/
71/** Windows DLL loader protection level. */
72DECL_HIDDEN_DATA(RTR3WINLDRPROT) g_enmWinLdrProt = RTR3WINLDRPROT_NONE;
73/** Our simplified windows version. */
74DECL_HIDDEN_DATA(RTWINOSTYPE) g_enmWinVer = kRTWinOSType_UNKNOWN;
75/** Extended windows version information. */
76DECL_HIDDEN_DATA(OSVERSIONINFOEXW) g_WinOsInfoEx;
77
78/** The native kernel32.dll handle. */
79DECL_HIDDEN_DATA(HMODULE) g_hModKernel32 = NULL;
80/** GetSystemWindowsDirectoryW or GetWindowsDirectoryW (NT4). */
81DECL_HIDDEN_DATA(PFNGETWINSYSDIR) g_pfnGetSystemWindowsDirectoryW = NULL;
82/** The GetCurrentThreadStackLimits API. */
83static PFNGETCURRENTTHREADSTACKLIMITS g_pfnGetCurrentThreadStackLimits = NULL;
84/** SetUnhandledExceptionFilter. */
85static PFNSETUNHANDLEDEXCEPTIONFILTER g_pfnSetUnhandledExceptionFilter = NULL;
86/** The previous unhandled exception filter. */
87static LPTOP_LEVEL_EXCEPTION_FILTER g_pfnUnhandledXcptFilter = NULL;
88/** SystemTimeToTzSpecificLocalTime. */
89DECL_HIDDEN_DATA(decltype(SystemTimeToTzSpecificLocalTime) *) g_pfnSystemTimeToTzSpecificLocalTime = NULL;
90/** CreateWaitableTimerEx . */
91DECL_HIDDEN_DATA(PFNCREATEWAITABLETIMEREX) g_pfnCreateWaitableTimerExW = NULL;
92
93/** The native ntdll.dll handle. */
94DECL_HIDDEN_DATA(HMODULE) g_hModNtDll = NULL;
95/** NtQueryFullAttributesFile */
96DECL_HIDDEN_DATA(PFNNTQUERYFULLATTRIBUTESFILE) g_pfnNtQueryFullAttributesFile = NULL;
97/** NtDuplicateToken (NT 3.51). */
98DECL_HIDDEN_DATA(PFNNTDUPLICATETOKEN) g_pfnNtDuplicateToken = NULL;
99/** NtAlertThread (NT 3.51). */
100DECL_HIDDEN_DATA(decltype(NtAlertThread) *) g_pfnNtAlertThread = NULL;
101
102/** Either ws2_32.dll (NT4+) or wsock32.dll (NT3.x). */
103DECL_HIDDEN_DATA(HMODULE) g_hModWinSock = NULL;
104/** Set if we're dealing with old winsock. */
105DECL_HIDDEN_DATA(bool) g_fOldWinSock = false;
106/** WSAStartup */
107DECL_HIDDEN_DATA(PFNWSASTARTUP) g_pfnWSAStartup = NULL;
108/** WSACleanup */
109DECL_HIDDEN_DATA(PFNWSACLEANUP) g_pfnWSACleanup = NULL;
110/** Pointner to WSAGetLastError (for RTErrVarsSave). */
111DECL_HIDDEN_DATA(PFNWSAGETLASTERROR) g_pfnWSAGetLastError = NULL;
112/** Pointner to WSASetLastError (for RTErrVarsRestore). */
113DECL_HIDDEN_DATA(PFNWSASETLASTERROR) g_pfnWSASetLastError = NULL;
114/** WSACreateEvent */
115DECL_HIDDEN_DATA(PFNWSACREATEEVENT) g_pfnWSACreateEvent = NULL;
116/** WSACloseEvent */
117DECL_HIDDEN_DATA(PFNWSACLOSEEVENT) g_pfnWSACloseEvent = NULL;
118/** WSASetEvent */
119DECL_HIDDEN_DATA(PFNWSASETEVENT) g_pfnWSASetEvent = NULL;
120/** WSAEventSelect */
121DECL_HIDDEN_DATA(PFNWSAEVENTSELECT) g_pfnWSAEventSelect = NULL;
122/** WSAEnumNetworkEvents */
123DECL_HIDDEN_DATA(PFNWSAENUMNETWORKEVENTS) g_pfnWSAEnumNetworkEvents = NULL;
124/** WSASend */
125DECL_HIDDEN_DATA(PFNWSASend) g_pfnWSASend = NULL;
126/** socket */
127DECL_HIDDEN_DATA(PFNWINSOCKSOCKET) g_pfnsocket = NULL;
128/** closesocket */
129DECL_HIDDEN_DATA(PFNWINSOCKCLOSESOCKET) g_pfnclosesocket = NULL;
130/** recv */
131DECL_HIDDEN_DATA(PFNWINSOCKRECV) g_pfnrecv = NULL;
132/** send */
133DECL_HIDDEN_DATA(PFNWINSOCKSEND) g_pfnsend = NULL;
134/** recvfrom */
135DECL_HIDDEN_DATA(PFNWINSOCKRECVFROM) g_pfnrecvfrom = NULL;
136/** sendto */
137DECL_HIDDEN_DATA(PFNWINSOCKSENDTO) g_pfnsendto = NULL;
138/** bind */
139DECL_HIDDEN_DATA(PFNWINSOCKBIND) g_pfnbind = NULL;
140/** listen */
141DECL_HIDDEN_DATA(PFNWINSOCKLISTEN) g_pfnlisten = NULL;
142/** accept */
143DECL_HIDDEN_DATA(PFNWINSOCKACCEPT) g_pfnaccept = NULL;
144/** connect */
145DECL_HIDDEN_DATA(PFNWINSOCKCONNECT) g_pfnconnect = NULL;
146/** shutdown */
147DECL_HIDDEN_DATA(PFNWINSOCKSHUTDOWN) g_pfnshutdown = NULL;
148/** getsockopt */
149DECL_HIDDEN_DATA(PFNWINSOCKGETSOCKOPT) g_pfngetsockopt = NULL;
150/** setsockopt */
151DECL_HIDDEN_DATA(PFNWINSOCKSETSOCKOPT) g_pfnsetsockopt = NULL;
152/** ioctlsocket */
153DECL_HIDDEN_DATA(PFNWINSOCKIOCTLSOCKET) g_pfnioctlsocket = NULL;
154/** getpeername */
155DECL_HIDDEN_DATA(PFNWINSOCKGETPEERNAME) g_pfngetpeername = NULL;
156/** getsockname */
157DECL_HIDDEN_DATA(PFNWINSOCKGETSOCKNAME) g_pfngetsockname = NULL;
158/** __WSAFDIsSet */
159DECL_HIDDEN_DATA(PFNWINSOCK__WSAFDISSET) g_pfn__WSAFDIsSet = NULL;
160/** select */
161DECL_HIDDEN_DATA(PFNWINSOCKSELECT) g_pfnselect = NULL;
162/** gethostbyname */
163DECL_HIDDEN_DATA(PFNWINSOCKGETHOSTBYNAME) g_pfngethostbyname = NULL;
164
165
166/*********************************************************************************************************************************
167* Internal Functions *
168*********************************************************************************************************************************/
169static LONG CALLBACK rtR3WinUnhandledXcptFilter(PEXCEPTION_POINTERS);
170
171
172/**
173 * Translates OSVERSIONINOFEX into a Windows OS type.
174 *
175 * @returns The Windows OS type.
176 * @param pOSInfoEx The OS info returned by Windows.
177 *
178 * @remarks This table has been assembled from Usenet postings, personal
179 * observations, and reading other people's code. Please feel
180 * free to add to it or correct it.
181 * <pre>
182 dwPlatFormID dwMajorVersion dwMinorVersion dwBuildNumber
18395 1 4 0 950
18495 SP1 1 4 0 >950 && <=1080
18595 OSR2 1 4 <10 >1080
18698 1 4 10 1998
18798 SP1 1 4 10 >1998 && <2183
18898 SE 1 4 10 >=2183
189ME 1 4 90 3000
190
191NT 3.51 2 3 51 1057
192NT 4 2 4 0 1381
1932000 2 5 0 2195
194XP 2 5 1 2600
1952003 2 5 2 3790
196Vista 2 6 0
197
198CE 1.0 3 1 0
199CE 2.0 3 2 0
200CE 2.1 3 2 1
201CE 3.0 3 3 0
202</pre>
203 */
204static RTWINOSTYPE rtR3InitWinSimplifiedVersion(OSVERSIONINFOEXW const *pOSInfoEx)
205{
206 RTWINOSTYPE enmVer = kRTWinOSType_UNKNOWN;
207 BYTE const bProductType = pOSInfoEx->wProductType;
208 DWORD const dwPlatformId = pOSInfoEx->dwPlatformId;
209 DWORD const dwMinorVersion = pOSInfoEx->dwMinorVersion;
210 DWORD const dwMajorVersion = pOSInfoEx->dwMajorVersion;
211 DWORD const dwBuildNumber = pOSInfoEx->dwBuildNumber & 0xFFFF; /* Win 9x needs this. */
212
213 if ( dwPlatformId == VER_PLATFORM_WIN32_WINDOWS
214 && dwMajorVersion == 4)
215 {
216 if ( dwMinorVersion < 10
217 && dwBuildNumber == 950)
218 enmVer = kRTWinOSType_95;
219 else if ( dwMinorVersion < 10
220 && dwBuildNumber > 950
221 && dwBuildNumber <= 1080)
222 enmVer = kRTWinOSType_95SP1;
223 else if ( dwMinorVersion < 10
224 && dwBuildNumber > 1080)
225 enmVer = kRTWinOSType_95OSR2;
226 else if ( dwMinorVersion == 10
227 && dwBuildNumber == 1998)
228 enmVer = kRTWinOSType_98;
229 else if ( dwMinorVersion == 10
230 && dwBuildNumber > 1998
231 && dwBuildNumber < 2183)
232 enmVer = kRTWinOSType_98SP1;
233 else if ( dwMinorVersion == 10
234 && dwBuildNumber >= 2183)
235 enmVer = kRTWinOSType_98SE;
236 else if (dwMinorVersion == 90)
237 enmVer = kRTWinOSType_ME;
238 }
239 else if (dwPlatformId == VER_PLATFORM_WIN32_NT)
240 {
241 if (dwMajorVersion == 3)
242 {
243 if ( dwMinorVersion < 50)
244 enmVer = kRTWinOSType_NT310;
245 else if (dwMinorVersion == 50)
246 enmVer = kRTWinOSType_NT350;
247 else
248 enmVer = kRTWinOSType_NT351;
249 }
250 else if (dwMajorVersion == 4)
251 enmVer = kRTWinOSType_NT4;
252 else if (dwMajorVersion == 5)
253 {
254 if (dwMinorVersion == 0)
255 enmVer = kRTWinOSType_2K;
256 else if (dwMinorVersion == 1)
257 enmVer = kRTWinOSType_XP;
258 else
259 enmVer = kRTWinOSType_2003;
260 }
261 else if (dwMajorVersion == 6)
262 {
263 if (dwMinorVersion == 0)
264 enmVer = bProductType != VER_NT_WORKSTATION ? kRTWinOSType_2008 : kRTWinOSType_VISTA;
265 else if (dwMinorVersion == 1)
266 enmVer = bProductType != VER_NT_WORKSTATION ? kRTWinOSType_2008R2 : kRTWinOSType_7;
267 else if (dwMinorVersion == 2)
268 enmVer = bProductType != VER_NT_WORKSTATION ? kRTWinOSType_2012 : kRTWinOSType_8;
269 else if (dwMinorVersion == 3)
270 enmVer = bProductType != VER_NT_WORKSTATION ? kRTWinOSType_2012R2 : kRTWinOSType_81;
271 else if (dwMinorVersion == 4)
272 enmVer = bProductType != VER_NT_WORKSTATION ? kRTWinOSType_2016 : kRTWinOSType_10;
273 else
274 enmVer = kRTWinOSType_NT_UNKNOWN;
275 }
276 else if (dwMajorVersion == 10)
277 {
278 if (dwMinorVersion == 0)
279 {
280 /* The version detection for server 2019, server 2022 and windows 11
281 are by build number. Stupid, stupid, Microsoft. */
282 if (bProductType == VER_NT_WORKSTATION)
283 enmVer = dwBuildNumber >= 22000 ? kRTWinOSType_11 : kRTWinOSType_10;
284 else
285 enmVer = dwBuildNumber >= 20348 ? kRTWinOSType_2022
286 : dwBuildNumber >= 17763 ? kRTWinOSType_2019 : kRTWinOSType_2016;
287 }
288 else
289 enmVer = kRTWinOSType_NT_UNKNOWN;
290 }
291 else
292 enmVer = kRTWinOSType_NT_UNKNOWN;
293 }
294
295 return enmVer;
296}
297
298
299/**
300 * Initializes the global variables related to windows version.
301 */
302static void rtR3InitWindowsVersion(void)
303{
304 Assert(g_hModNtDll != NULL);
305
306 /*
307 * ASSUMES OSVERSIONINFOEX starts with the exact same layout as OSVERSIONINFO (safe).
308 */
309 AssertCompileMembersSameSizeAndOffset(OSVERSIONINFOEX, szCSDVersion, OSVERSIONINFO, szCSDVersion);
310 AssertCompileMemberOffset(OSVERSIONINFOEX, wServicePackMajor, sizeof(OSVERSIONINFO));
311
312 /*
313 * Use the NT version of GetVersionExW so we don't get fooled by
314 * compatability shims.
315 */
316 RT_ZERO(g_WinOsInfoEx);
317 g_WinOsInfoEx.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
318
319 LONG (__stdcall *pfnRtlGetVersion)(OSVERSIONINFOEXW *);
320 *(FARPROC *)&pfnRtlGetVersion = GetProcAddress(g_hModNtDll, "RtlGetVersion");
321 LONG rcNt = -1;
322 if (pfnRtlGetVersion)
323 rcNt = pfnRtlGetVersion(&g_WinOsInfoEx);
324 if (rcNt != 0)
325 {
326 /*
327 * Couldn't find it or it failed, try the windows version of the API.
328 */
329 RT_ZERO(g_WinOsInfoEx);
330 g_WinOsInfoEx.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
331 if (!GetVersionExW((POSVERSIONINFOW)&g_WinOsInfoEx))
332 {
333 /*
334 * If that didn't work either, just get the basic version bits.
335 */
336 RT_ZERO(g_WinOsInfoEx);
337 g_WinOsInfoEx.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
338 if (GetVersionExW((POSVERSIONINFOW)&g_WinOsInfoEx))
339 Assert(g_WinOsInfoEx.dwPlatformId != VER_PLATFORM_WIN32_NT || g_WinOsInfoEx.dwMajorVersion < 5);
340 else
341 {
342 AssertBreakpoint();
343 RT_ZERO(g_WinOsInfoEx);
344 }
345 }
346 }
347
348 if (g_WinOsInfoEx.dwOSVersionInfoSize)
349 g_enmWinVer = rtR3InitWinSimplifiedVersion(&g_WinOsInfoEx);
350}
351
352
353/**
354 * Resolves the winsock error APIs.
355 */
356static void rtR3InitWinSockApis(void)
357{
358 /*
359 * Try get ws2_32.dll, then try load it, then finally fall back to the old
360 * wsock32.dll. We use RTLdrLoadSystem to the loading as it has all the fancy
361 * logic for safely doing that.
362 */
363 g_hModWinSock = GetModuleHandleW(L"ws2_32.dll");
364 if (g_hModWinSock == NULL)
365 {
366 RTLDRMOD hLdrMod;
367 int rc = RTLdrLoadSystem("ws2_32.dll", true /*fNoUnload*/, &hLdrMod);
368 if (RT_FAILURE(rc))
369 {
370 rc = RTLdrLoadSystem("wsock32.dll", true /*fNoUnload*/, &hLdrMod);
371 if (RT_FAILURE(rc))
372 {
373 AssertMsgFailed(("rc=%Rrc\n", rc));
374 return;
375 }
376 g_fOldWinSock = true;
377 }
378 g_hModWinSock = (HMODULE)RTLdrGetNativeHandle(hLdrMod);
379 RTLdrClose(hLdrMod);
380 }
381
382 g_pfnWSAStartup = (decltype(g_pfnWSAStartup)) GetProcAddress(g_hModWinSock, "WSAStartup");
383 g_pfnWSACleanup = (decltype(g_pfnWSACleanup)) GetProcAddress(g_hModWinSock, "WSACleanup");
384 g_pfnWSAGetLastError = (decltype(g_pfnWSAGetLastError)) GetProcAddress(g_hModWinSock, "WSAGetLastError");
385 g_pfnWSASetLastError = (decltype(g_pfnWSASetLastError)) GetProcAddress(g_hModWinSock, "WSASetLastError");
386 g_pfnWSACreateEvent = (decltype(g_pfnWSACreateEvent)) GetProcAddress(g_hModWinSock, "WSACreateEvent");
387 g_pfnWSACloseEvent = (decltype(g_pfnWSACloseEvent)) GetProcAddress(g_hModWinSock, "WSACloseEvent");
388 g_pfnWSASetEvent = (decltype(g_pfnWSASetEvent)) GetProcAddress(g_hModWinSock, "WSASetEvent");
389 g_pfnWSAEventSelect = (decltype(g_pfnWSAEventSelect)) GetProcAddress(g_hModWinSock, "WSAEventSelect");
390 g_pfnWSAEnumNetworkEvents = (decltype(g_pfnWSAEnumNetworkEvents))GetProcAddress(g_hModWinSock,"WSAEnumNetworkEvents");
391 g_pfnWSASend = (decltype(g_pfnWSASend)) GetProcAddress(g_hModWinSock, "WSASend");
392 g_pfnsocket = (decltype(g_pfnsocket)) GetProcAddress(g_hModWinSock, "socket");
393 g_pfnclosesocket = (decltype(g_pfnclosesocket)) GetProcAddress(g_hModWinSock, "closesocket");
394 g_pfnrecv = (decltype(g_pfnrecv)) GetProcAddress(g_hModWinSock, "recv");
395 g_pfnsend = (decltype(g_pfnsend)) GetProcAddress(g_hModWinSock, "send");
396 g_pfnrecvfrom = (decltype(g_pfnrecvfrom)) GetProcAddress(g_hModWinSock, "recvfrom");
397 g_pfnsendto = (decltype(g_pfnsendto)) GetProcAddress(g_hModWinSock, "sendto");
398 g_pfnbind = (decltype(g_pfnbind)) GetProcAddress(g_hModWinSock, "bind");
399 g_pfnlisten = (decltype(g_pfnlisten)) GetProcAddress(g_hModWinSock, "listen");
400 g_pfnaccept = (decltype(g_pfnaccept)) GetProcAddress(g_hModWinSock, "accept");
401 g_pfnconnect = (decltype(g_pfnconnect)) GetProcAddress(g_hModWinSock, "connect");
402 g_pfnshutdown = (decltype(g_pfnshutdown)) GetProcAddress(g_hModWinSock, "shutdown");
403 g_pfngetsockopt = (decltype(g_pfngetsockopt)) GetProcAddress(g_hModWinSock, "getsockopt");
404 g_pfnsetsockopt = (decltype(g_pfnsetsockopt)) GetProcAddress(g_hModWinSock, "setsockopt");
405 g_pfnioctlsocket = (decltype(g_pfnioctlsocket)) GetProcAddress(g_hModWinSock, "ioctlsocket");
406 g_pfngetpeername = (decltype(g_pfngetpeername)) GetProcAddress(g_hModWinSock, "getpeername");
407 g_pfngetsockname = (decltype(g_pfngetsockname)) GetProcAddress(g_hModWinSock, "getsockname");
408 g_pfn__WSAFDIsSet = (decltype(g_pfn__WSAFDIsSet)) GetProcAddress(g_hModWinSock, "__WSAFDIsSet");
409 g_pfnselect = (decltype(g_pfnselect)) GetProcAddress(g_hModWinSock, "select");
410 g_pfngethostbyname = (decltype(g_pfngethostbyname)) GetProcAddress(g_hModWinSock, "gethostbyname");
411
412 Assert(g_pfnWSAStartup);
413 Assert(g_pfnWSACleanup);
414 Assert(g_pfnWSAGetLastError);
415 Assert(g_pfnWSASetLastError);
416 Assert(g_pfnWSACreateEvent || g_fOldWinSock);
417 Assert(g_pfnWSACloseEvent || g_fOldWinSock);
418 Assert(g_pfnWSASetEvent || g_fOldWinSock);
419 Assert(g_pfnWSAEventSelect || g_fOldWinSock);
420 Assert(g_pfnWSAEnumNetworkEvents || g_fOldWinSock);
421 Assert(g_pfnWSASend || g_fOldWinSock);
422 Assert(g_pfnsocket);
423 Assert(g_pfnclosesocket);
424 Assert(g_pfnrecv);
425 Assert(g_pfnsend);
426 Assert(g_pfnrecvfrom);
427 Assert(g_pfnsendto);
428 Assert(g_pfnbind);
429 Assert(g_pfnlisten);
430 Assert(g_pfnaccept);
431 Assert(g_pfnconnect);
432 Assert(g_pfnshutdown);
433 Assert(g_pfngetsockopt);
434 Assert(g_pfnsetsockopt);
435 Assert(g_pfnioctlsocket);
436 Assert(g_pfngetpeername);
437 Assert(g_pfngetsockname);
438 Assert(g_pfn__WSAFDIsSet);
439 Assert(g_pfnselect);
440 Assert(g_pfngethostbyname);
441}
442
443
444static int rtR3InitNativeObtrusiveWorker(uint32_t fFlags)
445{
446 /*
447 * Disable error popups.
448 */
449 UINT fOldErrMode = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
450 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX | fOldErrMode);
451
452 /*
453 * Restrict DLL searching for the process on windows versions which allow
454 * us to do so.
455 * - The first trick works on XP SP1+ and disables the searching of the
456 * current directory.
457 * - The second trick is W7 w/ KB2533623 and W8+, it restrict the DLL
458 * searching to the application directory (except when
459 * RTR3INIT_FLAGS_STANDALONE_APP is given) and the System32 directory.
460 */
461 int rc = VINF_SUCCESS;
462
463 typedef BOOL (WINAPI *PFNSETDLLDIRECTORY)(LPCWSTR);
464 PFNSETDLLDIRECTORY pfnSetDllDir = (PFNSETDLLDIRECTORY)GetProcAddress(g_hModKernel32, "SetDllDirectoryW");
465 if (pfnSetDllDir)
466 {
467 if (pfnSetDllDir(L""))
468 g_enmWinLdrProt = RTR3WINLDRPROT_NO_CWD;
469 else
470 rc = VERR_INTERNAL_ERROR_3;
471 }
472
473 /** @bugref{6861} Observed GUI issues on Vista (32-bit and 64-bit) when using
474 * SetDefaultDllDirectories.
475 * @bugref{8194} Try use SetDefaultDllDirectories on Vista for standalone apps
476 * despite potential GUI issues. */
477 if ( g_enmWinVer > kRTWinOSType_VISTA
478 || (fFlags & RTR3INIT_FLAGS_STANDALONE_APP))
479 {
480 typedef BOOL(WINAPI *PFNSETDEFAULTDLLDIRECTORIES)(DWORD);
481 PFNSETDEFAULTDLLDIRECTORIES pfnSetDefDllDirs;
482 pfnSetDefDllDirs = (PFNSETDEFAULTDLLDIRECTORIES)GetProcAddress(g_hModKernel32, "SetDefaultDllDirectories");
483 if (pfnSetDefDllDirs)
484 {
485 DWORD fDllDirs = LOAD_LIBRARY_SEARCH_SYSTEM32;
486 if (!(fFlags & RTR3INIT_FLAGS_STANDALONE_APP))
487 fDllDirs |= LOAD_LIBRARY_SEARCH_APPLICATION_DIR;
488 if (pfnSetDefDllDirs(fDllDirs))
489 g_enmWinLdrProt = fDllDirs & LOAD_LIBRARY_SEARCH_APPLICATION_DIR ? RTR3WINLDRPROT_SAFE : RTR3WINLDRPROT_SAFER;
490 else if (RT_SUCCESS(rc))
491 rc = VERR_INTERNAL_ERROR_4;
492 }
493 }
494
495 /*
496 * Register an unhandled exception callback if we can.
497 */
498 g_pfnGetCurrentThreadStackLimits = (PFNGETCURRENTTHREADSTACKLIMITS)GetProcAddress(g_hModKernel32, "GetCurrentThreadStackLimits");
499 g_pfnSetUnhandledExceptionFilter = (PFNSETUNHANDLEDEXCEPTIONFILTER)GetProcAddress(g_hModKernel32, "SetUnhandledExceptionFilter");
500 if (g_pfnSetUnhandledExceptionFilter && !g_pfnUnhandledXcptFilter)
501 {
502 g_pfnUnhandledXcptFilter = g_pfnSetUnhandledExceptionFilter(rtR3WinUnhandledXcptFilter);
503 AssertStmt(g_pfnUnhandledXcptFilter != rtR3WinUnhandledXcptFilter, g_pfnUnhandledXcptFilter = NULL);
504 }
505
506 return rc;
507}
508
509
510DECLHIDDEN(int) rtR3InitNativeFirst(uint32_t fFlags)
511{
512 /*
513 * Make sure we've got the handles of the two main Windows NT dlls.
514 */
515 g_hModKernel32 = GetModuleHandleW(L"kernel32.dll");
516 if (g_hModKernel32 == NULL)
517 return VERR_INTERNAL_ERROR_2;
518 g_hModNtDll = GetModuleHandleW(L"ntdll.dll");
519 if (g_hModNtDll == NULL)
520 return VERR_INTERNAL_ERROR_2;
521
522 rtR3InitWindowsVersion();
523
524 int rc = VINF_SUCCESS;
525 if (!(fFlags & RTR3INIT_FLAGS_UNOBTRUSIVE))
526 rc = rtR3InitNativeObtrusiveWorker(fFlags);
527
528 /*
529 * Resolve some kernel32.dll APIs we may need but aren't necessarily
530 * present in older windows versions.
531 */
532 g_pfnGetSystemWindowsDirectoryW = (PFNGETWINSYSDIR)GetProcAddress(g_hModKernel32, "GetSystemWindowsDirectoryW");
533 if (g_pfnGetSystemWindowsDirectoryW)
534 g_pfnGetSystemWindowsDirectoryW = (PFNGETWINSYSDIR)GetProcAddress(g_hModKernel32, "GetWindowsDirectoryW");
535 g_pfnSystemTimeToTzSpecificLocalTime = (decltype(SystemTimeToTzSpecificLocalTime) *)GetProcAddress(g_hModKernel32, "SystemTimeToTzSpecificLocalTime");
536 g_pfnCreateWaitableTimerExW = (PFNCREATEWAITABLETIMEREX)GetProcAddress(g_hModKernel32, "CreateWaitableTimerExW");
537
538 /*
539 * Resolve some ntdll.dll APIs that weren't there in early NT versions.
540 */
541 g_pfnNtQueryFullAttributesFile = (PFNNTQUERYFULLATTRIBUTESFILE)GetProcAddress(g_hModNtDll, "NtQueryFullAttributesFile");
542 g_pfnNtDuplicateToken = (PFNNTDUPLICATETOKEN)GetProcAddress( g_hModNtDll, "NtDuplicateToken");
543 g_pfnNtAlertThread = (decltype(NtAlertThread) *)GetProcAddress( g_hModNtDll, "NtAlertThread");
544
545 /*
546 * Resolve the winsock error getter and setter so assertions can save those too.
547 */
548 rtR3InitWinSockApis();
549
550 return rc;
551}
552
553
554DECLHIDDEN(void) rtR3InitNativeObtrusive(uint32_t fFlags)
555{
556 rtR3InitNativeObtrusiveWorker(fFlags);
557}
558
559
560DECLHIDDEN(int) rtR3InitNativeFinal(uint32_t fFlags)
561{
562 /* Nothing to do here. */
563 RT_NOREF_PV(fFlags);
564 return VINF_SUCCESS;
565}
566
567
568/**
569 * Unhandled exception filter callback.
570 *
571 * Will try log stuff.
572 */
573static LONG CALLBACK rtR3WinUnhandledXcptFilter(PEXCEPTION_POINTERS pPtrs)
574{
575 /*
576 * Try get the logger and log exception details.
577 *
578 * Note! We'll be using RTLogLogger for now, though we should probably add
579 * a less deadlock prone API here and gives up pretty fast if it
580 * cannot get the lock...
581 */
582 PRTLOGGER pLogger = RTLogRelGetDefaultInstance();
583 if (!pLogger)
584 pLogger = RTLogGetDefaultInstance();
585 if (pLogger)
586 {
587 RTLogLogger(pLogger, NULL, "\n!!! rtR3WinUnhandledXcptFilter caught an exception on thread %p in %u !!!\n",
588 RTThreadNativeSelf(), RTProcSelf());
589
590 /*
591 * Dump the exception record.
592 */
593 uintptr_t uXcptPC = 0;
594 PEXCEPTION_RECORD pXcptRec = RT_VALID_PTR(pPtrs) && RT_VALID_PTR(pPtrs->ExceptionRecord) ? pPtrs->ExceptionRecord : NULL;
595 if (pXcptRec)
596 {
597 RTLogLogger(pLogger, NULL, "\nExceptionCode=%#010x ExceptionFlags=%#010x ExceptionAddress=%p\n",
598 pXcptRec->ExceptionCode, pXcptRec->ExceptionFlags, pXcptRec->ExceptionAddress);
599 for (uint32_t i = 0; i < RT_MIN(pXcptRec->NumberParameters, EXCEPTION_MAXIMUM_PARAMETERS); i++)
600 RTLogLogger(pLogger, NULL, "ExceptionInformation[%d]=%p\n", i, pXcptRec->ExceptionInformation[i]);
601 uXcptPC = (uintptr_t)pXcptRec->ExceptionAddress;
602
603 /* Nested? Display one level only. */
604 PEXCEPTION_RECORD pNestedRec = pXcptRec->ExceptionRecord;
605 if (RT_VALID_PTR(pNestedRec))
606 {
607 RTLogLogger(pLogger, NULL, "Nested: ExceptionCode=%#010x ExceptionFlags=%#010x ExceptionAddress=%p (nested %p)\n",
608 pNestedRec->ExceptionCode, pNestedRec->ExceptionFlags, pNestedRec->ExceptionAddress,
609 pNestedRec->ExceptionRecord);
610 for (uint32_t i = 0; i < RT_MIN(pNestedRec->NumberParameters, EXCEPTION_MAXIMUM_PARAMETERS); i++)
611 RTLogLogger(pLogger, NULL, "Nested: ExceptionInformation[%d]=%p\n", i, pNestedRec->ExceptionInformation[i]);
612 uXcptPC = (uintptr_t)pNestedRec->ExceptionAddress;
613 }
614 }
615
616 /*
617 * Dump the context record.
618 */
619 volatile char szMarker[] = "stackmarker";
620 uintptr_t uXcptSP = (uintptr_t)&szMarker[0];
621 PCONTEXT pXcptCtx = RT_VALID_PTR(pPtrs) && RT_VALID_PTR(pPtrs->ContextRecord) ? pPtrs->ContextRecord : NULL;
622 if (pXcptCtx)
623 {
624#ifdef RT_ARCH_AMD64
625 RTLogLogger(pLogger, NULL, "\ncs:rip=%04x:%016RX64\n", pXcptCtx->SegCs, pXcptCtx->Rip);
626 RTLogLogger(pLogger, NULL, "ss:rsp=%04x:%016RX64 rbp=%016RX64\n", pXcptCtx->SegSs, pXcptCtx->Rsp, pXcptCtx->Rbp);
627 RTLogLogger(pLogger, NULL, "rax=%016RX64 rcx=%016RX64 rdx=%016RX64 rbx=%016RX64\n",
628 pXcptCtx->Rax, pXcptCtx->Rcx, pXcptCtx->Rdx, pXcptCtx->Rbx);
629 RTLogLogger(pLogger, NULL, "rsi=%016RX64 rdi=%016RX64 rsp=%016RX64 rbp=%016RX64\n",
630 pXcptCtx->Rsi, pXcptCtx->Rdi, pXcptCtx->Rsp, pXcptCtx->Rbp);
631 RTLogLogger(pLogger, NULL, "r8 =%016RX64 r9 =%016RX64 r10=%016RX64 r11=%016RX64\n",
632 pXcptCtx->R8, pXcptCtx->R9, pXcptCtx->R10, pXcptCtx->R11);
633 RTLogLogger(pLogger, NULL, "r12=%016RX64 r13=%016RX64 r14=%016RX64 r15=%016RX64\n",
634 pXcptCtx->R12, pXcptCtx->R13, pXcptCtx->R14, pXcptCtx->R15);
635 RTLogLogger(pLogger, NULL, "ds=%04x es=%04x fs=%04x gs=%04x eflags=%08x\n",
636 pXcptCtx->SegDs, pXcptCtx->SegEs, pXcptCtx->SegFs, pXcptCtx->SegGs, pXcptCtx->EFlags);
637 RTLogLogger(pLogger, NULL, "p1home=%016RX64 p2home=%016RX64 pe3home=%016RX64\n",
638 pXcptCtx->P1Home, pXcptCtx->P2Home, pXcptCtx->P3Home);
639 RTLogLogger(pLogger, NULL, "p4home=%016RX64 p5home=%016RX64 pe6home=%016RX64\n",
640 pXcptCtx->P4Home, pXcptCtx->P5Home, pXcptCtx->P6Home);
641 RTLogLogger(pLogger, NULL, " LastBranchToRip=%016RX64 LastBranchFromRip=%016RX64\n",
642 pXcptCtx->LastBranchToRip, pXcptCtx->LastBranchFromRip);
643 RTLogLogger(pLogger, NULL, "LastExceptionToRip=%016RX64 LastExceptionFromRip=%016RX64\n",
644 pXcptCtx->LastExceptionToRip, pXcptCtx->LastExceptionFromRip);
645 uXcptSP = pXcptCtx->Rsp;
646 uXcptPC = pXcptCtx->Rip;
647
648#elif defined(RT_ARCH_X86)
649 RTLogLogger(pLogger, NULL, "\ncs:eip=%04x:%08RX32\n", pXcptCtx->SegCs, pXcptCtx->Eip);
650 RTLogLogger(pLogger, NULL, "ss:esp=%04x:%08RX32 ebp=%08RX32\n", pXcptCtx->SegSs, pXcptCtx->Esp, pXcptCtx->Ebp);
651 RTLogLogger(pLogger, NULL, "eax=%08RX32 ecx=%08RX32 edx=%08RX32 ebx=%08RX32\n",
652 pXcptCtx->Eax, pXcptCtx->Ecx, pXcptCtx->Edx, pXcptCtx->Ebx);
653 RTLogLogger(pLogger, NULL, "esi=%08RX32 edi=%08RX32 esp=%08RX32 ebp=%08RX32\n",
654 pXcptCtx->Esi, pXcptCtx->Edi, pXcptCtx->Esp, pXcptCtx->Ebp);
655 RTLogLogger(pLogger, NULL, "ds=%04x es=%04x fs=%04x gs=%04x eflags=%08x\n",
656 pXcptCtx->SegDs, pXcptCtx->SegEs, pXcptCtx->SegFs, pXcptCtx->SegGs, pXcptCtx->EFlags);
657 uXcptSP = pXcptCtx->Esp;
658 uXcptPC = pXcptCtx->Eip;
659#endif
660 }
661
662 /*
663 * Dump stack.
664 */
665 uintptr_t uStack = (uintptr_t)(void *)&szMarker[0];
666 uStack -= uStack & 15;
667
668 size_t cbToDump = PAGE_SIZE - (uStack & PAGE_OFFSET_MASK);
669 if (cbToDump < 512)
670 cbToDump += PAGE_SIZE;
671 size_t cbToXcpt = uXcptSP - uStack;
672 while (cbToXcpt > cbToDump && cbToXcpt <= _16K)
673 cbToDump += PAGE_SIZE;
674 ULONG_PTR uLow = (uintptr_t)&szMarker[0];
675 ULONG_PTR uHigh = (uintptr_t)&szMarker[0];
676 if (g_pfnGetCurrentThreadStackLimits)
677 {
678 g_pfnGetCurrentThreadStackLimits(&uLow, &uHigh);
679 size_t cbToTop = RT_MAX(uLow, uHigh) - uStack;
680 if (cbToTop < _1M)
681 cbToDump = cbToTop;
682 }
683
684 RTLogLogger(pLogger, NULL, "\nStack %p, dumping %#x bytes (low=%p, high=%p)\n", uStack, cbToDump, uLow, uHigh);
685 RTLogLogger(pLogger, NULL, "%.*RhxD\n", cbToDump, uStack);
686
687 /*
688 * Try figure the thread name.
689 *
690 * Note! This involves the thread db lock, so it may deadlock, which
691 * is why it's at the end.
692 */
693 RTLogLogger(pLogger, NULL, "Thread ID: %p\n", RTThreadNativeSelf());
694 RTLogLogger(pLogger, NULL, "Thread name: %s\n", RTThreadSelfName());
695 RTLogLogger(pLogger, NULL, "Thread IPRT: %p\n", RTThreadSelf());
696
697 /*
698 * Try dump the load information.
699 */
700 PPEB pPeb = RTNtCurrentPeb();
701 if (RT_VALID_PTR(pPeb))
702 {
703 PPEB_LDR_DATA pLdrData = pPeb->Ldr;
704 if (RT_VALID_PTR(pLdrData))
705 {
706 PLDR_DATA_TABLE_ENTRY pFound = NULL;
707 LIST_ENTRY * const pList = &pLdrData->InMemoryOrderModuleList;
708 LIST_ENTRY *pListEntry = pList->Flink;
709 uint32_t cLoops = 0;
710 RTLogLogger(pLogger, NULL,
711 "\nLoaded Modules:\n"
712 "%-*s[*] Timestamp Path\n", sizeof(void *) * 4 + 2 - 1, "Address range"
713 );
714 while (pListEntry != pList && RT_VALID_PTR(pListEntry) && cLoops < 1024)
715 {
716 PLDR_DATA_TABLE_ENTRY pLdrEntry = RT_FROM_MEMBER(pListEntry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);
717 uint32_t const cbLength = (uint32_t)(uintptr_t)pLdrEntry->Reserved3[1];
718 char chInd = ' ';
719 if (uXcptPC - (uintptr_t)pLdrEntry->DllBase < cbLength)
720 {
721 chInd = '*';
722 pFound = pLdrEntry;
723 }
724
725 if ( RT_VALID_PTR(pLdrEntry->FullDllName.Buffer)
726 && pLdrEntry->FullDllName.Length > 0
727 && pLdrEntry->FullDllName.Length < _8K
728 && (pLdrEntry->FullDllName.Length & 1) == 0
729 && pLdrEntry->FullDllName.Length <= pLdrEntry->FullDllName.MaximumLength)
730 RTLogLogger(pLogger, NULL, "%p..%p%c %08RX32 %.*ls\n",
731 pLdrEntry->DllBase, (uintptr_t)pLdrEntry->DllBase + cbLength - 1, chInd,
732 pLdrEntry->TimeDateStamp, pLdrEntry->FullDllName.Length / sizeof(RTUTF16),
733 pLdrEntry->FullDllName.Buffer);
734 else
735 RTLogLogger(pLogger, NULL, "%p..%p%c %08RX32 <bad or missing: %p LB %#x max %#x\n",
736 pLdrEntry->DllBase, (uintptr_t)pLdrEntry->DllBase + cbLength - 1, chInd,
737 pLdrEntry->TimeDateStamp, pLdrEntry->FullDllName.Buffer, pLdrEntry->FullDllName.Length,
738 pLdrEntry->FullDllName.MaximumLength);
739
740 /* advance */
741 pListEntry = pListEntry->Flink;
742 cLoops++;
743 }
744
745 /*
746 * Use the above to pick out code addresses on the stack.
747 */
748 if ( cLoops < 1024
749 && uXcptSP - uStack < cbToDump)
750 {
751 RTLogLogger(pLogger, NULL, "\nPotential code addresses on the stack:\n");
752 if (pFound)
753 {
754 if ( RT_VALID_PTR(pFound->FullDllName.Buffer)
755 && pFound->FullDllName.Length > 0
756 && pFound->FullDllName.Length < _8K
757 && (pFound->FullDllName.Length & 1) == 0
758 && pFound->FullDllName.Length <= pFound->FullDllName.MaximumLength)
759 RTLogLogger(pLogger, NULL, "%-*s: %p - %#010RX32 bytes into %.*ls\n",
760 sizeof(void *) * 2, "Xcpt PC", uXcptPC, (uint32_t)(uXcptPC - (uintptr_t)pFound->DllBase),
761 pFound->FullDllName.Length / sizeof(RTUTF16), pFound->FullDllName.Buffer);
762 else
763 RTLogLogger(pLogger, NULL, "%-*s: %p - %08RX32 into module at %p\n",
764 sizeof(void *) * 2, "Xcpt PC", uXcptPC, (uint32_t)(uXcptPC - (uintptr_t)pFound->DllBase),
765 pFound->DllBase);
766 }
767
768 uintptr_t const *puStack = (uintptr_t const *)uXcptSP;
769 uintptr_t cLeft = (cbToDump - (uXcptSP - uStack)) / sizeof(uintptr_t);
770 while (cLeft-- > 0)
771 {
772 uintptr_t uPtr = *puStack;
773 if (RT_VALID_PTR(uPtr))
774 {
775 /* Search the module table. */
776 pFound = NULL;
777 cLoops = 0;
778 pListEntry = pList->Flink;
779 while (pListEntry != pList && RT_VALID_PTR(pListEntry) && cLoops < 1024)
780 {
781 PLDR_DATA_TABLE_ENTRY pLdrEntry = RT_FROM_MEMBER(pListEntry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);
782 uint32_t const cbLength = (uint32_t)(uintptr_t)pLdrEntry->Reserved3[1];
783 if (uPtr - (uintptr_t)pLdrEntry->DllBase < cbLength)
784 {
785 pFound = pLdrEntry;
786 break;
787 }
788
789 /* advance */
790 pListEntry = pListEntry->Flink;
791 cLoops++;
792 }
793
794 if (pFound)
795 {
796 if ( RT_VALID_PTR(pFound->FullDllName.Buffer)
797 && pFound->FullDllName.Length > 0
798 && pFound->FullDllName.Length < _8K
799 && (pFound->FullDllName.Length & 1) == 0
800 && pFound->FullDllName.Length <= pFound->FullDllName.MaximumLength)
801 RTLogLogger(pLogger, NULL, "%p: %p - %#010RX32 bytes into %.*ls\n",
802 puStack, uPtr, (uint32_t)(uPtr - (uintptr_t)pFound->DllBase),
803 pFound->FullDllName.Length / sizeof(RTUTF16), pFound->FullDllName.Buffer);
804 else
805 RTLogLogger(pLogger, NULL, "%p: %p - %08RX32 into module at %p\n",
806 puStack, uPtr, (uint32_t)(uPtr - (uintptr_t)pFound->DllBase), pFound->DllBase);
807 }
808 }
809
810 puStack++;
811 }
812 }
813 }
814
815 /*
816 * Dump the command line if we have one. We do this last in case it crashes.
817 */
818 PRTL_USER_PROCESS_PARAMETERS pProcParams = pPeb->ProcessParameters;
819 if (RT_VALID_PTR(pProcParams))
820 {
821 if (RT_VALID_PTR(pProcParams->CommandLine.Buffer)
822 && pProcParams->CommandLine.Length > 0
823 && pProcParams->CommandLine.Length <= pProcParams->CommandLine.MaximumLength
824 && !(pProcParams->CommandLine.Length & 1)
825 && !(pProcParams->CommandLine.MaximumLength & 1))
826 RTLogLogger(pLogger, NULL, "PEB/CommandLine: %.*ls\n",
827 pProcParams->CommandLine.Length / sizeof(RTUTF16), pProcParams->CommandLine.Buffer);
828 }
829 }
830 }
831
832 /*
833 * Do the default stuff, never mind us.
834 */
835 if (g_pfnUnhandledXcptFilter)
836 return g_pfnUnhandledXcptFilter(pPtrs);
837 return EXCEPTION_CONTINUE_SEARCH;
838}
839
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use