summaryrefslogtreecommitdiffstats
path: root/src/VBox/Runtime/r3/win/init-win.cpp
blob: ae74cf4887a715a6e4659a91c017b0b0672327b1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
/* $Id: init-win.cpp $ */
/** @file
 * IPRT - Init Ring-3, Windows Specific Code.
 */

/*
 * Copyright (C) 2006-2020 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 *
 * The contents of this file may alternatively be used under the terms
 * of the Common Development and Distribution License Version 1.0
 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
 * VirtualBox OSE distribution, in which case the provisions of the
 * CDDL are applicable instead of those of the GPL.
 *
 * You may elect to license modified versions of this file under the
 * terms and conditions of either the GPL or the CDDL or both.
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#define LOG_GROUP RTLOGGROUP_DEFAULT
#include <iprt/nt/nt-and-windows.h>
#ifndef LOAD_LIBRARY_SEARCH_APPLICATION_DIR
# define LOAD_LIBRARY_SEARCH_APPLICATION_DIR    0x200
# define LOAD_LIBRARY_SEARCH_SYSTEM32           0x800
#endif

#include "internal-r3-win.h"
#include <iprt/initterm.h>
#include <iprt/assert.h>
#include <iprt/err.h>
#include <iprt/ldr.h>
#include <iprt/log.h>
#include <iprt/param.h>
#include <iprt/string.h>
#include <iprt/thread.h>
#include "../init.h"


/*********************************************************************************************************************************
*   Structures and Typedefs                                                                                                      *
*********************************************************************************************************************************/
typedef VOID (WINAPI *PFNGETCURRENTTHREADSTACKLIMITS)(PULONG_PTR puLow, PULONG_PTR puHigh);
typedef LPTOP_LEVEL_EXCEPTION_FILTER (WINAPI * PFNSETUNHANDLEDEXCEPTIONFILTER)(LPTOP_LEVEL_EXCEPTION_FILTER);


/*********************************************************************************************************************************
*   Global Variables                                                                                                             *
*********************************************************************************************************************************/
/** Windows DLL loader protection level. */
DECLHIDDEN(RTR3WINLDRPROT)      g_enmWinLdrProt = RTR3WINLDRPROT_NONE;
/** Our simplified windows version.    */
DECLHIDDEN(RTWINOSTYPE)         g_enmWinVer = kRTWinOSType_UNKNOWN;
/** Extended windows version information. */
DECLHIDDEN(OSVERSIONINFOEXW)    g_WinOsInfoEx;

/** The native kernel32.dll handle. */
DECLHIDDEN(HMODULE)                         g_hModKernel32 = NULL;
/** GetSystemWindowsDirectoryW or GetWindowsDirectoryW (NT4). */
DECLHIDDEN(PFNGETWINSYSDIR)                 g_pfnGetSystemWindowsDirectoryW = NULL;
/** The GetCurrentThreadStackLimits API. */
static PFNGETCURRENTTHREADSTACKLIMITS       g_pfnGetCurrentThreadStackLimits = NULL;
/** SetUnhandledExceptionFilter. */
static PFNSETUNHANDLEDEXCEPTIONFILTER       g_pfnSetUnhandledExceptionFilter = NULL;
/** The previous unhandled exception filter. */
static LPTOP_LEVEL_EXCEPTION_FILTER         g_pfnUnhandledXcptFilter = NULL;
/** SystemTimeToTzSpecificLocalTime. */
decltype(SystemTimeToTzSpecificLocalTime)  *g_pfnSystemTimeToTzSpecificLocalTime = NULL;

/** The native ntdll.dll handle. */
DECLHIDDEN(HMODULE)                         g_hModNtDll = NULL;
/** NtQueryFullAttributesFile   */
DECLHIDDEN(PFNNTQUERYFULLATTRIBUTESFILE)    g_pfnNtQueryFullAttributesFile = NULL;
/** NtDuplicateToken (NT 3.51). */
DECLHIDDEN(PFNNTDUPLICATETOKEN)             g_pfnNtDuplicateToken = NULL;
/** NtAlertThread (NT 3.51). */
decltype(NtAlertThread)                    *g_pfnNtAlertThread = NULL;

/** Either ws2_32.dll (NT4+) or wsock32.dll (NT3.x). */
DECLHIDDEN(HMODULE)                         g_hModWinSock = NULL;
/** Set if we're dealing with old winsock.   */
DECLHIDDEN(bool)                            g_fOldWinSock = false;
/** WSAStartup   */
DECLHIDDEN(PFNWSASTARTUP)                   g_pfnWSAStartup = NULL;
/** WSACleanup */
DECLHIDDEN(PFNWSACLEANUP)                   g_pfnWSACleanup = NULL;
/** Pointner to WSAGetLastError (for RTErrVarsSave). */
DECLHIDDEN(PFNWSAGETLASTERROR)              g_pfnWSAGetLastError = NULL;
/** Pointner to WSASetLastError (for RTErrVarsRestore). */
DECLHIDDEN(PFNWSASETLASTERROR)              g_pfnWSASetLastError = NULL;
/** WSACreateEvent */
DECLHIDDEN(PFNWSACREATEEVENT)               g_pfnWSACreateEvent = NULL;
/** WSACloseEvent  */
DECLHIDDEN(PFNWSACLOSEEVENT)                g_pfnWSACloseEvent = NULL;
/** WSASetEvent */
DECLHIDDEN(PFNWSASETEVENT)                  g_pfnWSASetEvent = NULL;
/** WSAEventSelect   */
DECLHIDDEN(PFNWSAEVENTSELECT)               g_pfnWSAEventSelect = NULL;
/** WSAEnumNetworkEvents */
DECLHIDDEN(PFNWSAENUMNETWORKEVENTS)         g_pfnWSAEnumNetworkEvents = NULL;
/** WSASend */
DECLHIDDEN(PFNWSASend)                      g_pfnWSASend = NULL;
/** socket */
DECLHIDDEN(PFNWINSOCKSOCKET)                g_pfnsocket = NULL;
/** closesocket */
DECLHIDDEN(PFNWINSOCKCLOSESOCKET)           g_pfnclosesocket = NULL;
/** recv */
DECLHIDDEN(PFNWINSOCKRECV)                  g_pfnrecv = NULL;
/** send */
DECLHIDDEN(PFNWINSOCKSEND)                  g_pfnsend = NULL;
/** recvfrom */
DECLHIDDEN(PFNWINSOCKRECVFROM)              g_pfnrecvfrom = NULL;
/** sendto */
DECLHIDDEN(PFNWINSOCKSENDTO)                g_pfnsendto = NULL;
/** bind */
DECLHIDDEN(PFNWINSOCKBIND)                  g_pfnbind = NULL;
/** listen  */
DECLHIDDEN(PFNWINSOCKLISTEN)                g_pfnlisten = NULL;
/** accept */
DECLHIDDEN(PFNWINSOCKACCEPT)                g_pfnaccept = NULL;
/** connect */
DECLHIDDEN(PFNWINSOCKCONNECT)               g_pfnconnect = NULL;
/** shutdown */
DECLHIDDEN(PFNWINSOCKSHUTDOWN)              g_pfnshutdown = NULL;
/** getsockopt */
DECLHIDDEN(PFNWINSOCKGETSOCKOPT)            g_pfngetsockopt = NULL;
/** setsockopt */
DECLHIDDEN(PFNWINSOCKSETSOCKOPT)            g_pfnsetsockopt = NULL;
/** ioctlsocket */
DECLHIDDEN(PFNWINSOCKIOCTLSOCKET)           g_pfnioctlsocket = NULL;
/** getpeername   */
DECLHIDDEN(PFNWINSOCKGETPEERNAME)           g_pfngetpeername = NULL;
/** getsockname */
DECLHIDDEN(PFNWINSOCKGETSOCKNAME)           g_pfngetsockname = NULL;
/** __WSAFDIsSet */
DECLHIDDEN(PFNWINSOCK__WSAFDISSET)          g_pfn__WSAFDIsSet = NULL;
/** select */
DECLHIDDEN(PFNWINSOCKSELECT)                g_pfnselect = NULL;
/** gethostbyname */
DECLHIDDEN(PFNWINSOCKGETHOSTBYNAME)         g_pfngethostbyname = NULL;


/*********************************************************************************************************************************
*   Internal Functions                                                                                                           *
*********************************************************************************************************************************/
static LONG CALLBACK rtR3WinUnhandledXcptFilter(PEXCEPTION_POINTERS);


/**
 * Translates OSVERSIONINOFEX into a Windows OS type.
 *
 * @returns The Windows OS type.
 * @param   pOSInfoEx       The OS info returned by Windows.
 *
 * @remarks This table has been assembled from Usenet postings, personal
 *          observations, and reading other people's code.  Please feel
 *          free to add to it or correct it.
 * <pre>
         dwPlatFormID  dwMajorVersion  dwMinorVersion  dwBuildNumber
95             1              4               0             950
95 SP1         1              4               0        >950 && <=1080
95 OSR2        1              4             <10           >1080
98             1              4              10            1998
98 SP1         1              4              10       >1998 && <2183
98 SE          1              4              10          >=2183
ME             1              4              90            3000

NT 3.51        2              3              51            1057
NT 4           2              4               0            1381
2000           2              5               0            2195
XP             2              5               1            2600
2003           2              5               2            3790
Vista          2              6               0

CE 1.0         3              1               0
CE 2.0         3              2               0
CE 2.1         3              2               1
CE 3.0         3              3               0
</pre>
 */
static RTWINOSTYPE rtR3InitWinSimplifiedVersion(OSVERSIONINFOEXW const *pOSInfoEx)
{
    RTWINOSTYPE enmVer         = kRTWinOSType_UNKNOWN;
    BYTE  const bProductType   = pOSInfoEx->wProductType;
    DWORD const dwPlatformId   = pOSInfoEx->dwPlatformId;
    DWORD const dwMinorVersion = pOSInfoEx->dwMinorVersion;
    DWORD const dwMajorVersion = pOSInfoEx->dwMajorVersion;
    DWORD const dwBuildNumber  = pOSInfoEx->dwBuildNumber & 0xFFFF;   /* Win 9x needs this. */

    if (    dwPlatformId == VER_PLATFORM_WIN32_WINDOWS
        &&  dwMajorVersion == 4)
    {
        if (        dwMinorVersion < 10
                 && dwBuildNumber == 950)
            enmVer = kRTWinOSType_95;
        else if (   dwMinorVersion < 10
                 && dwBuildNumber > 950
                 && dwBuildNumber <= 1080)
            enmVer = kRTWinOSType_95SP1;
        else if (   dwMinorVersion < 10
                 && dwBuildNumber > 1080)
            enmVer = kRTWinOSType_95OSR2;
        else if (   dwMinorVersion == 10
                 && dwBuildNumber == 1998)
            enmVer = kRTWinOSType_98;
        else if (   dwMinorVersion == 10
                 && dwBuildNumber > 1998
                 && dwBuildNumber < 2183)
            enmVer = kRTWinOSType_98SP1;
        else if (   dwMinorVersion == 10
                 && dwBuildNumber >= 2183)
            enmVer = kRTWinOSType_98SE;
        else if (dwMinorVersion == 90)
            enmVer = kRTWinOSType_ME;
    }
    else if (dwPlatformId == VER_PLATFORM_WIN32_NT)
    {
        if (dwMajorVersion == 3)
        {
            if (     dwMinorVersion < 50)
                enmVer = kRTWinOSType_NT310;
            else if (dwMinorVersion == 50)
                enmVer = kRTWinOSType_NT350;
            else
                enmVer = kRTWinOSType_NT351;
        }
        else if (dwMajorVersion == 4)
            enmVer = kRTWinOSType_NT4;
        else if (dwMajorVersion == 5)
        {
            if (dwMinorVersion == 0)
                enmVer = kRTWinOSType_2K;
            else if (dwMinorVersion == 1)
                enmVer = kRTWinOSType_XP;
            else
                enmVer = kRTWinOSType_2003;
        }
        else if (dwMajorVersion == 6)
        {
            if (dwMinorVersion == 0)
                enmVer = bProductType != VER_NT_WORKSTATION ? kRTWinOSType_2008   : kRTWinOSType_VISTA;
            else if (dwMinorVersion == 1)
                enmVer = bProductType != VER_NT_WORKSTATION ? kRTWinOSType_2008R2 : kRTWinOSType_7;
            else if (dwMinorVersion == 2)
                enmVer = bProductType != VER_NT_WORKSTATION ? kRTWinOSType_2012   : kRTWinOSType_8;
            else if (dwMinorVersion == 3)
                enmVer = bProductType != VER_NT_WORKSTATION ? kRTWinOSType_2012R2 : kRTWinOSType_81;
            else if (dwMinorVersion == 4)
                enmVer = bProductType != VER_NT_WORKSTATION ? kRTWinOSType_2016   : kRTWinOSType_10;
            else
                enmVer = kRTWinOSType_NT_UNKNOWN;
        }
        else if (dwMajorVersion == 10)
        {
            if (dwMinorVersion == 0)
                enmVer = bProductType != VER_NT_WORKSTATION ? kRTWinOSType_2016   : kRTWinOSType_10;
            else
                enmVer = kRTWinOSType_NT_UNKNOWN;
        }
        else
            enmVer = kRTWinOSType_NT_UNKNOWN;
    }

    return enmVer;
}


/**
 * Initializes the global variables related to windows version.
 */
static void rtR3InitWindowsVersion(void)
{
    Assert(g_hModNtDll != NULL);

    /*
     * ASSUMES OSVERSIONINFOEX starts with the exact same layout as OSVERSIONINFO (safe).
     */
    AssertCompileMembersSameSizeAndOffset(OSVERSIONINFOEX, szCSDVersion, OSVERSIONINFO, szCSDVersion);
    AssertCompileMemberOffset(OSVERSIONINFOEX, wServicePackMajor, sizeof(OSVERSIONINFO));

    /*
     * Use the NT version of GetVersionExW so we don't get fooled by
     * compatability shims.
     */
    RT_ZERO(g_WinOsInfoEx);
    g_WinOsInfoEx.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);

    LONG (__stdcall *pfnRtlGetVersion)(OSVERSIONINFOEXW *);
    *(FARPROC *)&pfnRtlGetVersion = GetProcAddress(g_hModNtDll, "RtlGetVersion");
    LONG rcNt = -1;
    if (pfnRtlGetVersion)
        rcNt = pfnRtlGetVersion(&g_WinOsInfoEx);
    if (rcNt != 0)
    {
        /*
         * Couldn't find it or it failed, try the windows version of the API.
         */
        RT_ZERO(g_WinOsInfoEx);
        g_WinOsInfoEx.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
        if (!GetVersionExW((POSVERSIONINFOW)&g_WinOsInfoEx))
        {
            /*
             * If that didn't work either, just get the basic version bits.
             */
            RT_ZERO(g_WinOsInfoEx);
            g_WinOsInfoEx.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
            if (GetVersionExW((POSVERSIONINFOW)&g_WinOsInfoEx))
                Assert(g_WinOsInfoEx.dwPlatformId != VER_PLATFORM_WIN32_NT || g_WinOsInfoEx.dwMajorVersion < 5);
            else
            {
                AssertBreakpoint();
                RT_ZERO(g_WinOsInfoEx);
            }
        }
    }

    if (g_WinOsInfoEx.dwOSVersionInfoSize)
        g_enmWinVer = rtR3InitWinSimplifiedVersion(&g_WinOsInfoEx);
}


/**
 * Resolves the winsock error APIs.
 */
static void rtR3InitWinSockApis(void)
{
    /*
     * Try get ws2_32.dll, then try load it, then finally fall back to the old
     * wsock32.dll.  We use RTLdrLoadSystem to the loading as it has all the fancy
     * logic for safely doing that.
     */
    g_hModWinSock = GetModuleHandleW(L"ws2_32.dll");
    if (g_hModWinSock == NULL)
    {
        RTLDRMOD hLdrMod;
        int rc = RTLdrLoadSystem("ws2_32.dll", true /*fNoUnload*/, &hLdrMod);
        if (RT_FAILURE(rc))
        {
            rc = RTLdrLoadSystem("wsock32.dll", true /*fNoUnload*/, &hLdrMod);
            if (RT_FAILURE(rc))
            {
                AssertMsgFailed(("rc=%Rrc\n", rc));
                return;
            }
            g_fOldWinSock = true;
        }
        g_hModWinSock = (HMODULE)RTLdrGetNativeHandle(hLdrMod);
        RTLdrClose(hLdrMod);
    }

    g_pfnWSAStartup           = (decltype(g_pfnWSAStartup))         GetProcAddress(g_hModWinSock, "WSAStartup");
    g_pfnWSACleanup           = (decltype(g_pfnWSACleanup))         GetProcAddress(g_hModWinSock, "WSACleanup");
    g_pfnWSAGetLastError      = (decltype(g_pfnWSAGetLastError))    GetProcAddress(g_hModWinSock, "WSAGetLastError");
    g_pfnWSASetLastError      = (decltype(g_pfnWSASetLastError))    GetProcAddress(g_hModWinSock, "WSASetLastError");
    g_pfnWSACreateEvent       = (decltype(g_pfnWSACreateEvent))     GetProcAddress(g_hModWinSock, "WSACreateEvent");
    g_pfnWSACloseEvent        = (decltype(g_pfnWSACloseEvent))      GetProcAddress(g_hModWinSock, "WSACloseEvent");
    g_pfnWSASetEvent          = (decltype(g_pfnWSASetEvent))        GetProcAddress(g_hModWinSock, "WSASetEvent");
    g_pfnWSAEventSelect       = (decltype(g_pfnWSAEventSelect))     GetProcAddress(g_hModWinSock, "WSAEventSelect");
    g_pfnWSAEnumNetworkEvents = (decltype(g_pfnWSAEnumNetworkEvents))GetProcAddress(g_hModWinSock,"WSAEnumNetworkEvents");
    g_pfnWSASend              = (decltype(g_pfnWSASend))            GetProcAddress(g_hModWinSock, "WSASend");
    g_pfnsocket               = (decltype(g_pfnsocket))             GetProcAddress(g_hModWinSock, "socket");
    g_pfnclosesocket          = (decltype(g_pfnclosesocket))        GetProcAddress(g_hModWinSock, "closesocket");
    g_pfnrecv                 = (decltype(g_pfnrecv))               GetProcAddress(g_hModWinSock, "recv");
    g_pfnsend                 = (decltype(g_pfnsend))               GetProcAddress(g_hModWinSock, "send");
    g_pfnrecvfrom             = (decltype(g_pfnrecvfrom))           GetProcAddress(g_hModWinSock, "recvfrom");
    g_pfnsendto               = (decltype(g_pfnsendto))             GetProcAddress(g_hModWinSock, "sendto");
    g_pfnbind                 = (decltype(g_pfnbind))               GetProcAddress(g_hModWinSock, "bind");
    g_pfnlisten               = (decltype(g_pfnlisten))             GetProcAddress(g_hModWinSock, "listen");
    g_pfnaccept               = (decltype(g_pfnaccept))             GetProcAddress(g_hModWinSock, "accept");
    g_pfnconnect              = (decltype(g_pfnconnect))            GetProcAddress(g_hModWinSock, "connect");
    g_pfnshutdown             = (decltype(g_pfnshutdown))           GetProcAddress(g_hModWinSock, "shutdown");
    g_pfngetsockopt           = (decltype(g_pfngetsockopt))         GetProcAddress(g_hModWinSock, "getsockopt");
    g_pfnsetsockopt           = (decltype(g_pfnsetsockopt))         GetProcAddress(g_hModWinSock, "setsockopt");
    g_pfnioctlsocket          = (decltype(g_pfnioctlsocket))        GetProcAddress(g_hModWinSock, "ioctlsocket");
    g_pfngetpeername          = (decltype(g_pfngetpeername))        GetProcAddress(g_hModWinSock, "getpeername");
    g_pfngetsockname          = (decltype(g_pfngetsockname))        GetProcAddress(g_hModWinSock, "getsockname");
    g_pfn__WSAFDIsSet         = (decltype(g_pfn__WSAFDIsSet))       GetProcAddress(g_hModWinSock, "__WSAFDIsSet");
    g_pfnselect               = (decltype(g_pfnselect))             GetProcAddress(g_hModWinSock, "select");
    g_pfngethostbyname        = (decltype(g_pfngethostbyname))      GetProcAddress(g_hModWinSock, "gethostbyname");

    Assert(g_pfnWSAStartup);
    Assert(g_pfnWSACleanup);
    Assert(g_pfnWSAGetLastError);
    Assert(g_pfnWSASetLastError);
    Assert(g_pfnWSACreateEvent       || g_fOldWinSock);
    Assert(g_pfnWSACloseEvent        || g_fOldWinSock);
    Assert(g_pfnWSASetEvent          || g_fOldWinSock);
    Assert(g_pfnWSAEventSelect       || g_fOldWinSock);
    Assert(g_pfnWSAEnumNetworkEvents || g_fOldWinSock);
    Assert(g_pfnWSASend              || g_fOldWinSock);
    Assert(g_pfnsocket);
    Assert(g_pfnclosesocket);
    Assert(g_pfnrecv);
    Assert(g_pfnsend);
    Assert(g_pfnrecvfrom);
    Assert(g_pfnsendto);
    Assert(g_pfnbind);
    Assert(g_pfnlisten);
    Assert(g_pfnaccept);
    Assert(g_pfnconnect);
    Assert(g_pfnshutdown);
    Assert(g_pfngetsockopt);
    Assert(g_pfnsetsockopt);
    Assert(g_pfnioctlsocket);
    Assert(g_pfngetpeername);
    Assert(g_pfngetsockname);
    Assert(g_pfn__WSAFDIsSet);
    Assert(g_pfnselect);
    Assert(g_pfngethostbyname);
}


static int rtR3InitNativeObtrusiveWorker(uint32_t fFlags)
{
    /*
     * Disable error popups.
     */
    UINT fOldErrMode = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
    SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX | fOldErrMode);

    /*
     * Restrict DLL searching for the process on windows versions which allow
     * us to do so.
     *  - The first trick works on XP SP1+ and disables the searching of the
     *    current directory.
     *  - The second trick is W7 w/ KB2533623 and W8+, it restrict the DLL
     *    searching to the application directory (except when
     *    RTR3INIT_FLAGS_STANDALONE_APP is given) and the System32 directory.
     */
    int rc = VINF_SUCCESS;

    typedef BOOL (WINAPI *PFNSETDLLDIRECTORY)(LPCWSTR);
    PFNSETDLLDIRECTORY pfnSetDllDir = (PFNSETDLLDIRECTORY)GetProcAddress(g_hModKernel32, "SetDllDirectoryW");
    if (pfnSetDllDir)
    {
        if (pfnSetDllDir(L""))
            g_enmWinLdrProt = RTR3WINLDRPROT_NO_CWD;
        else
            rc = VERR_INTERNAL_ERROR_3;
    }

    /** @bugref{6861} Observed GUI issues on Vista (32-bit and 64-bit) when using
     *                SetDefaultDllDirectories.
     *  @bugref{8194} Try use SetDefaultDllDirectories on Vista for standalone apps
     *                despite potential GUI issues. */
    if (   g_enmWinVer > kRTWinOSType_VISTA
        || (fFlags & RTR3INIT_FLAGS_STANDALONE_APP))
    {
        typedef BOOL(WINAPI *PFNSETDEFAULTDLLDIRECTORIES)(DWORD);
        PFNSETDEFAULTDLLDIRECTORIES pfnSetDefDllDirs;
        pfnSetDefDllDirs = (PFNSETDEFAULTDLLDIRECTORIES)GetProcAddress(g_hModKernel32, "SetDefaultDllDirectories");
        if (pfnSetDefDllDirs)
        {
            DWORD fDllDirs = LOAD_LIBRARY_SEARCH_SYSTEM32;
            if (!(fFlags & RTR3INIT_FLAGS_STANDALONE_APP))
                fDllDirs |= LOAD_LIBRARY_SEARCH_APPLICATION_DIR;
            if (pfnSetDefDllDirs(fDllDirs))
                g_enmWinLdrProt = fDllDirs & LOAD_LIBRARY_SEARCH_APPLICATION_DIR ? RTR3WINLDRPROT_SAFE : RTR3WINLDRPROT_SAFER;
            else if (RT_SUCCESS(rc))
                rc = VERR_INTERNAL_ERROR_4;
        }
    }

    /*
     * Register an unhandled exception callback if we can.
     */
    g_pfnGetCurrentThreadStackLimits = (PFNGETCURRENTTHREADSTACKLIMITS)GetProcAddress(g_hModKernel32, "GetCurrentThreadStackLimits");
    g_pfnSetUnhandledExceptionFilter = (PFNSETUNHANDLEDEXCEPTIONFILTER)GetProcAddress(g_hModKernel32, "SetUnhandledExceptionFilter");
    if (g_pfnSetUnhandledExceptionFilter && !g_pfnUnhandledXcptFilter)
    {
        g_pfnUnhandledXcptFilter = g_pfnSetUnhandledExceptionFilter(rtR3WinUnhandledXcptFilter);
        AssertStmt(g_pfnUnhandledXcptFilter != rtR3WinUnhandledXcptFilter, g_pfnUnhandledXcptFilter = NULL);
    }

    return rc;
}


DECLHIDDEN(int) rtR3InitNativeFirst(uint32_t fFlags)
{
    /*
     * Make sure we've got the handles of the two main Windows NT dlls.
     */
    g_hModKernel32 = GetModuleHandleW(L"kernel32.dll");
    if (g_hModKernel32 == NULL)
        return VERR_INTERNAL_ERROR_2;
    g_hModNtDll    = GetModuleHandleW(L"ntdll.dll");
    if (g_hModNtDll == NULL)
        return VERR_INTERNAL_ERROR_2;

    rtR3InitWindowsVersion();

    int rc = VINF_SUCCESS;
    if (!(fFlags & RTR3INIT_FLAGS_UNOBTRUSIVE))
        rc = rtR3InitNativeObtrusiveWorker(fFlags);

    /*
     * Resolve some kernel32.dll APIs we may need but aren't necessarily
     * present in older windows versions.
     */
    g_pfnGetSystemWindowsDirectoryW = (PFNGETWINSYSDIR)GetProcAddress(g_hModKernel32, "GetSystemWindowsDirectoryW");
    if (g_pfnGetSystemWindowsDirectoryW)
        g_pfnGetSystemWindowsDirectoryW = (PFNGETWINSYSDIR)GetProcAddress(g_hModKernel32, "GetWindowsDirectoryW");
    g_pfnSystemTimeToTzSpecificLocalTime = (decltype(SystemTimeToTzSpecificLocalTime) *)GetProcAddress(g_hModKernel32, "SystemTimeToTzSpecificLocalTime");

    /*
     * Resolve some ntdll.dll APIs that weren't there in early NT versions.
     */
    g_pfnNtQueryFullAttributesFile = (PFNNTQUERYFULLATTRIBUTESFILE)GetProcAddress(g_hModNtDll, "NtQueryFullAttributesFile");
    g_pfnNtDuplicateToken          = (PFNNTDUPLICATETOKEN)GetProcAddress(         g_hModNtDll, "NtDuplicateToken");
    g_pfnNtAlertThread             = (decltype(NtAlertThread) *)GetProcAddress(   g_hModNtDll, "NtAlertThread");

    /*
     * Resolve the winsock error getter and setter so assertions can save those too.
     */
    rtR3InitWinSockApis();

    return rc;
}


DECLHIDDEN(void) rtR3InitNativeObtrusive(uint32_t fFlags)
{
    rtR3InitNativeObtrusiveWorker(fFlags);
}


DECLHIDDEN(int) rtR3InitNativeFinal(uint32_t fFlags)
{
    /* Nothing to do here. */
    RT_NOREF_PV(fFlags);
    return VINF_SUCCESS;
}


/**
 * Unhandled exception filter callback.
 *
 * Will try log stuff.
 */
static LONG CALLBACK rtR3WinUnhandledXcptFilter(PEXCEPTION_POINTERS pPtrs)
{
    /*
     * Try get the logger and log exception details.
     *
     * Note! We'll be using RTLogLogger for now, though we should probably add
     *       a less deadlock prone API here and gives up pretty fast if it
     *       cannot get the lock...
     */
    PRTLOGGER pLogger = RTLogRelGetDefaultInstance();
    if (!pLogger)
        pLogger = RTLogGetDefaultInstance();
    if (pLogger)
    {
        RTLogLogger(pLogger, NULL, "\n!!! rtR3WinUnhandledXcptFilter caught an exception on thread %p!!!\n", RTThreadNativeSelf());

        /*
         * Dump the exception record.
         */
        uintptr_t         uXcptPC  = 0;
        PEXCEPTION_RECORD pXcptRec = RT_VALID_PTR(pPtrs) && RT_VALID_PTR(pPtrs->ExceptionRecord) ? pPtrs->ExceptionRecord : NULL;
        if (pXcptRec)
        {
            RTLogLogger(pLogger, NULL, "\nExceptionCode=%#010x ExceptionFlags=%#010x ExceptionAddress=%p\n",
                        pXcptRec->ExceptionCode, pXcptRec->ExceptionFlags, pXcptRec->ExceptionAddress);
            for (uint32_t i = 0; i < RT_MIN(pXcptRec->NumberParameters, EXCEPTION_MAXIMUM_PARAMETERS); i++)
                RTLogLogger(pLogger, NULL, "ExceptionInformation[%d]=%p\n", i, pXcptRec->ExceptionInformation[i]);
            uXcptPC = (uintptr_t)pXcptRec->ExceptionAddress;

            /* Nested? Display one level only. */
            PEXCEPTION_RECORD pNestedRec = pXcptRec->ExceptionRecord;
            if (RT_VALID_PTR(pNestedRec))
            {
                RTLogLogger(pLogger, NULL, "Nested: ExceptionCode=%#010x ExceptionFlags=%#010x ExceptionAddress=%p (nested %p)\n",
                            pNestedRec->ExceptionCode, pNestedRec->ExceptionFlags, pNestedRec->ExceptionAddress,
                            pNestedRec->ExceptionRecord);
                for (uint32_t i = 0; i < RT_MIN(pNestedRec->NumberParameters, EXCEPTION_MAXIMUM_PARAMETERS); i++)
                    RTLogLogger(pLogger, NULL, "Nested: ExceptionInformation[%d]=%p\n", i, pNestedRec->ExceptionInformation[i]);
                uXcptPC = (uintptr_t)pNestedRec->ExceptionAddress;
            }
        }

        /*
         * Dump the context record.
         */
        volatile char   szMarker[] = "stackmarker";
        uintptr_t       uXcptSP = (uintptr_t)&szMarker[0];
        PCONTEXT pXcptCtx = RT_VALID_PTR(pPtrs) && RT_VALID_PTR(pPtrs->ContextRecord)   ? pPtrs->ContextRecord   : NULL;
        if (pXcptCtx)
        {
#ifdef RT_ARCH_AMD64
            RTLogLogger(pLogger, NULL, "\ncs:rip=%04x:%016RX64\n", pXcptCtx->SegCs, pXcptCtx->Rip);
            RTLogLogger(pLogger, NULL, "ss:rsp=%04x:%016RX64 rbp=%016RX64\n", pXcptCtx->SegSs, pXcptCtx->Rsp, pXcptCtx->Rbp);
            RTLogLogger(pLogger, NULL, "rax=%016RX64 rcx=%016RX64 rdx=%016RX64 rbx=%016RX64\n",
                        pXcptCtx->Rax, pXcptCtx->Rcx, pXcptCtx->Rdx, pXcptCtx->Rbx);
            RTLogLogger(pLogger, NULL, "rsi=%016RX64 rdi=%016RX64 rsp=%016RX64 rbp=%016RX64\n",
                        pXcptCtx->Rsi, pXcptCtx->Rdi, pXcptCtx->Rsp, pXcptCtx->Rbp);
            RTLogLogger(pLogger, NULL, "r8 =%016RX64 r9 =%016RX64 r10=%016RX64 r11=%016RX64\n",
                        pXcptCtx->R8,  pXcptCtx->R9,  pXcptCtx->R10, pXcptCtx->R11);
            RTLogLogger(pLogger, NULL, "r12=%016RX64 r13=%016RX64 r14=%016RX64 r15=%016RX64\n",
                        pXcptCtx->R12,  pXcptCtx->R13,  pXcptCtx->R14, pXcptCtx->R15);
            RTLogLogger(pLogger, NULL, "ds=%04x es=%04x fs=%04x gs=%04x eflags=%08x\n",
                        pXcptCtx->SegDs, pXcptCtx->SegEs, pXcptCtx->SegFs, pXcptCtx->SegGs, pXcptCtx->EFlags);
            RTLogLogger(pLogger, NULL, "p1home=%016RX64 p2home=%016RX64 pe3home=%016RX64\n",
                        pXcptCtx->P1Home, pXcptCtx->P2Home, pXcptCtx->P3Home);
            RTLogLogger(pLogger, NULL, "p4home=%016RX64 p5home=%016RX64 pe6home=%016RX64\n",
                        pXcptCtx->P4Home, pXcptCtx->P5Home, pXcptCtx->P6Home);
            RTLogLogger(pLogger, NULL, "   LastBranchToRip=%016RX64    LastBranchFromRip=%016RX64\n",
                        pXcptCtx->LastBranchToRip, pXcptCtx->LastBranchFromRip);
            RTLogLogger(pLogger, NULL, "LastExceptionToRip=%016RX64 LastExceptionFromRip=%016RX64\n",
                        pXcptCtx->LastExceptionToRip, pXcptCtx->LastExceptionFromRip);
            uXcptSP = pXcptCtx->Rsp;
            uXcptPC = pXcptCtx->Rip;

#elif defined(RT_ARCH_X86)
            RTLogLogger(pLogger, NULL, "\ncs:eip=%04x:%08RX32\n", pXcptCtx->SegCs, pXcptCtx->Eip);
            RTLogLogger(pLogger, NULL, "ss:esp=%04x:%08RX32 ebp=%08RX32\n", pXcptCtx->SegSs, pXcptCtx->Esp, pXcptCtx->Ebp);
            RTLogLogger(pLogger, NULL, "eax=%08RX32 ecx=%08RX32 edx=%08RX32 ebx=%08RX32\n",
                        pXcptCtx->Eax, pXcptCtx->Ecx,  pXcptCtx->Edx,  pXcptCtx->Ebx);
            RTLogLogger(pLogger, NULL, "esi=%08RX32 edi=%08RX32 esp=%08RX32 ebp=%08RX32\n",
                        pXcptCtx->Esi, pXcptCtx->Edi,  pXcptCtx->Esp,  pXcptCtx->Ebp);
            RTLogLogger(pLogger, NULL, "ds=%04x es=%04x fs=%04x gs=%04x eflags=%08x\n",
                        pXcptCtx->SegDs, pXcptCtx->SegEs, pXcptCtx->SegFs, pXcptCtx->SegGs, pXcptCtx->EFlags);
            uXcptSP = pXcptCtx->Esp;
            uXcptPC = pXcptCtx->Eip;
#endif
        }

        /*
         * Dump stack.
         */
        uintptr_t uStack = (uintptr_t)(void *)&szMarker[0];
        uStack -= uStack & 15;

        size_t cbToDump = PAGE_SIZE - (uStack & PAGE_OFFSET_MASK);
        if (cbToDump < 512)
            cbToDump += PAGE_SIZE;
        size_t cbToXcpt = uXcptSP - uStack;
        while (cbToXcpt > cbToDump && cbToXcpt <= _16K)
            cbToDump += PAGE_SIZE;
        ULONG_PTR uLow  = (uintptr_t)&szMarker[0];
        ULONG_PTR uHigh = (uintptr_t)&szMarker[0];
        if (g_pfnGetCurrentThreadStackLimits)
        {
            g_pfnGetCurrentThreadStackLimits(&uLow, &uHigh);
            size_t cbToTop = RT_MAX(uLow, uHigh) - uStack;
            if (cbToTop < _1M)
                cbToDump = cbToTop;
        }

        RTLogLogger(pLogger, NULL, "\nStack %p, dumping %#x bytes (low=%p, high=%p)\n", uStack, cbToDump, uLow, uHigh);
        RTLogLogger(pLogger, NULL, "%.*RhxD\n", cbToDump, uStack);

        /*
         * Try figure the thread name.
         *
         * Note! This involves the thread db lock, so it may deadlock, which
         *       is why it's at the end.
         */
        RTLogLogger(pLogger, NULL,  "Thread ID:   %p\n", RTThreadNativeSelf());
        RTLogLogger(pLogger, NULL,  "Thread name: %s\n", RTThreadSelfName());
        RTLogLogger(pLogger, NULL,  "Thread IPRT: %p\n", RTThreadSelf());

        /*
         * Try dump the load information.
         */
        PPEB pPeb = RTNtCurrentPeb();
        if (RT_VALID_PTR(pPeb))
        {
            PPEB_LDR_DATA pLdrData = pPeb->Ldr;
            if (RT_VALID_PTR(pLdrData))
            {
                PLDR_DATA_TABLE_ENTRY pFound     = NULL;
                LIST_ENTRY * const    pList      = &pLdrData->InMemoryOrderModuleList;
                LIST_ENTRY           *pListEntry = pList->Flink;
                uint32_t              cLoops     = 0;
                RTLogLogger(pLogger, NULL,
                            "\nLoaded Modules:\n"
                            "%-*s[*] Timestamp Path\n", sizeof(void *) * 4 + 2 - 1, "Address range"
                            );
                while (pListEntry != pList && RT_VALID_PTR(pListEntry) && cLoops < 1024)
                {
                    PLDR_DATA_TABLE_ENTRY pLdrEntry = RT_FROM_MEMBER(pListEntry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);
                    uint32_t const        cbLength  = (uint32_t)(uintptr_t)pLdrEntry->Reserved3[1];
                    char                  chInd     = ' ';
                    if (uXcptPC - (uintptr_t)pLdrEntry->DllBase < cbLength)
                    {
                        chInd = '*';
                        pFound = pLdrEntry;
                    }

                    if (   RT_VALID_PTR(pLdrEntry->FullDllName.Buffer)
                        && pLdrEntry->FullDllName.Length > 0
                        && pLdrEntry->FullDllName.Length < _8K
                        && (pLdrEntry->FullDllName.Length & 1) == 0
                        && pLdrEntry->FullDllName.Length <= pLdrEntry->FullDllName.MaximumLength)
                        RTLogLogger(pLogger, NULL, "%p..%p%c  %08RX32  %.*ls\n",
                                    pLdrEntry->DllBase, (uintptr_t)pLdrEntry->DllBase + cbLength - 1, chInd,
                                    pLdrEntry->TimeDateStamp, pLdrEntry->FullDllName.Length / sizeof(RTUTF16),
                                    pLdrEntry->FullDllName.Buffer);
                    else
                        RTLogLogger(pLogger, NULL, "%p..%p%c  %08RX32  <bad or missing: %p LB %#x max %#x\n",
                                    pLdrEntry->DllBase, (uintptr_t)pLdrEntry->DllBase + cbLength - 1, chInd,
                                    pLdrEntry->TimeDateStamp, pLdrEntry->FullDllName.Buffer, pLdrEntry->FullDllName.Length,
                                    pLdrEntry->FullDllName.MaximumLength);

                    /* advance */
                    pListEntry = pListEntry->Flink;
                    cLoops++;
                }

                /*
                 * Use the above to pick out code addresses on the stack.
                 */
                if (   cLoops < 1024
                    && uXcptSP - uStack < cbToDump)
                {
                    RTLogLogger(pLogger, NULL, "\nPotential code addresses on the stack:\n");
                    if (pFound)
                    {
                        if (   RT_VALID_PTR(pFound->FullDllName.Buffer)
                            && pFound->FullDllName.Length > 0
                            && pFound->FullDllName.Length < _8K
                            && (pFound->FullDllName.Length & 1) == 0
                            && pFound->FullDllName.Length <= pFound->FullDllName.MaximumLength)
                            RTLogLogger(pLogger, NULL, "%-*s: %p - %#010RX32 bytes into %.*ls\n",
                                        sizeof(void *) * 2, "Xcpt PC", uXcptPC, (uint32_t)(uXcptPC - (uintptr_t)pFound->DllBase),
                                        pFound->FullDllName.Length / sizeof(RTUTF16), pFound->FullDllName.Buffer);
                        else
                            RTLogLogger(pLogger, NULL, "%-*s: %p - %08RX32 into module at %p\n",
                                        sizeof(void *) * 2, "Xcpt PC", uXcptPC, (uint32_t)(uXcptPC - (uintptr_t)pFound->DllBase),
                                        pFound->DllBase);
                    }

                    uintptr_t const *puStack = (uintptr_t const *)uXcptSP;
                    uintptr_t        cLeft   = (cbToDump - (uXcptSP - uStack)) / sizeof(uintptr_t);
                    while (cLeft-- > 0)
                    {
                        uintptr_t uPtr = *puStack;
                        if (RT_VALID_PTR(uPtr))
                        {
                            /* Search the module table. */
                            pFound     = NULL;
                            cLoops     = 0;
                            pListEntry = pList->Flink;
                            while (pListEntry != pList && RT_VALID_PTR(pListEntry) && cLoops < 1024)
                            {
                                PLDR_DATA_TABLE_ENTRY pLdrEntry = RT_FROM_MEMBER(pListEntry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);
                                uint32_t const        cbLength  = (uint32_t)(uintptr_t)pLdrEntry->Reserved3[1];
                                if (uPtr - (uintptr_t)pLdrEntry->DllBase < cbLength)
                                {
                                    pFound = pLdrEntry;
                                    break;
                                }

                                /* advance */
                                pListEntry = pListEntry->Flink;
                                cLoops++;
                            }

                            if (pFound)
                            {
                                if (   RT_VALID_PTR(pFound->FullDllName.Buffer)
                                    && pFound->FullDllName.Length > 0
                                    && pFound->FullDllName.Length < _8K
                                    && (pFound->FullDllName.Length & 1) == 0
                                    && pFound->FullDllName.Length <= pFound->FullDllName.MaximumLength)
                                    RTLogLogger(pLogger, NULL, "%p: %p - %#010RX32 bytes into %.*ls\n",
                                                puStack, uPtr, (uint32_t)(uPtr - (uintptr_t)pFound->DllBase),
                                                pFound->FullDllName.Length / sizeof(RTUTF16), pFound->FullDllName.Buffer);
                                else
                                    RTLogLogger(pLogger, NULL, "%p: %p - %08RX32 into module at %p\n",
                                                puStack, uPtr, (uint32_t)(uPtr - (uintptr_t)pFound->DllBase), pFound->DllBase);
                            }
                        }

                        puStack++;
                    }
                }
            }
        }
    }

    /*
     * Do the default stuff, never mind us.
     */
    if (g_pfnUnhandledXcptFilter)
        return g_pfnUnhandledXcptFilter(pPtrs);
    return EXCEPTION_CONTINUE_SEARCH;
}