VirtualBox

Changeset 96572 in vbox for trunk/src/VBox


Ignore:
Timestamp:
Sep 1, 2022 8:36:22 PM (2 years ago)
Author:
vboxsync
Message:

HostDrives,Installer/win: Reworked the windows installer related code for no-CRT mode, where applicable, and changed the XxxxInstall.exe/XxxxUninstall.exe utilities to link against VBoxRT.dll instead of being statically linked. Lot's of cleanup. The change is uncomfortably large, but difficult to detangle these things. bugref:10261

Location:
trunk/src/VBox
Files:
1 deleted
23 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/VBox/Devices/Makefile.kmk

    r96407 r96572  
    112112 ifdef VBOX_WITH_VSCSI_SSC
    113113  VBoxDDU_SOURCES        += Storage/VSCSI/VSCSILunSsc.cpp
    114   VBoxDDU_DEFS          += VBOX_WITH_VSCSI_SSC
     114  VBoxDDU_DEFS            += VBOX_WITH_VSCSI_SSC
    115115 endif
    116116 VBoxDDU_LIBS             = \
     
    126126        $(PATH_STAGE_LIB)/USBLib$(VBOX_SUFF_LIB)
    127127  VBoxDDU_LIBS.win       += \
    128         $(PATH_STAGE_LIB)/VBoxDrvCfg$(VBOX_SUFF_LIB)
     128        $(PATH_STAGE_LIB)/VBoxDrvCfgDll$(VBOX_SUFF_LIB)
    129129 endif
    130130 VBoxDDU_LDFLAGS.darwin   = -install_name $(VBOX_DYLD_EXECUTABLE_PATH)/VBoxDDU.dylib
     
    909909
    910910 ifdef VBOX_WITH_NETFLT
    911   VBoxDD_LIBS.win       += $(PATH_STAGE_LIB)/WinNetConfig.lib
     911  VBoxDD_LIBS.win       += $(PATH_STAGE_LIB)/WinNetConfigDll$(VBOX_SUFF_LIB)
    912912 endif
    913913
  • trunk/src/VBox/HostDrivers/VBoxNetFlt/Makefile.kmk

    r96407 r96572  
    243243 # WinNetConfig - static library with host network interface config API (for the installer)
    244244 #
    245  LIBRARIES.win += WinNetConfig
    246  WinNetConfig_TEMPLATE = VBoxR3StaticDllNoAsan
    247  WinNetConfig_SDKS     = ReorderCompilerIncs $(VBOX_WINPSDK) $(VBOX_WINDDK)
    248  WinNetConfig_DEFS     = _WIN32_WINNT=0x0501 _UNICODE UNICODE
    249  WinNetConfig_INCS.win = $(PATH_TOOL_$(VBOX_VCC_TOOL)_INC)
    250  WinNetConfig_SOURCES  = win/cfg/VBoxNetCfg.cpp
    251 
    252  #
    253  # WinNetConfigNonStatic - static library with host network interface config API
    254  #
    255  LIBRARIES.win += WinNetConfigNonStatic
    256  WinNetConfigNonStatic_TEMPLATE = VBoxR3Dll
    257  WinNetConfigNonStatic_SDKS     = ReorderCompilerIncs $(VBOX_WINPSDK) $(VBOX_WINDDK)
    258  WinNetConfigNonStatic_DEFS     = _WIN32_WINNT=0x0501 _UNICODE UNICODE
    259  WinNetConfigNonStatic_INCS.win = $(PATH_TOOL_$(VBOX_VCC_TOOL)_INC)
    260  WinNetConfigNonStatic_SOURCES  = win/cfg/VBoxNetCfg.cpp
     245 LIBRARIES.win += WinNetConfigSharedStatic
     246 WinNetConfigSharedStatic_TEMPLATE = VBoxR3StaticDllNoAsan
     247 WinNetConfigSharedStatic_SDKS     = ReorderCompilerIncs $(VBOX_WINPSDK) $(VBOX_WINDDK)
     248 WinNetConfigSharedStatic_DEFS     = _UNICODE UNICODE
     249 WinNetConfigSharedStatic_SOURCES  = \
     250        win/cfg/VBoxNetCfg.cpp \
     251       ../../Main/glue/string.cpp
     252
     253 # Version for DLLs:
     254 LIBRARIES.win += WinNetConfigDll
     255 WinNetConfigDll_TEMPLATE = VBoxR3Dll
     256 WinNetConfigDll_EXTENDS  = WinNetConfigSharedStatic
     257
     258 # Version for EXEs:
     259 LIBRARIES.win += WinNetConfigExe
     260 WinNetConfigExe_TEMPLATE = VBOXR3EXE
     261 WinNetConfigExe_EXTENDS  = WinNetConfigSharedStatic
    261262
    262263
     
    265266 #
    266267 TEMPLATE_VBoxNetFltR3 = Template for NetFltInstall, NetFltUninstall, NetAdpInstall, NetAdpUninstall, ++
    267  TEMPLATE_VBoxNetFltR3_EXTENDS  = VBOXR3STATIC
    268  TEMPLATE_VBoxNetFltR3_SDKS     = $(TEMPLATE_VBOXR3STATIC_SDKS) ReorderCompilerIncs $(VBOX_WINPSDK) $(VBOX_WINDDK) VBOX_NTDLL VBOX_WIN_NEWDEV
    269  TEMPLATE_VBoxNetFltR3_CXXFLAGS = $(TEMPLATE_VBOXR3STATIC_CXXFLAGS) -Gz
    270  TEMPLATE_VBoxNetFltR3_CFLAGS   = $(TEMPLATE_VBOXR3STATIC_CFLAGS) -Gz
    271  TEMPLATE_VBoxNetFltR3_LIBS     = $(TEMPLATE_VBOXR3STATIC_LIBS) \
    272         $(WinNetConfig_1_TARGET) \
    273         $(PATH_STAGE_LIB)/VBoxDrvCfg$(VBOX_SUFF_LIB) \
     268 TEMPLATE_VBoxNetFltR3_EXTENDS  = VBOXR3EXE
     269 TEMPLATE_VBoxNetFltR3_SDKS     = $(TEMPLATE_VBOXR3EXE_SDKS) ReorderCompilerIncs $(VBOX_WINPSDK) $(VBOX_WINDDK) VBOX_NTDLL VBOX_WIN_NEWDEV
     270 TEMPLATE_VBoxNetFltR3_LIBS     = $(TEMPLATE_VBOXR3EXE_LIBS) \
     271        $(WinNetConfigExe_1_TARGET) \
     272        $(PATH_STAGE_LIB)/VBoxDrvCfgExe$(VBOX_SUFF_LIB) \
     273       $(LIB_RUNTIME) \
    274274        $(PATH_TOOL_$(VBOX_VCC_TOOL)_LIB)/comsupp.lib \
    275275        $(PATH_SDK_$(VBOX_WINPSDK)_LIB)/WbemUuid.Lib
     
    343343 endif
    344344 VBoxNetFltNobj_SDKS       = ReorderCompilerIncs $(VBOX_WINPSDK) $(VBOX_WINDDK)
    345  VBoxNetFltNobj_DEFS       = _WIN32_WINNT=0x0500 WIN32 _ATL_STATIC_REGISTRY
     345 VBoxNetFltNobj_DEFS       = WIN32 _ATL_STATIC_REGISTRY
    346346 VBoxNetFltNobj_INCS       = \
    347347        $(VBoxNetFltNobj_0_OUTDIR)
  • trunk/src/VBox/HostDrivers/VBoxNetFlt/win/cfg/VBoxNetCfg.cpp

    r96407 r96572  
    33 * VBoxNetCfg.cpp - Network Configuration API.
    44 */
     5
    56/*
    67 * Copyright (C) 2011-2022 Oracle and/or its affiliates.
     
    3334 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
    3435 */
     36
     37
     38/*********************************************************************************************************************************
     39*   Header Files                                                                                                                 *
     40*********************************************************************************************************************************/
     41#define _WIN32_DCOM
     42
    3543#include "VBox/VBoxNetCfg-win.h"
    3644#include "VBox/VBoxDrvCfg-win.h"
    3745
    38 #define _WIN32_DCOM
    39 
    4046#include <devguid.h>
    41 #include <stdio.h>
    4247#include <regstr.h>
    4348#include <iprt/win/shlobj.h>
    4449#include <cfgmgr32.h>
    45 #include <tchar.h>
    4650#include <iprt/win/objbase.h>
    4751
    48 #include <crtdbg.h>
    49 #include <stdlib.h>
    50 #include <string.h>
    51 
    5252#include <Wbemidl.h>
    53 #include <comutil.h>
    5453
    5554#include <iprt/win/winsock2.h>
     
    5958#include <iprt/win/iphlpapi.h>
    6059
    61 #include <set>
    62 
     60#include <iprt/asm.h>
     61#include <iprt/assertcompile.h>
     62#include <iprt/mem.h>
     63#include <iprt/list.h>
     64#include <iprt/rand.h>
     65#include <iprt/string.h>
     66#include <iprt/utf16.h>
     67#include <VBox/com/string.h>
     68
     69
     70/*********************************************************************************************************************************
     71*   Defined Constants And Macros                                                                                                 *
     72*********************************************************************************************************************************/
    6373#ifndef Assert   /** @todo r=bird: where would this be defined? */
    6474//# ifdef DEBUG
     
    7080# define AssertMsg(expr, msg) do{}while (0)
    7181#endif
     82
     83#define NonStandardLog              DoLogging
     84#define NonStandardLogFlow(x)       DoLogging x
     85
     86#define SetErrBreak(strAndArgs) \
     87    if (1) { \
     88        hrc = E_FAIL; \
     89        NonStandardLog strAndArgs; \
     90        bstrError.printfNoThrow strAndArgs; \
     91        break; \
     92    } else do {} while (0)
     93
     94
     95#define VBOXNETCFGWIN_NETADP_ID_SZ  "sun_VBoxNetAdp"
     96#define VBOXNETCFGWIN_NETADP_ID_WSZ RT_CONCAT(L,VBOXNETCFGWIN_NETADP_ID_SZ)
     97#define DRIVERHWID                  VBOXNETCFGWIN_NETADP_ID_WSZ
     98
     99/* We assume the following name matches the device description in vboxnetadp6.inf */
     100#define HOSTONLY_ADAPTER_NAME_SZ    "VirtualBox Host-Only Ethernet Adapter"
     101#define HOSTONLY_ADAPTER_NAME_WSZ   RT_CONCAT(L,HOSTONLY_ADAPTER_NAME_SZ)
     102
     103#define VBOX_CONNECTION_NAME_SZ     "VirtualBox Host-Only Network"
     104#define VBOX_CONNECTION_NAME_WSZ    RT_CONCAT(L,VBOX_CONNECTION_NAME_SZ)
     105
     106#define VBOXNETCFGWIN_NETLWF_ID     L"oracle_VBoxNetLwf"
     107
     108
     109
     110/*********************************************************************************************************************************
     111*   Global Variables                                                                                                             *
     112*********************************************************************************************************************************/
    72113static PFNVBOXNETCFGLOGGER volatile g_pfnLogger = NULL;
    73114
    74 static void DoLogging(const char *pszString, ...);
    75 #define NonStandardLog DoLogging
    76 #define NonStandardLogFlow(x) DoLogging x
    77 
    78 #define DbgLog                              /** @todo r=bird: What does this do? */
    79 
    80 #define VBOX_NETCFG_LOCK_TIME_OUT     5000  /** @todo r=bird: What does this do? */
    81 
    82 #define VBOXNETCFGWIN_NETADP_ID L"sun_VBoxNetAdp"
    83 
    84115/*
    85 * Wrappers for HelpAPI functions
    86 */
     116 * Wrappers for HelpAPI functions
     117 */
    87118typedef void FNINITIALIZEIPINTERFACEENTRY( _Inout_ PMIB_IPINTERFACE_ROW row);
    88119typedef FNINITIALIZEIPINTERFACEENTRY *PFNINITIALIZEIPINTERFACEENTRY;
     
    94125typedef FNSETIPINTERFACEENTRY *PFNSETIPINTERFACEENTRY;
    95126
    96 static  PFNINITIALIZEIPINTERFACEENTRY   g_pfnInitializeIpInterfaceEntry = NULL;
    97 static  PFNGETIPINTERFACEENTRY          g_pfnGetIpInterfaceEntry        = NULL;
    98 static  PFNSETIPINTERFACEENTRY          g_pfnSetIpInterfaceEntry        = NULL;
    99 
     127
     128/*********************************************************************************************************************************
     129*   Internal Functions                                                                                                           *
     130*********************************************************************************************************************************/
     131static PFNINITIALIZEIPINTERFACEENTRY    g_pfnInitializeIpInterfaceEntry = NULL;
     132static PFNGETIPINTERFACEENTRY           g_pfnGetIpInterfaceEntry        = NULL;
     133static PFNSETIPINTERFACEENTRY           g_pfnSetIpInterfaceEntry        = NULL;
     134
     135static void DoLogging(const char *pszString, ...);
    100136
    101137/*
    102 * Forward declaration for using vboxNetCfgWinSetupMetric()
    103 */
    104 HRESULT vboxNetCfgWinSetupMetric(IN NET_LUID* pLuid);
    105 HRESULT vboxNetCfgWinGetInterfaceLUID(IN HKEY hKey, OUT NET_LUID* pLUID);
    106 
    107 
    108 /*
    109  * For some weird reason we do not want to use IPRT here, hence the following
    110  * function provides a replacement for BstrFmt.
     138 * Forward declaration for using vboxNetCfgWinSetupMetric()
    111139 */
    112 static bstr_t bstr_printf(const char *cszFmt, ...)
    113 {
    114     char szBuffer[4096];
    115     szBuffer[sizeof(szBuffer) - 1] = 0; /* Make sure the string will be null-terminated */
    116     va_list va;
    117     va_start(va, cszFmt);
    118     _vsnprintf(szBuffer, sizeof(szBuffer) - 1, cszFmt, va);
    119     va_end(va);
    120     return bstr_t(szBuffer);
    121 }
     140static HRESULT vboxNetCfgWinSetupMetric(IN NET_LUID *pLuid);
     141static HRESULT vboxNetCfgWinGetInterfaceLUID(IN HKEY hKey, OUT NET_LUID *pLUID);
     142
     143
    122144
    123145static HRESULT vboxNetCfgWinINetCfgLock(IN INetCfg *pNetCfg,
     
    127149{
    128150    INetCfgLock *pLock;
    129     HRESULT hr = pNetCfg->QueryInterface(IID_INetCfgLock, (PVOID*)&pLock);
     151    HRESULT hr = pNetCfg->QueryInterface(IID_INetCfgLock, (PVOID *)&pLock);
    130152    if (FAILED(hr))
    131153    {
    132         NonStandardLogFlow(("QueryInterface failed, hr (0x%x)\n", hr));
     154        NonStandardLogFlow(("QueryInterface failed: %Rhrc\n", hr));
    133155        return hr;
    134156    }
     
    136158    hr = pLock->AcquireWriteLock(cmsTimeout, pszwClientDescription, ppszwClientDescription);
    137159    if (hr == S_FALSE)
    138     {
    139160        NonStandardLogFlow(("Write lock busy\n"));
    140     }
    141161    else if (FAILED(hr))
    142     {
    143         NonStandardLogFlow(("AcquireWriteLock failed, hr (0x%x)\n", hr));
    144     }
     162        NonStandardLogFlow(("AcquireWriteLock failed: %Rhrc\n", hr));
    145163
    146164    pLock->Release();
     
    151169{
    152170    INetCfgLock *pLock;
    153     HRESULT hr = pNetCfg->QueryInterface(IID_INetCfgLock, (PVOID*)&pLock);
     171    HRESULT hr = pNetCfg->QueryInterface(IID_INetCfgLock, (PVOID *)&pLock);
    154172    if (FAILED(hr))
    155173    {
    156         NonStandardLogFlow(("QueryInterface failed, hr (0x%x)\n", hr));
     174        NonStandardLogFlow(("QueryInterface failed: %Rhrc\n", hr));
    157175        return hr;
    158176    }
     
    160178    hr = pLock->ReleaseWriteLock();
    161179    if (FAILED(hr))
    162         NonStandardLogFlow(("ReleaseWriteLock failed, hr (0x%x)\n", hr));
     180        NonStandardLogFlow(("ReleaseWriteLock failed: %Rhrc\n", hr));
    163181
    164182    pLock->Release();
     
    172190                                                      OUT LPWSTR *ppszwClientDescription)
    173191{
    174     INetCfg *pNetCfg;
    175     HRESULT hr = CoCreateInstance(CLSID_CNetCfg, NULL, CLSCTX_INPROC_SERVER, IID_INetCfg, (PVOID*)&pNetCfg);
     192    INetCfg *pNetCfg = NULL;
     193    HRESULT hr = CoCreateInstance(CLSID_CNetCfg, NULL, CLSCTX_INPROC_SERVER, IID_INetCfg, (PVOID *)&pNetCfg);
    176194    if (FAILED(hr))
    177195    {
    178         NonStandardLogFlow(("CoCreateInstance failed, hr (0x%x)\n", hr));
     196        NonStandardLogFlow(("CoCreateInstance failed: %Rhrc\n", hr));
    179197        return hr;
    180198    }
     
    198216            return S_OK;
    199217        }
    200         else
    201             NonStandardLogFlow(("Initialize failed, hr (0x%x)\n", hr));
     218        NonStandardLogFlow(("Initialize failed: %Rhrc\n", hr));
    202219    }
    203220
     
    217234    if (FAILED(hr))
    218235    {
    219         NonStandardLogFlow(("Uninitialize failed, hr (0x%x)\n", hr));
     236        NonStandardLogFlow(("Uninitialize failed: %Rhrc\n", hr));
    220237        /* Try to release the write lock below. */
    221238    }
     
    225242        HRESULT hr2 = vboxNetCfgWinINetCfgUnlock(pNetCfg);
    226243        if (FAILED(hr2))
    227             NonStandardLogFlow(("vboxNetCfgWinINetCfgUnlock failed, hr (0x%x)\n", hr2));
     244            NonStandardLogFlow(("vboxNetCfgWinINetCfgUnlock failed: %Rhrc\n", hr2));
    228245        if (SUCCEEDED(hr))
    229246            hr = hr2;
     
    241258    if (FAILED(hr))
    242259    {
    243         NonStandardLogFlow(("Reset failed, hr (0x%x)\n", hr));
     260        NonStandardLogFlow(("Reset failed: %Rhrc\n", hr));
    244261        return hr;
    245262    }
    246263
    247     INetCfgComponent *pNcc;
     264    INetCfgComponent *pNcc = NULL;
    248265    while ((hr = pEnumNcc->Next(1, &pNcc, NULL)) == S_OK)
    249266    {
    250         ULONG uComponentStatus;
     267        ULONG uComponentStatus = 0;
    251268        hr = pNcc->GetDeviceStatus(&uComponentStatus);
    252269        if (SUCCEEDED(hr))
     
    267284                }
    268285                else
    269                     NonStandardLogFlow(("GetInstanceGuid failed, hr (0x%x)\n", hr));
     286                    NonStandardLogFlow(("GetInstanceGuid failed: %Rhrc\n", hr));
    270287            }
    271288        }
     
    281298                                                            OUT INetCfgComponent **ppncc)
    282299{
    283     IEnumNetCfgComponent *pEnumNcc;
     300    IEnumNetCfgComponent *pEnumNcc = NULL;
    284301    HRESULT hr = pNc->EnumComponents(pguidClass, &pEnumNcc);
    285 
    286302    if (SUCCEEDED(hr))
    287303    {
    288304        hr = vboxNetCfgWinGetComponentByGuidEnum(pEnumNcc, pComponentGuid, ppncc);
    289305        if (hr == S_FALSE)
    290         {
    291306            NonStandardLogFlow(("Component not found\n"));
    292         }
    293307        else if (FAILED(hr))
    294         {
    295             NonStandardLogFlow(("vboxNetCfgWinGetComponentByGuidEnum failed, hr (0x%x)\n", hr));
    296         }
     308            NonStandardLogFlow(("vboxNetCfgWinGetComponentByGuidEnum failed: %Rhrc\n", hr));
    297309        pEnumNcc->Release();
    298310    }
    299311    else
    300         NonStandardLogFlow(("EnumComponents failed, hr (0x%x)\n", hr));
     312        NonStandardLogFlow(("EnumComponents failed: %Rhrc\n", hr));
    301313    return hr;
    302314}
     
    304316static HRESULT vboxNetCfgWinQueryInstaller(IN INetCfg *pNetCfg, IN const GUID *pguidClass, INetCfgClassSetup **ppSetup)
    305317{
    306     HRESULT hr = pNetCfg->QueryNetCfgClass(pguidClass, IID_INetCfgClassSetup, (void**)ppSetup);
     318    HRESULT hr = pNetCfg->QueryNetCfgClass(pguidClass, IID_INetCfgClassSetup, (void **)ppSetup);
    307319    if (FAILED(hr))
    308         NonStandardLogFlow(("QueryNetCfgClass failed, hr (0x%x)\n", hr));
    309     return hr;
    310 }
    311 
    312 VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinInstallComponent(IN INetCfg *pNetCfg, IN LPCWSTR pszwComponentId, IN const GUID *pguidClass,
    313                                                           OUT INetCfgComponent **ppComponent)
     320        NonStandardLogFlow(("QueryNetCfgClass failed: %Rhrc\n", hr));
     321    return hr;
     322}
     323
     324VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinInstallComponent(IN INetCfg *pNetCfg, IN LPCWSTR pszwComponentId,
     325                                                          IN const GUID *pguidClass, OUT INetCfgComponent **ppComponent)
    314326{
    315327    INetCfgClassSetup *pSetup;
     
    317329    if (FAILED(hr))
    318330    {
    319         NonStandardLogFlow(("vboxNetCfgWinQueryInstaller failed, hr (0x%x)\n", hr));
     331        NonStandardLogFlow(("vboxNetCfgWinQueryInstaller failed: %Rhrc\n", hr));
    320332        return hr;
    321333    }
    322334
    323335    OBO_TOKEN Token;
    324     ZeroMemory(&Token, sizeof (Token));
     336    RT_ZERO(Token);
    325337    Token.Type = OBO_USER;
    326     INetCfgComponent* pTempComponent = NULL;
    327 
     338
     339    INetCfgComponent *pTempComponent = NULL;
    328340    hr = pSetup->Install(pszwComponentId, &Token,
    329341                         0,    /* IN DWORD dwSetupFlags */
     
    336348        if (pTempComponent != NULL)
    337349        {
    338             HKEY hkey = (HKEY)INVALID_HANDLE_VALUE;
    339             HRESULT res;
    340 
    341350            /*
    342             *   Set default metric value of interface to fix multicast issue
    343             *   See @bugref{6379} for details.
    344             */
    345             res = pTempComponent->OpenParamKey(&hkey);
     351             *   Set default metric value of interface to fix multicast issue
     352             *   See @bugref{6379} for details.
     353             */
     354            HKEY    hKey = (HKEY)INVALID_HANDLE_VALUE;
     355            HRESULT hrc2 = pTempComponent->OpenParamKey(&hKey);
    346356
    347357            /* Set default metric value for host-only interface only */
    348             if (   SUCCEEDED(res)
    349                 && hkey != INVALID_HANDLE_VALUE
    350                 && wcsnicmp(pszwComponentId, VBOXNETCFGWIN_NETADP_ID, 256) == 0)
     358            if (   SUCCEEDED(hrc2)
     359                && hKey != (HKEY)INVALID_HANDLE_VALUE
     360                /* Original was weird: && wcsnicmp(pszwComponentId, VBOXNETCFGWIN_NETADP_ID_WSZ, 256) == 0) */
     361                && RTUtf16ICmpAscii(pszwComponentId, VBOXNETCFGWIN_NETADP_ID_SZ) == 0)
    351362            {
    352363                NET_LUID luid;
    353                 res = vboxNetCfgWinGetInterfaceLUID(hkey, &luid);
     364                hrc2 = vboxNetCfgWinGetInterfaceLUID(hKey, &luid);
    354365
    355366                /* Close the key as soon as possible. See @bugref{7973}. */
    356                 RegCloseKey (hkey);
    357                 hkey = (HKEY)INVALID_HANDLE_VALUE;
    358 
    359                 if (FAILED(res))
     367                RegCloseKey(hKey);
     368                hKey = (HKEY)INVALID_HANDLE_VALUE;
     369
     370                if (FAILED(hrc2))
    360371                {
    361372                    /*
     
    363374                     *   So we will not break installation process due to this error.
    364375                     */
    365                     NonStandardLogFlow(("VBoxNetCfgWinInstallComponent Warning! "
    366                                         "vboxNetCfgWinGetInterfaceLUID failed, default metric "
    367                                         "for new interface will not be set, hr (0x%x)\n", res));
     376                    NonStandardLogFlow(("VBoxNetCfgWinInstallComponent Warning! vboxNetCfgWinGetInterfaceLUID failed, default metric for new interface will not be set: %Rhrc\n", hrc2));
    368377                }
    369378                else
    370379                {
    371                     res = vboxNetCfgWinSetupMetric(&luid);
    372                     if (FAILED(res))
     380                    hrc2 = vboxNetCfgWinSetupMetric(&luid);
     381                    if (FAILED(hrc2))
    373382                    {
    374383                        /*
     
    376385                         *   So we will not break installation process due to this error.
    377386                         */
    378                         NonStandardLogFlow(("VBoxNetCfgWinInstallComponent Warning! "
    379                                             "vboxNetCfgWinSetupMetric failed, default metric "
    380                                             "for new interface will not be set, hr (0x%x)\n", res));
     387                        NonStandardLogFlow(("VBoxNetCfgWinInstallComponent Warning! vboxNetCfgWinSetupMetric failed, default metric for new interface will not be set: %Rhrc\n", hrc2));
    381388                    }
    382389                }
    383390            }
    384             if (hkey != INVALID_HANDLE_VALUE)
    385             {
    386                 RegCloseKey (hkey);
    387                 hkey = (HKEY)INVALID_HANDLE_VALUE;
    388             }
     391            if (hKey != (HKEY)INVALID_HANDLE_VALUE)
     392                RegCloseKey(hKey);
    389393            if (ppComponent != NULL)
    390394                *ppComponent = pTempComponent;
     
    394398
    395399        /* ignore the apply failure */
    396         HRESULT tmpHr = pNetCfg->Apply();
    397         Assert(tmpHr == S_OK);
    398         if (tmpHr != S_OK)
    399             NonStandardLogFlow(("Apply failed, hr (0x%x)\n", tmpHr));
     400        HRESULT hrc3 = pNetCfg->Apply();
     401        Assert(hrc3 == S_OK);
     402        if (hrc3 != S_OK)
     403            NonStandardLogFlow(("Apply failed: %Rhrc\n", hrc3));
    400404    }
    401405    else
    402         NonStandardLogFlow(("Install failed, hr (0x%x)\n", hr));
     406        NonStandardLogFlow(("Install failed: %Rhrc\n", hr));
    403407
    404408    pSetup->Release();
     
    407411
    408412static HRESULT vboxNetCfgWinInstallInfAndComponent(IN INetCfg *pNetCfg, IN LPCWSTR pszwComponentId, IN const GUID *pguidClass,
    409                                                    IN LPCWSTR const *apInfPaths, IN UINT cInfPaths,
     413                                                   IN LPCWSTR const *apwszInfPaths, IN UINT cInfPaths,
    410414                                                   OUT INetCfgComponent **ppComponent)
    411415{
    412     HRESULT hr = S_OK;
    413     UINT cFilesProcessed = 0;
    414 
    415416    NonStandardLogFlow(("Installing %u INF files ...\n", cInfPaths));
    416417
     418    HRESULT hr              = S_OK;
     419    UINT    cFilesProcessed = 0;
    417420    for (; cFilesProcessed < cInfPaths; cFilesProcessed++)
    418421    {
    419         NonStandardLogFlow(("Installing INF file \"%ws\" ...\n", apInfPaths[cFilesProcessed]));
    420         hr = VBoxDrvCfgInfInstall(apInfPaths[cFilesProcessed]);
     422        NonStandardLogFlow(("Installing INF file \"%ls\" ...\n", apwszInfPaths[cFilesProcessed]));
     423        hr = VBoxDrvCfgInfInstall(apwszInfPaths[cFilesProcessed]);
    421424        if (FAILED(hr))
    422425        {
    423             NonStandardLogFlow(("VBoxNetCfgWinInfInstall failed, hr (0x%x)\n", hr));
     426            NonStandardLogFlow(("VBoxNetCfgWinInfInstall failed: %Rhrc\n", hr));
    424427            break;
    425428        }
     
    430433        hr = VBoxNetCfgWinInstallComponent(pNetCfg, pszwComponentId, pguidClass, ppComponent);
    431434        if (FAILED(hr))
    432             NonStandardLogFlow(("VBoxNetCfgWinInstallComponent failed, hr (0x%x)\n", hr));
     435            NonStandardLogFlow(("VBoxNetCfgWinInstallComponent failed: %Rhrc\n", hr));
    433436    }
    434437
     
    439442        do
    440443        {
    441             HRESULT hr2 = VBoxDrvCfgInfUninstall(apInfPaths[cFilesProcessed], 0);
     444            HRESULT hr2 = VBoxDrvCfgInfUninstall(apwszInfPaths[cFilesProcessed], 0);
    442445            if (FAILED(hr2))
    443                 NonStandardLogFlow(("VBoxDrvCfgInfUninstall failed, hr (0x%x)\n", hr2));
     446                NonStandardLogFlow(("VBoxDrvCfgInfUninstall failed: %Rhrc\n", hr2));
    444447                /* Keep going. */
    445448            if (!cFilesProcessed)
     
    459462    if (FAILED(hr))
    460463    {
    461         NonStandardLogFlow(("GetClassGuid failed, hr (0x%x)\n", hr));
     464        NonStandardLogFlow(("GetClassGuid failed: %Rhrc\n", hr));
    462465        return hr;
    463466    }
     
    467470    if (FAILED(hr))
    468471    {
    469         NonStandardLogFlow(("vboxNetCfgWinQueryInstaller failed, hr (0x%x)\n", hr));
     472        NonStandardLogFlow(("vboxNetCfgWinQueryInstaller failed: %Rhrc\n", hr));
    470473        return hr;
    471474    }
    472475
    473476    OBO_TOKEN Token;
    474     ZeroMemory(&Token, sizeof(Token));
     477    RT_ZERO(Token);
    475478    Token.Type = OBO_USER;
    476479
     
    480483        hr = pNetCfg->Apply();
    481484        if (FAILED(hr))
    482             NonStandardLogFlow(("Apply failed, hr (0x%x)\n", hr));
     485            NonStandardLogFlow(("Apply failed: %Rhrc\n", hr));
    483486    }
    484487    else
    485         NonStandardLogFlow(("DeInstall failed, hr (0x%x)\n", hr));
     488        NonStandardLogFlow(("DeInstall failed: %Rhrc\n", hr));
    486489
    487490    if (pSetup)
     
    490493}
    491494
    492 typedef BOOL (*VBOXNETCFGWIN_NETCFGENUM_CALLBACK) (IN INetCfg *pNetCfg, IN INetCfgComponent *pNetCfgComponent, PVOID pContext);
     495typedef BOOL (*PFN_VBOXNETCFGWIN_NETCFGENUM_CALLBACK_T)(IN INetCfg *pNetCfg, IN INetCfgComponent *pNetCfgComponent,
     496                                                        PVOID pvContext);
    493497
    494498static HRESULT vboxNetCfgWinEnumNetCfgComponents(IN INetCfg *pNetCfg,
    495499                                                 IN const GUID *pguidClass,
    496                                                  VBOXNETCFGWIN_NETCFGENUM_CALLBACK callback,
     500                                                 PFN_VBOXNETCFGWIN_NETCFGENUM_CALLBACK_T pfnCallback,
    497501                                                 PVOID pContext)
    498502{
    499     IEnumNetCfgComponent *pEnumComponent;
     503    IEnumNetCfgComponent *pEnumComponent = NULL;
    500504    HRESULT hr = pNetCfg->EnumComponents(pguidClass, &pEnumComponent);
    501505    if (SUCCEEDED(hr))
     
    503507        INetCfgComponent *pNetCfgComponent;
    504508        hr = pEnumComponent->Reset();
    505         do
     509        for (;;)
    506510        {
    507511            hr = pEnumComponent->Next(1, &pNetCfgComponent, NULL);
     
    514518                if (pNetCfgComponent)
    515519                {
    516                     if (pContext)
    517                         fResult = callback(pNetCfg, pNetCfgComponent, pContext);
     520                    fResult = pfnCallback(pNetCfg, pNetCfgComponent, pContext);
    518521                    pNetCfgComponent->Release();
    519522                }
     
    525528            {
    526529                if (hr == S_FALSE)
    527                 {
    528                     hr = S_OK;
    529                 }
     530                    hr = S_OK; /* no more components */
    530531                else
    531                     NonStandardLogFlow(("Next failed, hr (0x%x)\n", hr));
     532                    NonStandardLogFlow(("Next failed: %Rhrc\n", hr));
    532533                break;
    533534            }
    534         } while (true);
     535        }
    535536        pEnumComponent->Release();
    536537    }
     
    538539}
    539540
    540 /*
    541  * Forward declarations of functions used in vboxNetCfgWinRemoveAllNetDevicesOfIdCallback.
    542  */
    543 VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinGenHostonlyConnectionName(PCWSTR DevName, WCHAR *pBuf, PULONG pcbBuf);
    544 VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinRenameConnection(LPWSTR pGuid, PCWSTR NewName);
    545 
     541/** PFNVBOXNETCFGWINNETENUMCALLBACK */
    546542static BOOL vboxNetCfgWinRemoveAllNetDevicesOfIdCallback(HDEVINFO hDevInfo, PSP_DEVINFO_DATA pDev, PVOID pvContext)
    547543{
    548544    RT_NOREF1(pvContext);
     545
    549546    SP_REMOVEDEVICE_PARAMS rmdParams;
    550     memset(&rmdParams, 0, sizeof(SP_REMOVEDEVICE_PARAMS));
     547    RT_ZERO(rmdParams);
    551548    rmdParams.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER);
    552549    rmdParams.ClassInstallHeader.InstallFunction = DIF_REMOVE;
     
    567564                                             KEY_READ);
    568565            if (hKey == INVALID_HANDLE_VALUE)
    569             {
    570                 NonStandardLogFlow(("vboxNetCfgWinRemoveAllNetDevicesOfIdCallback: SetupDiOpenDevRegKey failed with error %ld\n",
     566                NonStandardLogFlow(("vboxNetCfgWinRemoveAllNetDevicesOfIdCallback: SetupDiOpenDevRegKey failed with error %u\n",
    571567                                    GetLastError()));
    572             }
    573568            else
    574569            {
    575570                WCHAR wszCfgGuidString[50] = { L'' };
    576                 DWORD cbSize = sizeof(wszCfgGuidString);
    577                 DWORD dwValueType;
    578                 DWORD ret = RegQueryValueExW(hKey, L"NetCfgInstanceId", NULL,
    579                                              &dwValueType, (LPBYTE)wszCfgGuidString, &cbSize);
    580                 if (ret == ERROR_SUCCESS)
    581                 {
    582                     NonStandardLogFlow(("vboxNetCfgWinRemoveAllNetDevicesOfIdCallback: Processing device ID \"%S\"\n",
    583                                         wszCfgGuidString));
    584 
    585                     /* Figure out device name. */
    586                     WCHAR wszDevName[256], wszTempName[256];
    587                     ULONG cbName = sizeof(wszTempName);
    588 
    589                     if (SetupDiGetDeviceRegistryPropertyW(hDevInfo, pDev,
    590                                                           SPDRP_FRIENDLYNAME, /* IN  DWORD Property,*/
    591                                                           NULL,               /* OUT PDWORD PropertyRegDataType, OPTIONAL*/
    592                                                           (PBYTE)wszDevName,  /* OUT PBYTE PropertyBuffer,*/
    593                                                           sizeof(wszDevName), /* IN  DWORD PropertyBufferSize,*/
    594                                                           NULL                /* OUT PDWORD RequiredSize OPTIONAL*/))
     571                DWORD cbSize = sizeof(wszCfgGuidString) - sizeof(WCHAR); /* make sure we get a terminated string back */
     572                DWORD dwValueType = 0;
     573                LSTATUS lrc = RegQueryValueExW(hKey, L"NetCfgInstanceId", NULL, &dwValueType, (LPBYTE)wszCfgGuidString, &cbSize);
     574                if (lrc == ERROR_SUCCESS)
     575                {
     576                    /** @todo r=bird: original didn't check the type here, just assumed it was a
     577                     * valid zero terminated string. (zero term handled by -sizeof(WHCAR) above now). */
     578                    if (dwValueType == REG_SZ || dwValueType == REG_EXPAND_SZ || dwValueType == REG_EXPAND_SZ)
    595579                    {
    596                         /*
    597                          * Rename the connection before removing the device. This will
    598                          * hopefully prevent an error when we will be attempting
    599                          * to rename a newly created connection (see @bugref{6740}).
    600                          */
    601                         HRESULT hr = VBoxNetCfgWinGenHostonlyConnectionName(wszDevName, wszTempName, &cbName);
    602                         wcscat_s(wszTempName, sizeof(wszTempName), L" removed");
    603                         if (SUCCEEDED(hr))
    604                             hr = VBoxNetCfgWinRenameConnection(wszCfgGuidString, wszTempName);
    605                         //NonStandardLogFlow(("VBoxNetCfgWinRenameConnection(%S,%S) => 0x%x\n", pWCfgGuidString, TempName, hr_tmp));
     580                        NonStandardLogFlow(("vboxNetCfgWinRemoveAllNetDevicesOfIdCallback: Processing device ID \"%ls\"\n",
     581                                            wszCfgGuidString));
     582
     583                        /* Figure out device name. */
     584                        WCHAR wszDevName[256 + 1] = {0};
     585                        if (SetupDiGetDeviceRegistryPropertyW(hDevInfo, pDev, SPDRP_FRIENDLYNAME, NULL, (PBYTE)wszDevName,
     586                                                              sizeof(wszDevName) - sizeof(WCHAR) /* yes, in bytes */, NULL))
     587                        {
     588                            /*
     589                             * Rename the connection before removing the device. This will
     590                             * hopefully prevent an error when we will be attempting
     591                             * to rename a newly created connection (see @bugref{6740}).
     592                             */
     593                            WCHAR wszNewName[RT_ELEMENTS(wszDevName) + 128 /* ensure sufficient buffer */];
     594                            HRESULT hr = VBoxNetCfgWinGenHostonlyConnectionName(wszDevName, wszNewName,
     595                                                                                RT_ELEMENTS(wszNewName) - 10 /*removed++*/,
     596                                                                                NULL);
     597                            RTUtf16CatAscii(wszNewName, sizeof(wszNewName), " removed");
     598                            if (SUCCEEDED(hr))
     599                                hr = VBoxNetCfgWinRenameConnection(wszCfgGuidString, wszNewName);
     600                            //NonStandardLogFlow(("VBoxNetCfgWinRenameConnection(%S,%S) => 0x%x\n", wszCfgGuidString, TempName, hr_tmp));
     601                        }
     602                        else
     603                            NonStandardLogFlow(("vboxNetCfgWinRemoveAllNetDevicesOfIdCallback: Failed to get friendly name for device \"%ls\"\n",
     604                                                wszCfgGuidString));
    606605                    }
    607606                    else
    608                     {
    609                         NonStandardLogFlow(("vboxNetCfgWinRemoveAllNetDevicesOfIdCallback: Failed to get friendly name for device \"%S\"\n",
    610                                             wszCfgGuidString));
    611                     }
     607                        NonStandardLogFlow(("vboxNetCfgWinRemoveAllNetDevicesOfIdCallback: Friendly name for \"%S\" isn't a string: %d\n",
     608                                            wszCfgGuidString, dwValueType
    612609                }
    613610                else
    614                 {
    615                     NonStandardLogFlow(("vboxNetCfgWinRemoveAllNetDevicesOfIdCallback: Querying instance ID failed with %d\n",
    616                                         ret));
    617                 }
     611                    NonStandardLogFlow(("vboxNetCfgWinRemoveAllNetDevicesOfIdCallback: Querying instance ID failed with %u (%#x)\n",
     612                                        lrc, lrc));
    618613
    619614                RegCloseKey(hKey);
     
    623618            if (SetupDiCallClassInstaller(DIF_REMOVE, hDevInfo, pDev))
    624619            {
    625                 SP_DEVINSTALL_PARAMS devParams;
    626                 memset(&devParams, 0, sizeof(SP_DEVINSTALL_PARAMS));
    627                 devParams.cbSize = sizeof(devParams);
    628 
    629                 if (SetupDiGetDeviceInstallParams(hDevInfo, pDev, &devParams))
    630                 {
    631                     if (   (devParams.Flags & DI_NEEDRESTART)
    632                         || (devParams.Flags & DI_NEEDREBOOT))
    633                     {
     620                SP_DEVINSTALL_PARAMS_W DevParams = { sizeof(DevParams) };
     621                if (SetupDiGetDeviceInstallParams(hDevInfo, pDev, &DevParams))
     622                {
     623                    if (   (DevParams.Flags & DI_NEEDRESTART)
     624                        || (DevParams.Flags & DI_NEEDREBOOT))
    634625                        NonStandardLog(("vboxNetCfgWinRemoveAllNetDevicesOfIdCallback: A reboot is required\n"));
    635                     }
    636626                }
    637627                else
    638                     NonStandardLogFlow(("vboxNetCfgWinRemoveAllNetDevicesOfIdCallback: SetupDiGetDeviceInstallParams failed with %ld\n",
     628                    NonStandardLogFlow(("vboxNetCfgWinRemoveAllNetDevicesOfIdCallback: SetupDiGetDeviceInstallParams failed with %u\n",
    639629                                        GetLastError()));
    640630            }
    641631            else
    642                 NonStandardLogFlow(("vboxNetCfgWinRemoveAllNetDevicesOfIdCallback: SetupDiCallClassInstaller failed with %ld\n",
     632                NonStandardLogFlow(("vboxNetCfgWinRemoveAllNetDevicesOfIdCallback: SetupDiCallClassInstaller failed with %u\n",
    643633                                    GetLastError()));
    644634        }
    645635        else
    646             NonStandardLogFlow(("vboxNetCfgWinRemoveAllNetDevicesOfIdCallback: SetupDiSetSelectedDevice failed with %ld\n",
     636            NonStandardLogFlow(("vboxNetCfgWinRemoveAllNetDevicesOfIdCallback: SetupDiSetSelectedDevice failed with %u\n",
    647637                                GetLastError()));
    648638    }
    649639    else
    650         NonStandardLogFlow(("vboxNetCfgWinRemoveAllNetDevicesOfIdCallback: SetupDiSetClassInstallParams failed with %ld\n",
     640        NonStandardLogFlow(("vboxNetCfgWinRemoveAllNetDevicesOfIdCallback: SetupDiSetClassInstallParams failed with %u\n",
    651641                            GetLastError()));
    652642
     
    657647typedef struct VBOXNECTFGWINPROPCHANGE
    658648{
    659     VBOXNECTFGWINPROPCHANGE_TYPE enmPcType;
     649    VBOXNECTFGWINPROPCHANGE_TYPE_T enmPcType;
    660650    HRESULT hr;
    661 } VBOXNECTFGWINPROPCHANGE ,*PVBOXNECTFGWINPROPCHANGE;
     651} VBOXNECTFGWINPROPCHANGE, *PVBOXNECTFGWINPROPCHANGE;
    662652
    663653static BOOL vboxNetCfgWinPropChangeAllNetDevicesOfIdCallback(HDEVINFO hDevInfo, PSP_DEVINFO_DATA pDev, PVOID pContext)
     
    666656
    667657    SP_PROPCHANGE_PARAMS PcParams;
    668     memset (&PcParams, 0, sizeof (PcParams));
     658    RT_ZERO(PcParams);
    669659    PcParams.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER);
    670660    PcParams.ClassInstallHeader.InstallFunction = DIF_PROPERTYCHANGE;
    671661    PcParams.Scope = DICS_FLAG_GLOBAL;
    672662
    673     switch(pPc->enmPcType)
     663    switch (pPc->enmPcType)
    674664    {
    675665        case VBOXNECTFGWINPROPCHANGE_TYPE_DISABLE:
     
    687677    }
    688678
    689     if (SetupDiSetClassInstallParams(hDevInfo, pDev, &PcParams.ClassInstallHeader, sizeof(PcParams)))
     679    if (SetupDiSetClassInstallParamsW(hDevInfo, pDev, &PcParams.ClassInstallHeader, sizeof(PcParams)))
    690680    {
    691681        if (SetupDiSetSelectedDevice(hDevInfo, pDev))
     
    693683            if (SetupDiCallClassInstaller(DIF_PROPERTYCHANGE, hDevInfo, pDev))
    694684            {
    695                 SP_DEVINSTALL_PARAMS devParams;
    696                 devParams.cbSize = sizeof(devParams);
    697                 if (SetupDiGetDeviceInstallParams(hDevInfo,pDev,&devParams))
    698                 {
    699                     if (   (devParams.Flags & DI_NEEDRESTART)
    700                         || (devParams.Flags & DI_NEEDREBOOT))
    701                     {
     685                SP_DEVINSTALL_PARAMS_W DevParams = { sizeof(DevParams) };
     686                if (SetupDiGetDeviceInstallParamsW(hDevInfo, pDev, &DevParams))
     687                {
     688                    if (   (DevParams.Flags & DI_NEEDRESTART)
     689                        || (DevParams.Flags & DI_NEEDREBOOT))
    702690                        NonStandardLog(("vboxNetCfgWinPropChangeAllNetDevicesOfIdCallback: A reboot is required\n"));
    703                     }
    704691                }
    705692                else
    706                     NonStandardLogFlow(("vboxNetCfgWinPropChangeAllNetDevicesOfIdCallback: SetupDiGetDeviceInstallParams failed with %ld\n",
     693                    NonStandardLogFlow(("vboxNetCfgWinPropChangeAllNetDevicesOfIdCallback: SetupDiGetDeviceInstallParams failed with %u\n",
    707694                                        GetLastError()));
    708695            }
    709696            else
    710                 NonStandardLogFlow(("vboxNetCfgWinPropChangeAllNetDevicesOfIdCallback: SetupDiCallClassInstaller failed with %ld\n",
     697                NonStandardLogFlow(("vboxNetCfgWinPropChangeAllNetDevicesOfIdCallback: SetupDiCallClassInstaller failed with %u\n",
    711698                                    GetLastError()));
    712699        }
    713700        else
    714             NonStandardLogFlow(("SetupDiSetSelectedDevice failed with %ld\n", GetLastError()));
     701            NonStandardLogFlow(("SetupDiSetSelectedDevice failed with %u\n", GetLastError()));
    715702    }
    716703    else
    717         NonStandardLogFlow(("SetupDiSetClassInstallParams failed with %ld\n", GetLastError()));
     704        NonStandardLogFlow(("SetupDiSetClassInstallParams failed with %u\n", GetLastError()));
    718705
    719706    /* Continue enumeration. */
     
    722709
    723710typedef BOOL (*PFNVBOXNETCFGWINNETENUMCALLBACK)(HDEVINFO hDevInfo, PSP_DEVINFO_DATA pDev, PVOID pContext);
    724 VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinEnumNetDevices(LPCWSTR pwszPnPId,
    725                                                         PFNVBOXNETCFGWINNETENUMCALLBACK pfnCallback, PVOID pvContext)
    726 {
    727     NonStandardLogFlow(("VBoxNetCfgWinEnumNetDevices: Searching for: %S\n", pwszPnPId));
     711
     712static HRESULT vboxNetCfgWinEnumNetDevices(LPCWSTR pwszPnPId, PFNVBOXNETCFGWINNETENUMCALLBACK pfnCallback, PVOID pvContext)
     713{
     714    NonStandardLogFlow(("VBoxNetCfgWinEnumNetDevices: Searching for: %ls\n", pwszPnPId));
    728715
    729716    HRESULT hr;
     
    737724    if (hDevInfo != INVALID_HANDLE_VALUE)
    738725    {
    739         DWORD winEr = NO_ERROR;
    740 
    741         DWORD dwDevId = 0;
    742         size_t cPnPId = wcslen(pwszPnPId);
    743 
    744         PBYTE pBuffer = NULL;
    745 
     726        size_t const cwcPnPId = RTUtf16Len(pwszPnPId);
     727        DWORD        winEr    = NO_ERROR;
     728        DWORD        dwDevId  = 0;
     729        DWORD        cbBuffer = 0;
     730        PBYTE        pbBuffer = NULL;
    746731        for (;;)
    747732        {
     
    754739                winEr = GetLastError();
    755740                if (winEr == ERROR_NO_MORE_ITEMS)
    756                     winEr = ERROR_SUCCESS;
     741                    winEr = NO_ERROR;
    757742                break;
    758743            }
    759744
    760             NonStandardLogFlow(("VBoxNetCfgWinEnumNetDevices: Enumerating device %ld ... \n", dwDevId));
     745            NonStandardLogFlow(("VBoxNetCfgWinEnumNetDevices: Enumerating device %u ... \n", dwDevId));
    761746            dwDevId++;
    762747
    763             if (pBuffer)
    764                 free(pBuffer);
    765             pBuffer = NULL;
    766             DWORD cbBuffer = 0;
    767748            DWORD cbRequired = 0;
    768 
     749            SetLastError(0);
    769750            if (!SetupDiGetDeviceRegistryPropertyW(hDevInfo, &Dev,
    770751                                                   SPDRP_HARDWAREID, /* IN DWORD Property */
    771752                                                   NULL,             /* OUT PDWORD PropertyRegDataType OPTIONAL */
    772                                                    pBuffer,          /* OUT PBYTE PropertyBuffer */
     753                                                   pbBuffer,         /* OUT PBYTE PropertyBuffer */
    773754                                                   cbBuffer,         /* IN DWORD PropertyBufferSize */
    774755                                                   &cbRequired       /* OUT PDWORD RequiredSize OPTIONAL */))
     
    777758                if (winEr != ERROR_INSUFFICIENT_BUFFER)
    778759                {
    779                     NonStandardLogFlow(("VBoxNetCfgWinEnumNetDevices: SetupDiGetDeviceRegistryPropertyW (1) failed with %ld\n", winEr));
     760                    if (winEr == ERROR_INVALID_DATA)
     761                    {
     762                        NonStandardLogFlow(("VBoxNetCfgWinEnumNetDevices: SetupDiGetDeviceRegistryPropertyW (1) failed with ERROR_INVALID_DATA - ignoring, skipping to next device\n"));
     763                        continue;
     764                    }
     765                    NonStandardLogFlow(("VBoxNetCfgWinEnumNetDevices: SetupDiGetDeviceRegistryPropertyW (1) failed with %u\n", winEr));
    780766                    break;
    781767                }
    782 
    783                 pBuffer = (PBYTE)malloc(cbRequired);
    784                 if (!pBuffer)
    785                 {
    786                     NonStandardLogFlow(("VBoxNetCfgWinEnumNetDevices: Out of memory allocating %ld bytes\n",
    787                                         cbRequired));
     768                winEr = NO_ERROR;
     769
     770                cbBuffer = RT_ALIGN_32(cbRequired, 64);
     771                void *pvNew = RTMemRealloc(pbBuffer, cbBuffer);
     772                if (pvNew)
     773                    pbBuffer = (PBYTE)pvNew;
     774                else
     775                {
     776                    NonStandardLogFlow(("VBoxNetCfgWinEnumNetDevices: Out of memory allocating %u bytes\n", cbBuffer));
    788777                    winEr = ERROR_OUTOFMEMORY;
    789778                    break;
    790779                }
    791780
    792                 cbBuffer = cbRequired;
    793 
    794                 if (!SetupDiGetDeviceRegistryPropertyW(hDevInfo,&Dev,
     781                if (!SetupDiGetDeviceRegistryPropertyW(hDevInfo, &Dev,
    795782                                                       SPDRP_HARDWAREID, /* IN DWORD Property */
    796783                                                       NULL,             /* OUT PDWORD PropertyRegDataType, OPTIONAL */
    797                                                        pBuffer,          /* OUT PBYTE PropertyBuffer */
     784                                                       pbBuffer,         /* OUT PBYTE PropertyBuffer */
    798785                                                       cbBuffer,         /* IN DWORD PropertyBufferSize */
    799786                                                       &cbRequired       /* OUT PDWORD RequiredSize OPTIONAL */))
    800787                {
    801788                    winEr = GetLastError();
    802                     NonStandardLogFlow(("VBoxNetCfgWinEnumNetDevices: SetupDiGetDeviceRegistryPropertyW (2) failed with %ld\n",
     789                    NonStandardLogFlow(("VBoxNetCfgWinEnumNetDevices: SetupDiGetDeviceRegistryPropertyW (2) failed with %u\n",
    803790                                        winEr));
    804791                    break;
     
    806793            }
    807794
    808             PWSTR pCurId = (PWSTR)pBuffer;
    809             size_t cCurId = wcslen(pCurId);
    810 
    811             NonStandardLogFlow(("VBoxNetCfgWinEnumNetDevices: Device %ld: %S\n", dwDevId, pCurId));
    812 
    813             if (cCurId >= cPnPId)
    814             {
    815                 NonStandardLogFlow(("!wcsnicmp(pCurId = (%S), pwszPnPId = (%S), cPnPId = (%d))\n", pCurId, pwszPnPId, cPnPId));
    816 
    817                 pCurId += cCurId - cPnPId;
    818                 if (!wcsnicmp(pCurId, pwszPnPId, cPnPId))
     795            PWSTR  pwszCurId = (PWSTR)pbBuffer;
     796            size_t cwcCurId  = RTUtf16Len(pwszCurId);
     797
     798            NonStandardLogFlow(("VBoxNetCfgWinEnumNetDevices: Device %u: %ls\n", dwDevId, pwszCurId));
     799
     800            if (cwcCurId >= cwcPnPId)
     801            {
     802                NonStandardLogFlow(("!RTUtf16NICmp(pwszCurId = (%ls), pwszPnPId = (%ls), cwcPnPId = (%d))\n", pwszCurId, pwszPnPId, cwcPnPId));
     803
     804                pwszCurId += cwcCurId - cwcPnPId;
     805                if (!RTUtf16NICmp(pwszCurId, pwszPnPId, cwcPnPId))
    819806                {
    820807                    if (!pfnCallback(hDevInfo, &Dev, pvContext))
     
    824811        }
    825812
    826         NonStandardLogFlow(("VBoxNetCfgWinEnumNetDevices: Found %ld devices total\n", dwDevId));
    827 
    828         if (pBuffer)
    829             free(pBuffer);
     813        NonStandardLogFlow(("VBoxNetCfgWinEnumNetDevices: Found %u devices total\n", dwDevId));
     814
     815        if (pbBuffer)
     816            RTMemFree(pbBuffer);
    830817
    831818        hr = HRESULT_FROM_WIN32(winEr);
     
    836823    {
    837824        DWORD winEr = GetLastError();
    838         NonStandardLogFlow(("VBoxNetCfgWinEnumNetDevices: SetupDiGetClassDevsExW failed with %ld\n", winEr));
     825        NonStandardLogFlow(("VBoxNetCfgWinEnumNetDevices: SetupDiGetClassDevsExW failed with %u\n", winEr));
    839826        hr = HRESULT_FROM_WIN32(winEr);
    840827    }
     
    844831}
    845832
    846 VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinRemoveAllNetDevicesOfId(IN LPCWSTR lpszPnPId)
    847 {
    848     return VBoxNetCfgWinEnumNetDevices(lpszPnPId, vboxNetCfgWinRemoveAllNetDevicesOfIdCallback, NULL);
    849 }
    850 
    851 VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinPropChangeAllNetDevicesOfId(IN LPCWSTR lpszPnPId, VBOXNECTFGWINPROPCHANGE_TYPE enmPcType)
     833VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinRemoveAllNetDevicesOfId(IN LPCWSTR pwszPnPId)
     834{
     835    return vboxNetCfgWinEnumNetDevices(pwszPnPId, vboxNetCfgWinRemoveAllNetDevicesOfIdCallback, NULL);
     836}
     837
     838VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinPropChangeAllNetDevicesOfId(IN LPCWSTR pwszPnPId, VBOXNECTFGWINPROPCHANGE_TYPE_T enmPcType)
    852839{
    853840    VBOXNECTFGWINPROPCHANGE Pc;
    854841    Pc.enmPcType = enmPcType;
    855842    Pc.hr = S_OK;
    856     NonStandardLogFlow(("Calling VBoxNetCfgWinEnumNetDevices with lpszPnPId =(%S) and vboxNetCfgWinPropChangeAllNetDevicesOfIdCallback\n", lpszPnPId));
    857 
    858     HRESULT hr = VBoxNetCfgWinEnumNetDevices(lpszPnPId, vboxNetCfgWinPropChangeAllNetDevicesOfIdCallback, &Pc);
     843    NonStandardLogFlow(("Calling VBoxNetCfgWinEnumNetDevices with pwszPnPId (= %ls) and vboxNetCfgWinPropChangeAllNetDevicesOfIdCallback\n", pwszPnPId));
     844
     845    HRESULT hr = vboxNetCfgWinEnumNetDevices(pwszPnPId, vboxNetCfgWinPropChangeAllNetDevicesOfIdCallback, &Pc);
    859846    if (!SUCCEEDED(hr))
    860847    {
     
    872859}
    873860
    874 /*
    875  * logging
    876  */
     861
     862
     863/*********************************************************************************************************************************
     864*   Logging                                                                                                                      *
     865*********************************************************************************************************************************/
     866
    877867static void DoLogging(const char *pszString, ...)
    878868{
     
    880870    if (pfnLogger)
    881871    {
    882         char szBuffer[4096] = {0};
     872        char szBuffer[4096];
    883873        va_list va;
    884874        va_start(va, pszString);
    885         _vsnprintf(szBuffer, RT_ELEMENTS(szBuffer), pszString, va);
     875        RTStrPrintfV(szBuffer, RT_ELEMENTS(szBuffer), pszString, va);
    886876        va_end(va);
    887877
     
    895885}
    896886
    897 /*
    898  * IP configuration API
    899  */
     887
     888
     889/*********************************************************************************************************************************
     890*   IP configuration API                                                                                                         *
     891*********************************************************************************************************************************/
    900892/* network settings config */
     893#if 1 /** @todo r=bird: Can't we replace this with VBox/com/ptr.h? */
    901894/**
    902895 *  Strong referencing operators. Used as a second argument to ComPtr<>/ComObjPtr<>.
    903896 */
    904 template <class C>
     897template<class C>
    905898class ComStrongRef
    906899{
    907900protected:
    908901
    909     static void addref (C *p) { p->AddRef(); }
    910     static void release (C *p) { p->Release(); }
     902    static void addref(C *p) { p->AddRef(); }
     903    static void release(C *p) { p->Release(); }
    911904};
    912905
     
    915908 *  Base template for smart COM pointers. Not intended to be used directly.
    916909 */
    917 template <class C, template <class> class RefOps = ComStrongRef>
    918 class ComPtrBase : protected RefOps <C>
     910template<class C, template<class> class RefOps = ComStrongRef>
     911class ComPtrBase : protected RefOps<C>
    919912{
    920913public:
    921914
    922915    /* special template to disable AddRef()/Release() */
    923     template <class I>
     916    template<class I>
    924917    class NoAddRefRelease : public I
    925918    {
     
    938931protected:
    939932
    940     ComPtrBase () : p (NULL) {}
    941     ComPtrBase (const ComPtrBase &that) : p (that.p) { addref(); }
    942     ComPtrBase (C *that_p) : p (that_p) { addref(); }
     933    ComPtrBase() : p(NULL) {}
     934    ComPtrBase(const ComPtrBase &that) : p(that.p) { addref(); }
     935    ComPtrBase(C *that_p) : p(that_p)              { addref(); }
    943936
    944937    ~ComPtrBase() { release(); }
    945938
    946     ComPtrBase &operator= (const ComPtrBase &that)
    947     {
    948         safe_assign (that.p);
     939    ComPtrBase &operator=(const ComPtrBase &that)
     940    {
     941        safe_assign(that.p);
    949942        return *this;
    950943    }
    951944
    952     ComPtrBase &operator= (C *that_p)
    953     {
    954         safe_assign (that_p);
     945    ComPtrBase &operator=(C *that_p)
     946    {
     947        safe_assign(that_p);
    955948        return *this;
    956949    }
     
    969962    }
    970963
    971     bool operator! () const { return isNull(); }
    972 
    973     bool operator< (C* that_p) const { return p < that_p; }
    974     bool operator== (C* that_p) const { return p == that_p; }
    975 
    976     template <class I>
    977     bool equalsTo (I *aThat) const
    978     {
    979         return ComPtrEquals (p, aThat);
    980     }
    981 
    982     template <class OC>
    983     bool equalsTo (const ComPtrBase <OC> &oc) const
    984     {
    985         return equalsTo ((OC *) oc);
     964    bool operator!() const              { return isNull(); }
     965
     966    bool operator<(C* that_p) const    { return p < that_p; }
     967    bool operator==(C* that_p) const    { return p == that_p; }
     968
     969    template<class I>
     970    bool equalsTo(I *aThat) const
     971    {
     972        return ComPtrEquals(p, aThat);
     973    }
     974
     975    template<class OC>
     976    bool equalsTo(const ComPtrBase<OC> &oc) const
     977    {
     978        return equalsTo((OC *) oc);
    986979    }
    987980
    988981    /** Intended to pass instances as in parameters to interface methods */
    989     operator C* () const { return p; }
     982    operator C *() const { return p; }
    990983
    991984    /**
     
    993986     *  pointer).
    994987     */
    995     NoAddRefRelease <C> *operator-> () const
     988    NoAddRefRelease<C> *operator->() const
    996989    {
    997990        AssertMsg (p, ("Managed pointer must not be null\n"));
     
    999992    }
    1000993
    1001     template <class I>
    1002     HRESULT queryInterfaceTo (I **pp) const
     994    template<class I>
     995    HRESULT queryInterfaceTo(I **pp) const
    1003996    {
    1004997        if (pp)
    1005998        {
    1006999            if (p)
    1007             {
    1008                 return p->QueryInterface (COM_IIDOF (I), (void **) pp);
    1009             }
    1010             else
    1011             {
    1012                 *pp = NULL;
    1013                 return S_OK;
    1014             }
    1015         }
    1016 
     1000                return p->QueryInterface(COM_IIDOF(I), (void **)pp);
     1001            *pp = NULL;
     1002            return S_OK;
     1003        }
    10171004        return E_INVALIDARG;
    10181005    }
     
    10301017    {
    10311018        if (p)
    1032             RefOps <C>::addref (p);
     1019            RefOps<C>::addref(p);
    10331020    }
    10341021
     
    10361023    {
    10371024        if (p)
    1038             RefOps <C>::release (p);
    1039     }
    1040 
    1041     void safe_assign (C *that_p)
     1025            RefOps<C>::release(p);
     1026    }
     1027
     1028    void safe_assign(C *that_p)
    10421029    {
    10431030        /* be aware of self-assignment */
    10441031        if (that_p)
    1045             RefOps <C>::addref (that_p);
     1032            RefOps<C>::addref(that_p);
    10461033        release();
    10471034        p = that_p;
     
    10571044 *  @param I    COM interface class
    10581045 */
    1059 template <class I, template <class> class RefOps = ComStrongRef>
    1060 class ComPtr : public ComPtrBase <I, RefOps>
    1061 {
    1062     typedef ComPtrBase <I, RefOps> Base;
     1046template<class I, template<class> class RefOps = ComStrongRef>
     1047class ComPtr : public ComPtrBase<I, RefOps>
     1048{
     1049    typedef ComPtrBase<I, RefOps> Base;
    10631050
    10641051public:
    10651052
    1066     ComPtr () : Base() {}
    1067     ComPtr (const ComPtr &that) : Base(that) {}
    1068     ComPtr &operator= (const ComPtr &that)
    1069     {
    1070         Base::operator= (that);
     1053    ComPtr() : Base() {}
     1054    ComPtr(const ComPtr &that) : Base(that) {}
     1055    ComPtr&operator= (const ComPtr &that)
     1056    {
     1057        Base::operator=(that);
    10711058        return *this;
    10721059    }
    10731060
    1074     template <class OI>
    1075     ComPtr (OI *that_p) : Base () { operator= (that_p); }
     1061    template<class OI>
     1062    ComPtr(OI *that_p) : Base () { operator=(that_p); }
    10761063
    10771064    /* specialization for I */
    1078     ComPtr (I *that_p) : Base (that_p) {}
     1065    ComPtr(I *that_p) : Base (that_p) {}
    10791066
    10801067    template <class OC>
    1081     ComPtr (const ComPtr <OC, RefOps> &oc) : Base () { operator= ((OC *) oc); }
    1082 
    1083     template <class OI>
    1084     ComPtr &operator= (OI *that_p)
     1068    ComPtr(const ComPtr<OC, RefOps> &oc) : Base() { operator=((OC *) oc); }
     1069
     1070    template<class OI>
     1071    ComPtr &operator=(OI *that_p)
    10851072    {
    10861073        if (that_p)
    1087             that_p->QueryInterface (COM_IIDOF (I), (void **) Base::asOutParam());
     1074            that_p->QueryInterface(COM_IIDOF(I), (void **)Base::asOutParam());
    10881075        else
    10891076            Base::setNull();
     
    10941081    ComPtr &operator=(I *that_p)
    10951082    {
    1096         Base::operator= (that_p);
     1083        Base::operator=(that_p);
    10971084        return *this;
    10981085    }
    10991086
    1100     template <class OC>
    1101     ComPtr &operator= (const ComPtr <OC, RefOps> &oc)
    1102     {
    1103         return operator= ((OC *) oc);
     1087    template<class OC>
     1088    ComPtr &operator=(const ComPtr<OC, RefOps> &oc)
     1089    {
     1090        return operator=((OC *) oc);
    11041091    }
    11051092};
    1106 
    1107 static HRESULT netIfWinFindAdapterClassById(IWbemServices * pSvc, const GUID * pGuid, IWbemClassObject **pAdapterConfig)
     1093#endif
     1094
     1095static HRESULT netIfWinFindAdapterClassById(IWbemServices *pSvc, const GUID *pGuid, IWbemClassObject **pAdapterConfig)
    11081096{
    11091097    HRESULT hr;
    1110     WCHAR wszQuery[256];
     1098
    11111099    WCHAR wszGuid[50];
    1112 
    1113     int length = StringFromGUID2(*pGuid, wszGuid, RT_ELEMENTS(wszGuid));
    1114     if (length)
    1115     {
    1116         swprintf(wszQuery, L"SELECT * FROM Win32_NetworkAdapterConfiguration WHERE SettingID = \"%s\"", wszGuid);
     1100    int cwcGuid = StringFromGUID2(*pGuid, wszGuid, RT_ELEMENTS(wszGuid));
     1101    if (cwcGuid)
     1102    {
     1103        com::BstrFmt bstrQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE SettingID = \"%ls\"", wszGuid);
    11171104        IEnumWbemClassObject* pEnumerator = NULL;
    1118         hr = pSvc->ExecQuery(bstr_t("WQL"), bstr_t(wszQuery), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
     1105        hr = pSvc->ExecQuery(com::Bstr("WQL").raw(), bstrQuery.raw(), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
    11191106                             NULL, &pEnumerator);
    11201107        if (SUCCEEDED(hr))
     
    11221109            if (pEnumerator)
    11231110            {
    1124                 IWbemClassObject *pclsObj;
     1111                IWbemClassObject *pclsObj = NULL;
    11251112                ULONG uReturn = 0;
    11261113                hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
     
    11361123                        return S_OK;
    11371124                    }
    1138 
    11391125                    hr = E_FAIL;
    11401126                }
    1141 
    11421127                pEnumerator->Release();
    11431128            }
     
    11541139    {
    11551140        DWORD winEr = GetLastError();
    1156         hr = HRESULT_FROM_WIN32( winEr );
     1141        hr = HRESULT_FROM_WIN32(winEr);
    11571142        if (SUCCEEDED(hr))
    11581143            hr = E_FAIL;
     
    11641149}
    11651150
    1166 static HRESULT netIfWinIsHostOnly(IWbemClassObject * pAdapterConfig, BOOL * pbIsHostOnly)
     1151static HRESULT netIfWinIsHostOnly(IWbemClassObject *pAdapterConfig, BOOL *pfIsHostOnly)
    11671152{
    11681153    VARIANT vtServiceName;
     
    11721157    if (SUCCEEDED(hr))
    11731158    {
    1174         *pbIsHostOnly = bstr_t(vtServiceName.bstrVal) == bstr_t("VBoxNetAdp");
     1159        *pfIsHostOnly = RTUtf16CmpAscii(vtServiceName.bstrVal, "VBoxNetAdp") == 0;
    11751160
    11761161        VariantClear(&vtServiceName);
     
    11821167static HRESULT netIfWinGetIpSettings(IWbemClassObject * pAdapterConfig, ULONG *pIpv4, ULONG *pMaskv4)
    11831168{
     1169    *pIpv4   = 0;
     1170    *pMaskv4 = 0;
     1171
    11841172    VARIANT vtIp;
    1185     HRESULT hr;
    11861173    VariantInit(&vtIp);
    1187 
    1188     *pIpv4 = 0;
    1189     *pMaskv4 = 0;
    1190 
    1191     hr = pAdapterConfig->Get(L"IPAddress", 0, &vtIp, 0, 0);
     1174    HRESULT hr = pAdapterConfig->Get(L"IPAddress", 0, &vtIp, 0, 0);
    11921175    if (SUCCEEDED(hr))
    11931176    {
     
    12011184                if (vtMask.vt == (VT_ARRAY | VT_BSTR))
    12021185                {
    1203                     SAFEARRAY * pIpArray = vtIp.parray;
    1204                     SAFEARRAY * pMaskArray = vtMask.parray;
     1186                    SAFEARRAY *pIpArray  = vtIp.parray;
     1187                    SAFEARRAY *pMaskArray = vtMask.parray;
    12051188                    if (pIpArray && pMaskArray)
    12061189                    {
    1207                         BSTR pCurIp;
    1208                         BSTR pCurMask;
     1190                        BSTR pBstrCurIp;
     1191                        BSTR pBstrCurMask;
    12091192                        for (LONG i = 0;
    1210                             SafeArrayGetElement(pIpArray, &i, (PVOID)&pCurIp) == S_OK
    1211                             && SafeArrayGetElement(pMaskArray, &i, (PVOID)&pCurMask) == S_OK;
    1212                             i++)
     1193                                SafeArrayGetElement(pIpArray,  &i,  (PVOID)&pBstrCurIp)  == S_OK
     1194                             && SafeArrayGetElement(pMaskArray, &i, (PVOID)&pBstrCurMask) == S_OK;
     1195                             i++)
    12131196                        {
    1214                             bstr_t ip(pCurIp);
    1215 
    1216                             ULONG Ipv4 = inet_addr((char*)(ip));
     1197                            com::Utf8Str strIp(pBstrCurIp);
     1198                            ULONG Ipv4 = inet_addr(strIp.c_str());
    12171199                            if (Ipv4 != INADDR_NONE)
    12181200                            {
    12191201                                *pIpv4 = Ipv4;
    1220                                 bstr_t mask(pCurMask);
    1221                                 *pMaskv4 = inet_addr((char*)(mask));
     1202
     1203                                com::Utf8Str strMask(pBstrCurMask);
     1204                                *pMaskv4 = inet_addr(strMask.c_str());
    12221205                                break;
    12231206                            }
     
    12251208                    }
    12261209                }
    1227                 else
    1228                 {
    1229                     *pIpv4 = 0;
    1230                     *pMaskv4 = 0;
    1231                 }
    1232 
    12331210                VariantClear(&vtMask);
    12341211            }
    12351212        }
    1236         else
    1237         {
    1238             *pIpv4 = 0;
    1239             *pMaskv4 = 0;
    1240         }
    1241 
    12421213        VariantClear(&vtIp);
    12431214    }
     
    13081279    ULONG i;
    13091280    *pFound = false;
    1310     ComPtr <IWbemClassObject> pAdapterConfig;
     1281    ComPtr<IWbemClassObject> pAdapterConfig;
    13111282    for (i = 0;
    13121283            (hr = netIfWinFindAdapterClassById(pSvc, pGuid, pAdapterConfig.asOutParam())) == S_OK
     
    13241295#endif /* unused */
    13251296
    1326 static HRESULT netIfWinCreateIWbemServices(IWbemServices ** ppSvc)
     1297static HRESULT netIfWinCreateIWbemServices(IWbemServices **ppSvc)
    13271298{
    13281299    IWbemLocator *pLoc = NULL;
    1329     HRESULT hr = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &pLoc);
     1300    HRESULT hr = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *)&pLoc);
    13301301    if (SUCCEEDED(hr))
    13311302    {
    13321303        IWbemServices *pSvc = NULL;
    1333         hr = pLoc->ConnectServer(bstr_t(L"ROOT\\CIMV2"), /* [in] const BSTR strNetworkResource */
    1334                 NULL, /* [in] const BSTR strUser */
    1335                 NULL, /* [in] const BSTR strPassword */
    1336                 0,    /* [in] const BSTR strLocale */
    1337                 NULL, /* [in] LONG lSecurityFlags */
    1338                 0,    /* [in] const BSTR strAuthority */
    1339                 0,    /* [in] IWbemContext* pCtx */
    1340                 &pSvc /* [out] IWbemServices** ppNamespace */);
     1304        hr = pLoc->ConnectServer(com::Bstr(L"ROOT\\CIMV2").raw(), /* [in] const BSTR strNetworkResource */
     1305                                 NULL, /* [in] const BSTR strUser */
     1306                                 NULL, /* [in] const BSTR strPassword */
     1307                                 0,    /* [in] const BSTR strLocale */
     1308                                 NULL, /* [in] LONG lSecurityFlags */
     1309                                 0,    /* [in] const BSTR strAuthority */
     1310                                 0,    /* [in] IWbemContext* pCtx */
     1311                                 &pSvc /* [out] IWbemServices** ppNamespace */);
    13411312        if (SUCCEEDED(hr))
    13421313        {
    13431314            hr = CoSetProxyBlanket(pSvc, /* IUnknown * pProxy */
    1344                     RPC_C_AUTHN_WINNT, /* DWORD dwAuthnSvc */
    1345                     RPC_C_AUTHZ_NONE, /* DWORD dwAuthzSvc */
    1346                     NULL, /* WCHAR * pServerPrincName */
    1347                     RPC_C_AUTHN_LEVEL_CALL, /* DWORD dwAuthnLevel */
    1348                     RPC_C_IMP_LEVEL_IMPERSONATE, /* DWORD dwImpLevel */
    1349                     NULL, /* RPC_AUTH_IDENTITY_HANDLE pAuthInfo */
    1350                     EOAC_NONE /* DWORD dwCapabilities */
    1351                     );
     1315                                   RPC_C_AUTHN_WINNT, /* DWORD dwAuthnSvc */
     1316                                   RPC_C_AUTHZ_NONE, /* DWORD dwAuthzSvc */
     1317                                   NULL, /* WCHAR * pServerPrincName */
     1318                                   RPC_C_AUTHN_LEVEL_CALL, /* DWORD dwAuthnLevel */
     1319                                   RPC_C_IMP_LEVEL_IMPERSONATE, /* DWORD dwImpLevel */
     1320                                   NULL, /* RPC_AUTH_IDENTITY_HANDLE pAuthInfo */
     1321                                   EOAC_NONE /* DWORD dwCapabilities */
     1322                                   );
    13521323            if (SUCCEEDED(hr))
    13531324            {
     
    13571328                return hr;
    13581329            }
    1359             else
    1360                 NonStandardLogFlow(("CoSetProxyBlanket failed, hr (0x%x)\n", hr));
    1361 
     1330
     1331            NonStandardLogFlow(("CoSetProxyBlanket failed: %Rhrc\n", hr));
    13621332            pSvc->Release();
    13631333        }
    13641334        else
    1365             NonStandardLogFlow(("ConnectServer failed, hr (0x%x)\n", hr));
     1335            NonStandardLogFlow(("ConnectServer failed: %Rhrc\n", hr));
    13661336        pLoc->Release();
    13671337    }
    13681338    else
    1369         NonStandardLogFlow(("CoCreateInstance failed, hr (0x%x)\n", hr));
    1370     return hr;
    1371 }
    1372 
    1373 static HRESULT netIfWinAdapterConfigPath(IWbemClassObject *pObj, BSTR * pStr)
     1339        NonStandardLogFlow(("CoCreateInstance failed: %Rhrc\n", hr));
     1340    return hr;
     1341}
     1342
     1343static HRESULT netIfWinAdapterConfigPath(IWbemClassObject *pObj, com::Bstr *pRet)
    13741344{
    13751345    VARIANT index;
     1346    VariantInit(&index);
    13761347    HRESULT hr = pObj->Get(L"Index", 0, &index, 0, 0);
    13771348    if (SUCCEEDED(hr))
    1378     {
    1379         WCHAR strIndex[8];
    1380         swprintf(strIndex, L"%u", index.uintVal);
    1381         *pStr = (bstr_t(L"Win32_NetworkAdapterConfiguration.Index='") + strIndex + "'").copy();
    1382     }
     1349        hr = pRet->printfNoThrow("Win32_NetworkAdapterConfiguration.Index='%u'", index.uintVal);
    13831350    else
    1384         NonStandardLogFlow(("Get failed, hr (0x%x)\n", hr));
    1385     return hr;
    1386 }
    1387 
    1388 static HRESULT netIfExecMethod(IWbemServices * pSvc, IWbemClassObject *pClass, BSTR ObjPath,
    1389         BSTR MethodName, LPWSTR *pArgNames, LPVARIANT *pArgs, UINT cArgs,
    1390         IWbemClassObject** ppOutParams
    1391         )
    1392 {
    1393     HRESULT hr = S_OK;
    1394     ComPtr<IWbemClassObject> pInParamsDefinition;
    1395     ComPtr<IWbemClassObject> pClassInstance;
    1396 
    1397     if (cArgs)
    1398     {
    1399         hr = pClass->GetMethod(MethodName, 0, pInParamsDefinition.asOutParam(), NULL);
     1351    {
     1352        pRet->setNull();
     1353        NonStandardLogFlow(("Get failed: %Rhrc\n", hr));
     1354    }
     1355    return hr;
     1356}
     1357
     1358static HRESULT netIfExecMethod(IWbemServices * pSvc, IWbemClassObject *pClass, com::Bstr const &rObjPath,
     1359                               const char *pszMethodName, LPWSTR *papwszArgNames, LPVARIANT *pArgs, UINT cArgs,
     1360                               IWbemClassObject **ppOutParams)
     1361{
     1362    *ppOutParams = NULL;
     1363    com::Bstr bstrMethodName;
     1364    HRESULT hr = bstrMethodName.assignEx(pszMethodName);
     1365    if (SUCCEEDED(hr))
     1366    {
     1367        ComPtr<IWbemClassObject> pInParamsDefinition;
     1368        ComPtr<IWbemClassObject> pClassInstance;
     1369        if (cArgs)
     1370        {
     1371            hr = pClass->GetMethod(bstrMethodName.raw(), 0, pInParamsDefinition.asOutParam(), NULL);
     1372            if (SUCCEEDED(hr))
     1373            {
     1374                hr = pInParamsDefinition->SpawnInstance(0, pClassInstance.asOutParam());
     1375                if (SUCCEEDED(hr))
     1376                {
     1377                    for (UINT i = 0; i < cArgs; i++)
     1378                    {
     1379                        hr = pClassInstance->Put(papwszArgNames[i], 0, pArgs[i], 0);
     1380                        if (FAILED(hr))
     1381                            break;
     1382                    }
     1383                }
     1384            }
     1385        }
     1386
    14001387        if (SUCCEEDED(hr))
    14011388        {
    1402             hr = pInParamsDefinition->SpawnInstance(0, pClassInstance.asOutParam());
     1389            IWbemClassObject *pOutParams = NULL;
     1390            hr = pSvc->ExecMethod(rObjPath.raw(), bstrMethodName.raw(), 0, NULL, pClassInstance, &pOutParams, NULL);
    14031391            if (SUCCEEDED(hr))
    1404             {
    1405                 for (UINT i = 0; i < cArgs; i++)
    1406                 {
    1407                     hr = pClassInstance->Put(pArgNames[i], 0,
    1408                         pArgs[i], 0);
    1409                     if (FAILED(hr))
    1410                         break;
    1411                 }
    1412             }
    1413         }
    1414     }
    1415 
    1416     if (SUCCEEDED(hr))
    1417     {
    1418         IWbemClassObject* pOutParams = NULL;
    1419         hr = pSvc->ExecMethod(ObjPath, MethodName, 0, NULL, pClassInstance, &pOutParams, NULL);
     1392                *ppOutParams = pOutParams;
     1393        }
     1394    }
     1395
     1396    return hr;
     1397}
     1398
     1399static HRESULT netIfWinCreateIpArray(SAFEARRAY **ppArray, in_addr const *paIps, UINT cIps)
     1400{
     1401    HRESULT    hr = S_OK;
     1402    SAFEARRAY *pIpArray = SafeArrayCreateVector(VT_BSTR, 0, cIps);
     1403    if (pIpArray)
     1404    {
     1405        for (UINT i = 0; i < cIps; i++)
     1406        {
     1407            com::Bstr bstrVal;
     1408            hr = bstrVal.printfNoThrow("%RTnaipv4", paIps[i].s_addr);
     1409            if (SUCCEEDED(hr))
     1410            {
     1411                Assert(bstrVal.equals(inet_ntoa(paIps[i])));
     1412
     1413                BSTR pRawVal;
     1414                hr = bstrVal.detachToEx(&pRawVal);
     1415                if (SUCCEEDED(hr))
     1416                {
     1417                    LONG aIndex[1] = { (LONG)i };
     1418                    hr = SafeArrayPutElement(pIpArray, aIndex, pRawVal);
     1419                    if (SUCCEEDED(hr))
     1420                        continue;
     1421                    SysFreeString(pRawVal);
     1422                }
     1423            }
     1424            break;
     1425        }
     1426
    14201427        if (SUCCEEDED(hr))
    1421         {
    1422             *ppOutParams = pOutParams;
    1423         }
    1424     }
    1425 
    1426     return hr;
    1427 }
    1428 
    1429 static HRESULT netIfWinCreateIpArray(SAFEARRAY **ppArray, in_addr* aIp, UINT cIp)
    1430 {
    1431     HRESULT hr = S_OK; /* MSC maybe used uninitialized */
    1432     SAFEARRAY * pIpArray = SafeArrayCreateVector(VT_BSTR, 0, cIp);
    1433     if (pIpArray)
    1434     {
    1435         for (UINT i = 0; i < cIp; i++)
    1436         {
    1437             char* addr = inet_ntoa(aIp[i]);
    1438             BSTR val = bstr_t(addr).copy();
    1439             long aIndex[1];
    1440             aIndex[0] = i;
    1441             hr = SafeArrayPutElement(pIpArray, aIndex, val);
    1442             if (FAILED(hr))
    1443             {
    1444                 SysFreeString(val);
    1445                 SafeArrayDestroy(pIpArray);
    1446                 break;
    1447             }
    1448         }
    1449 
    1450         if (SUCCEEDED(hr))
    1451         {
    14521428            *ppArray = pIpArray;
    1453         }
     1429        else
     1430            SafeArrayDestroy(pIpArray);
    14541431    }
    14551432    else
    14561433        hr = HRESULT_FROM_WIN32(GetLastError());
    1457 
    14581434    return hr;
    14591435}
     
    14661442    if (pIpArray)
    14671443    {
    1468         BSTR val = bstr_t(Ip, false).copy();
     1444        BSTR val = com::Bstr(Ip, false).copy();
    14691445        long aIndex[1];
    14701446        aIndex[0] = 0;
     
    14891465
    14901466
    1491 static HRESULT netIfWinCreateIpArrayVariantV4(VARIANT * pIpAddresses, in_addr* aIp, UINT cIp)
    1492 {
    1493     HRESULT hr;
     1467static HRESULT netIfWinCreateIpArrayVariantV4(VARIANT *pIpAddresses, in_addr const *paIps, UINT cIps)
     1468{
    14941469    VariantInit(pIpAddresses);
    14951470    pIpAddresses->vt = VT_ARRAY | VT_BSTR;
     1471
    14961472    SAFEARRAY *pIpArray;
    1497     hr = netIfWinCreateIpArray(&pIpArray, aIp, cIp);
     1473    HRESULT hr = netIfWinCreateIpArray(&pIpArray, paIps, cIps);
    14981474    if (SUCCEEDED(hr))
    1499     {
    15001475        pIpAddresses->parray = pIpArray;
    1501     }
    15021476    return hr;
    15031477}
     
    15191493#endif
    15201494
    1521 static HRESULT netIfWinEnableStatic(IWbemServices *pSvc, const GUID *pGuid, BSTR ObjPath, VARIANT *pIp, VARIANT *pMask)
     1495static HRESULT netIfWinEnableStatic(IWbemServices *pSvc, const GUID *pGuid, com::Bstr &rObjPath, VARIANT *pIp, VARIANT *pMask)
     1496{
     1497    com::Bstr bstrClassName;
     1498    HRESULT hr = bstrClassName.assignEx("Win32_NetworkAdapterConfiguration");
     1499    if (SUCCEEDED(hr))
     1500    {
     1501        ComPtr<IWbemClassObject> pClass;
     1502        hr = pSvc->GetObject(bstrClassName.raw(), 0, NULL, pClass.asOutParam(), NULL);
     1503        if (SUCCEEDED(hr))
     1504        {
     1505            LPWSTR argNames[] = {L"IPAddress", L"SubnetMask"};
     1506            LPVARIANT  args[] = {         pIp,        pMask };
     1507
     1508            ComPtr<IWbemClassObject> pOutParams;
     1509            hr = netIfExecMethod(pSvc, pClass, rObjPath.raw(), "EnableStatic", argNames, args,
     1510                                 2, pOutParams.asOutParam());
     1511            if (SUCCEEDED(hr))
     1512            {
     1513                com::Bstr bstrReturnValue;
     1514                hr = bstrReturnValue.assignEx("ReturnValue");
     1515                if (SUCCEEDED(hr))
     1516                {
     1517                    VARIANT varReturnValue;
     1518                    VariantInit(&varReturnValue);
     1519                    hr = pOutParams->Get(bstrReturnValue.raw(), 0, &varReturnValue, NULL, 0);
     1520                    Assert(SUCCEEDED(hr));
     1521                    if (SUCCEEDED(hr))
     1522                    {
     1523                        //Assert(varReturnValue.vt == VT_UINT);
     1524                        int winEr = varReturnValue.uintVal;
     1525                        switch (winEr)
     1526                        {
     1527                            case 0:
     1528                            {
     1529                                hr = S_OK;
     1530                                //bool bFound;
     1531                                //HRESULT tmpHr = netIfWinWaitIpSettings(pSvc, pGuid, pIp->parray, pMask->parray, 180, &bFound);
     1532                                NOREF(pGuid);
     1533                                break;
     1534                            }
     1535                            default:
     1536                                hr = HRESULT_FROM_WIN32( winEr );
     1537                                break;
     1538                        }
     1539                    }
     1540                }
     1541            }
     1542        }
     1543    }
     1544    return hr;
     1545}
     1546
     1547
     1548static HRESULT netIfWinEnableStaticV4(IWbemServices *pSvc, const GUID *pGuid, com::Bstr &rObjPath,
     1549                                      in_addr const *paIps, in_addr const *paMasks, UINT cIpAndMasks)
     1550{
     1551    VARIANT ipAddresses;
     1552    HRESULT hr = netIfWinCreateIpArrayVariantV4(&ipAddresses, paIps, cIpAndMasks);
     1553    if (SUCCEEDED(hr))
     1554    {
     1555        VARIANT ipMasks;
     1556        hr = netIfWinCreateIpArrayVariantV4(&ipMasks, paMasks, cIpAndMasks);
     1557        if (SUCCEEDED(hr))
     1558        {
     1559            hr = netIfWinEnableStatic(pSvc, pGuid, rObjPath, &ipAddresses, &ipMasks);
     1560            VariantClear(&ipMasks);
     1561        }
     1562        VariantClear(&ipAddresses);
     1563    }
     1564    return hr;
     1565}
     1566
     1567#if 0 /* unused */
     1568
     1569static HRESULT netIfWinEnableStaticV4V6(IWbemServices * pSvc, const GUID * pGuid, BSTR ObjPath, BSTR Ip, BSTR Mask)
     1570{
     1571    VARIANT ipAddresses;
     1572    HRESULT hr = netIfWinCreateIpArrayVariantV4V6(&ipAddresses, Ip);
     1573    if (SUCCEEDED(hr))
     1574    {
     1575        VARIANT ipMasks;
     1576        hr = netIfWinCreateIpArrayVariantV4V6(&ipMasks, Mask);
     1577        if (SUCCEEDED(hr))
     1578        {
     1579            hr = netIfWinEnableStatic(pSvc, pGuid, ObjPath, &ipAddresses, &ipMasks);
     1580            VariantClear(&ipMasks);
     1581        }
     1582        VariantClear(&ipAddresses);
     1583    }
     1584    return hr;
     1585}
     1586
     1587/* win API allows to set gw metrics as well, we are not setting them */
     1588static HRESULT netIfWinSetGateways(IWbemServices * pSvc, BSTR ObjPath, VARIANT * pGw)
    15221589{
    15231590    ComPtr<IWbemClassObject> pClass;
     
    15291596        if (SUCCEEDED(hr))
    15301597        {
    1531             LPWSTR argNames[] = {L"IPAddress", L"SubnetMask"};
    1532             LPVARIANT args[] = {pIp, pMask};
    1533             ComPtr<IWbemClassObject> pOutParams;
    1534 
    1535             hr = netIfExecMethod(pSvc, pClass, ObjPath, bstr_t(L"EnableStatic"), argNames, args, 2, pOutParams.asOutParam());
    1536             if (SUCCEEDED(hr))
    1537             {
    1538                 VARIANT varReturnValue;
    1539                 hr = pOutParams->Get(bstr_t(L"ReturnValue"), 0,
    1540                     &varReturnValue, NULL, 0);
    1541                 Assert(SUCCEEDED(hr));
    1542                 if (SUCCEEDED(hr))
    1543                 {
    1544 //                    Assert(varReturnValue.vt == VT_UINT);
    1545                     int winEr = varReturnValue.uintVal;
    1546                     switch (winEr)
    1547                     {
    1548                         case 0:
    1549                         {
    1550                             hr = S_OK;
    1551 //                            bool bFound;
    1552 //                            HRESULT tmpHr = netIfWinWaitIpSettings(pSvc, pGuid, pIp->parray, pMask->parray, 180, &bFound);
    1553                             NOREF(pGuid);
    1554                             break;
    1555                         }
    1556                         default:
    1557                             hr = HRESULT_FROM_WIN32( winEr );
    1558                             break;
    1559                     }
    1560                 }
    1561             }
    1562         }
    1563         SysFreeString(ClassName);
    1564     }
    1565     else
    1566         hr = HRESULT_FROM_WIN32(GetLastError());
    1567 
    1568     return hr;
    1569 }
    1570 
    1571 
    1572 static HRESULT netIfWinEnableStaticV4(IWbemServices * pSvc, const GUID * pGuid, BSTR ObjPath, in_addr* aIp, in_addr * aMask, UINT cIp)
    1573 {
    1574     VARIANT ipAddresses;
    1575     HRESULT hr = netIfWinCreateIpArrayVariantV4(&ipAddresses, aIp, cIp);
    1576     if (SUCCEEDED(hr))
    1577     {
    1578         VARIANT ipMasks;
    1579         hr = netIfWinCreateIpArrayVariantV4(&ipMasks, aMask, cIp);
    1580         if (SUCCEEDED(hr))
    1581         {
    1582             hr = netIfWinEnableStatic(pSvc, pGuid, ObjPath, &ipAddresses, &ipMasks);
    1583             VariantClear(&ipMasks);
    1584         }
    1585         VariantClear(&ipAddresses);
    1586     }
    1587     return hr;
    1588 }
    1589 
    1590 #if 0 /* unused */
    1591 
    1592 static HRESULT netIfWinEnableStaticV4V6(IWbemServices * pSvc, const GUID * pGuid, BSTR ObjPath, BSTR Ip, BSTR Mask)
    1593 {
    1594     VARIANT ipAddresses;
    1595     HRESULT hr = netIfWinCreateIpArrayVariantV4V6(&ipAddresses, Ip);
    1596     if (SUCCEEDED(hr))
    1597     {
    1598         VARIANT ipMasks;
    1599         hr = netIfWinCreateIpArrayVariantV4V6(&ipMasks, Mask);
    1600         if (SUCCEEDED(hr))
    1601         {
    1602             hr = netIfWinEnableStatic(pSvc, pGuid, ObjPath, &ipAddresses, &ipMasks);
    1603             VariantClear(&ipMasks);
    1604         }
    1605         VariantClear(&ipAddresses);
    1606     }
    1607     return hr;
    1608 }
    1609 
    1610 /* win API allows to set gw metrics as well, we are not setting them */
    1611 static HRESULT netIfWinSetGateways(IWbemServices * pSvc, BSTR ObjPath, VARIANT * pGw)
    1612 {
    1613     ComPtr<IWbemClassObject> pClass;
    1614     BSTR ClassName = SysAllocString(L"Win32_NetworkAdapterConfiguration");
    1615     HRESULT hr;
    1616     if (ClassName)
    1617     {
    1618         hr = pSvc->GetObject(ClassName, 0, NULL, pClass.asOutParam(), NULL);
    1619         if (SUCCEEDED(hr))
    1620         {
    16211598            LPWSTR argNames[] = {L"DefaultIPGateway"};
    16221599            LPVARIANT args[] = {pGw};
    16231600            ComPtr<IWbemClassObject> pOutParams;
    16241601
    1625             hr = netIfExecMethod(pSvc, pClass, ObjPath, bstr_t(L"SetGateways"), argNames, args, 1, pOutParams.asOutParam());
     1602            hr = netIfExecMethod(pSvc, pClass, ObjPath, com::Bstr(L"SetGateways"), argNames, args, 1, pOutParams.asOutParam());
    16261603            if (SUCCEEDED(hr))
    16271604            {
    16281605                VARIANT varReturnValue;
    1629                 hr = pOutParams->Get(bstr_t(L"ReturnValue"), 0, &varReturnValue, NULL, 0);
     1606                hr = pOutParams->Get(com::Bstr(L"ReturnValue"), 0, &varReturnValue, NULL, 0);
    16301607                Assert(SUCCEEDED(hr));
    16311608                if (SUCCEEDED(hr))
     
    16811658#endif /* unused */
    16821659
    1683 static HRESULT netIfWinEnableDHCP(IWbemServices * pSvc, BSTR ObjPath)
    1684 {
    1685     ComPtr<IWbemClassObject> pClass;
    1686     BSTR ClassName = SysAllocString(L"Win32_NetworkAdapterConfiguration");
    1687     HRESULT hr;
    1688     if (ClassName)
    1689     {
    1690         hr = pSvc->GetObject(ClassName, 0, NULL, pClass.asOutParam(), NULL);
     1660static HRESULT netIfWinEnableDHCP(IWbemServices * pSvc, const com::Bstr &rObjPath)
     1661{
     1662    com::Bstr bstrClassName;
     1663    HRESULT hr = bstrClassName.assignEx("Win32_NetworkAdapterConfiguration");
     1664    if (SUCCEEDED(hr))
     1665    {
     1666        ComPtr<IWbemClassObject> pClass;
     1667        hr = pSvc->GetObject(bstrClassName.raw(), 0, NULL, pClass.asOutParam(), NULL);
    16911668        if (SUCCEEDED(hr))
    16921669        {
    16931670            ComPtr<IWbemClassObject> pOutParams;
    1694 
    1695             hr = netIfExecMethod(pSvc, pClass, ObjPath, bstr_t(L"EnableDHCP"), NULL, NULL, 0, pOutParams.asOutParam());
     1671            hr = netIfExecMethod(pSvc, pClass, rObjPath, "EnableDHCP", NULL, NULL, 0, pOutParams.asOutParam());
    16961672            if (SUCCEEDED(hr))
    16971673            {
    1698                 VARIANT varReturnValue;
    1699                 hr = pOutParams->Get(bstr_t(L"ReturnValue"), 0,
    1700                     &varReturnValue, NULL, 0);
    1701                 Assert(SUCCEEDED(hr));
     1674                com::Bstr bstrReturnValue;
     1675                hr = bstrReturnValue.assignEx("ReturnValue");
    17021676                if (SUCCEEDED(hr))
    17031677                {
    1704 //                    Assert(varReturnValue.vt == VT_UINT);
    1705                     int winEr = varReturnValue.uintVal;
    1706                     switch (winEr)
     1678                    VARIANT varReturnValue;
     1679                    VariantInit(&varReturnValue);
     1680                    hr = pOutParams->Get(bstrReturnValue.raw(), 0, &varReturnValue, NULL, 0);
     1681                    Assert(SUCCEEDED(hr));
     1682                    if (SUCCEEDED(hr))
    17071683                    {
    1708                     case 0:
    1709                         hr = S_OK;
    1710                         break;
    1711                     default:
    1712                         hr = HRESULT_FROM_WIN32( winEr );
    1713                         break;
     1684                        //Assert(varReturnValue.vt == VT_UINT);
     1685                        int winEr = varReturnValue.uintVal;
     1686                        switch (winEr)
     1687                        {
     1688                            case 0:
     1689                                hr = S_OK;
     1690                                break;
     1691                            default:
     1692                                hr = HRESULT_FROM_WIN32( winEr );
     1693                                break;
     1694                        }
    17141695                    }
    17151696                }
    17161697            }
    17171698        }
    1718         SysFreeString(ClassName);
    1719     }
    1720     else
    1721         hr = HRESULT_FROM_WIN32(GetLastError());
    1722 
    1723     return hr;
    1724 }
    1725 
    1726 static HRESULT netIfWinDhcpRediscover(IWbemServices * pSvc, BSTR ObjPath)
    1727 {
    1728     ComPtr<IWbemClassObject> pClass;
    1729     BSTR ClassName = SysAllocString(L"Win32_NetworkAdapterConfiguration");
    1730     HRESULT hr;
    1731     if (ClassName)
    1732     {
    1733         hr = pSvc->GetObject(ClassName, 0, NULL, pClass.asOutParam(), NULL);
     1699    }
     1700    return hr;
     1701}
     1702
     1703static HRESULT netIfWinDhcpRediscover(IWbemServices * pSvc, const com::Bstr &rObjPath)
     1704{
     1705    com::Bstr bstrClassName;
     1706    HRESULT hr = bstrClassName.assignEx("Win32_NetworkAdapterConfiguration");
     1707    if (SUCCEEDED(hr))
     1708    {
     1709        ComPtr<IWbemClassObject> pClass;
     1710        hr = pSvc->GetObject(bstrClassName.raw(), 0, NULL, pClass.asOutParam(), NULL);
    17341711        if (SUCCEEDED(hr))
    17351712        {
    17361713            ComPtr<IWbemClassObject> pOutParams;
    1737 
    1738             hr = netIfExecMethod(pSvc, pClass, ObjPath, bstr_t(L"ReleaseDHCPLease"), NULL, NULL, 0, pOutParams.asOutParam());
     1714            hr = netIfExecMethod(pSvc, pClass, rObjPath, "ReleaseDHCPLease", NULL, NULL, 0, pOutParams.asOutParam());
    17391715            if (SUCCEEDED(hr))
    17401716            {
    1741                 VARIANT varReturnValue;
    1742                 hr = pOutParams->Get(bstr_t(L"ReturnValue"), 0, &varReturnValue, NULL, 0);
    1743                 Assert(SUCCEEDED(hr));
     1717                com::Bstr bstrReturnValue;
     1718                hr = bstrReturnValue.assignEx("ReturnValue");
    17441719                if (SUCCEEDED(hr))
    17451720                {
    1746 //                    Assert(varReturnValue.vt == VT_UINT);
    1747                     int winEr = varReturnValue.uintVal;
    1748                     if (winEr == 0)
     1721                    VARIANT varReturnValue;
     1722                    VariantInit(&varReturnValue);
     1723                    hr = pOutParams->Get(bstrReturnValue.raw(), 0, &varReturnValue, NULL, 0);
     1724                    Assert(SUCCEEDED(hr));
     1725                    if (SUCCEEDED(hr))
    17491726                    {
    1750                         hr = netIfExecMethod(pSvc, pClass, ObjPath, bstr_t(L"RenewDHCPLease"), NULL, NULL, 0, pOutParams.asOutParam());
    1751                         if (SUCCEEDED(hr))
     1727                        //Assert(varReturnValue.vt == VT_UINT);
     1728                        int winEr = varReturnValue.uintVal;
     1729                        if (winEr == 0)
    17521730                        {
    1753                             hr = pOutParams->Get(bstr_t(L"ReturnValue"), 0, &varReturnValue, NULL, 0);
    1754                             Assert(SUCCEEDED(hr));
     1731                            hr = netIfExecMethod(pSvc, pClass, rObjPath, "RenewDHCPLease", NULL, NULL, 0, pOutParams.asOutParam());
    17551732                            if (SUCCEEDED(hr))
    17561733                            {
    1757             //                    Assert(varReturnValue.vt == VT_UINT);
    1758                                 winEr = varReturnValue.uintVal;
    1759                                 if (winEr == 0)
    1760                                     hr = S_OK;
    1761                                 else
    1762                                     hr = HRESULT_FROM_WIN32( winEr );
     1734                                hr = pOutParams->Get(bstrReturnValue.raw(), 0, &varReturnValue, NULL, 0);
     1735                                Assert(SUCCEEDED(hr));
     1736                                if (SUCCEEDED(hr))
     1737                                {
     1738                                    //Assert(varReturnValue.vt == VT_UINT);
     1739                                    winEr = varReturnValue.uintVal;
     1740                                    if (winEr == 0)
     1741                                        hr = S_OK;
     1742                                    else
     1743                                        hr = HRESULT_FROM_WIN32( winEr );
     1744                                }
    17631745                            }
    17641746                        }
     1747                        else
     1748                            hr = HRESULT_FROM_WIN32( winEr );
    17651749                    }
    1766                     else
    1767                         hr = HRESULT_FROM_WIN32( winEr );
    1768                 }
    1769             }
    1770         }
    1771         SysFreeString(ClassName);
    1772     }
    1773     else
    1774         hr = HRESULT_FROM_WIN32(GetLastError());
    1775 
    1776     return hr;
    1777 }
    1778 
    1779 static HRESULT vboxNetCfgWinIsDhcpEnabled(IWbemClassObject * pAdapterConfig, BOOL *pEnabled)
     1750                }
     1751            }
     1752        }
     1753    }
     1754
     1755    return hr;
     1756}
     1757
     1758static HRESULT vboxNetCfgWinIsDhcpEnabled(IWbemClassObject *pAdapterConfig, BOOL *pfEnabled)
    17801759{
    17811760    VARIANT vtEnabled;
     1761    VariantInit(&vtEnabled);
    17821762    HRESULT hr = pAdapterConfig->Get(L"DHCPEnabled", 0, &vtEnabled, 0, 0);
    17831763    if (SUCCEEDED(hr))
    1784         *pEnabled = vtEnabled.boolVal;
    1785     return hr;
    1786 }
    1787 
    1788 VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinGetAdapterSettings(IN const GUID * pGuid, OUT PADAPTER_SETTINGS pSettings)
    1789 {
    1790     HRESULT hr;
    1791     ComPtr <IWbemServices> pSvc;
    1792     hr = netIfWinCreateIWbemServices(pSvc.asOutParam());
     1764        *pfEnabled = vtEnabled.boolVal;
     1765    else
     1766        *pfEnabled = FALSE;
     1767    return hr;
     1768}
     1769
     1770VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinGetAdapterSettings(IN const GUID *pGuid, OUT PADAPTER_SETTINGS pSettings)
     1771{
     1772    ComPtr<IWbemServices> pSvc;
     1773    HRESULT hr = netIfWinCreateIWbemServices(pSvc.asOutParam());
    17931774    if (SUCCEEDED(hr))
    17941775    {
     
    18081789VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinIsDhcpEnabled(const GUID * pGuid, BOOL *pEnabled)
    18091790{
    1810     HRESULT hr;
    1811     ComPtr <IWbemServices> pSvc;
    1812     hr = netIfWinCreateIWbemServices(pSvc.asOutParam());
     1791    ComPtr<IWbemServices> pSvc;
     1792    HRESULT hr = netIfWinCreateIWbemServices(pSvc.asOutParam());
    18131793    if (SUCCEEDED(hr))
    18141794    {
     
    18381818        if (SUCCEEDED(hr))
    18391819        {
    1840             BOOL bIsHostOnly;
    1841             hr = netIfWinIsHostOnly(pAdapterConfig, &bIsHostOnly);
     1820            BOOL fIsHostOnly;
     1821            hr = netIfWinIsHostOnly(pAdapterConfig, &fIsHostOnly);
    18421822            if (SUCCEEDED(hr))
    18431823            {
    1844                 if (bIsHostOnly)
     1824                if (fIsHostOnly)
    18451825                {
    18461826                    in_addr aIp[1];
    18471827                    in_addr aMask[1];
    1848                     aIp[0].S_un.S_addr = ip;
     1828                    aIp[0].S_un.S_addr   = ip;
    18491829                    aMask[0].S_un.S_addr = mask;
    18501830
    1851                     BSTR ObjPath;
    1852                     hr = netIfWinAdapterConfigPath(pAdapterConfig, &ObjPath);
     1831                    com::Bstr bstrObjPath;
     1832                    hr = netIfWinAdapterConfigPath(pAdapterConfig, &bstrObjPath);
    18531833                    if (SUCCEEDED(hr))
    18541834                    {
    1855                         hr = netIfWinEnableStaticV4(pSvc, pGuid, ObjPath, aIp, aMask, ip != 0 ? 1 : 0);
     1835                        hr = netIfWinEnableStaticV4(pSvc, pGuid, bstrObjPath, aIp, aMask, ip != 0 ? 1 : 0);
    18561836                        if (SUCCEEDED(hr))
    18571837                        {
     
    18591839                            in_addr aGw[1];
    18601840                            aGw[0].S_un.S_addr = gw;
    1861                             hr = netIfWinSetGatewaysV4(pSvc, ObjPath, aGw, 1);
     1841                            hr = netIfWinSetGatewaysV4(pSvc, bstrObjPath, aGw, 1);
    18621842                            if (SUCCEEDED(hr))
    18631843#endif
     
    18651845                            }
    18661846                        }
    1867                         SysFreeString(ObjPath);
    18681847                    }
    18691848                }
     
    18761855    }
    18771856
    1878     NonStandardLogFlow(("VBoxNetCfgWinEnableStaticIpConfig: returns 0x%x\n", hr));
     1857    NonStandardLogFlow(("VBoxNetCfgWinEnableStaticIpConfig: returns %Rhrc\n", hr));
    18791858    return hr;
    18801859}
     
    18841863{
    18851864    HRESULT hr;
    1886         ComPtr <IWbemServices> pSvc;
     1865        ComPtr<IWbemServices> pSvc;
    18871866        hr = netIfWinCreateIWbemServices(pSvc.asOutParam());
    18881867        if (SUCCEEDED(hr))
     
    19311910VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinEnableDynamicIpConfig(IN const GUID *pGuid)
    19321911{
    1933     HRESULT hr;
    1934         ComPtr <IWbemServices> pSvc;
    1935         hr = netIfWinCreateIWbemServices(pSvc.asOutParam());
    1936         if (SUCCEEDED(hr))
    1937         {
    1938             ComPtr<IWbemClassObject> pAdapterConfig;
    1939             hr = netIfWinFindAdapterClassById(pSvc, pGuid, pAdapterConfig.asOutParam());
    1940             if (SUCCEEDED(hr))
    1941             {
    1942                 BOOL bIsHostOnly;
    1943                 hr = netIfWinIsHostOnly(pAdapterConfig, &bIsHostOnly);
    1944                 if (SUCCEEDED(hr))
    1945                 {
    1946                     if (bIsHostOnly)
    1947                     {
    1948                         BSTR ObjPath;
    1949                         hr = netIfWinAdapterConfigPath(pAdapterConfig, &ObjPath);
    1950                         if (SUCCEEDED(hr))
    1951                         {
    1952                             hr = netIfWinEnableDHCP(pSvc, ObjPath);
    1953                             if (SUCCEEDED(hr))
    1954                             {
    1955 //                              hr = netIfWinUpdateConfig(pIf);
    1956                             }
    1957                             SysFreeString(ObjPath);
    1958                         }
    1959                     }
    1960                     else
    1961                     {
    1962                         hr = E_FAIL;
    1963                     }
    1964                 }
    1965             }
    1966         }
    1967 
    1968 
    1969     return hr;
    1970 }
    1971 
    1972 VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinDhcpRediscover(IN const GUID *pGuid)
    1973 {
    1974     HRESULT hr;
    1975     ComPtr <IWbemServices> pSvc;
    1976     hr = netIfWinCreateIWbemServices(pSvc.asOutParam());
     1912    ComPtr<IWbemServices> pSvc;
     1913    HRESULT hr = netIfWinCreateIWbemServices(pSvc.asOutParam());
    19771914    if (SUCCEEDED(hr))
    19781915    {
     
    19811918        if (SUCCEEDED(hr))
    19821919        {
    1983             BOOL bIsHostOnly;
    1984             hr = netIfWinIsHostOnly(pAdapterConfig, &bIsHostOnly);
     1920            BOOL fIsHostOnly;
     1921            hr = netIfWinIsHostOnly(pAdapterConfig, &fIsHostOnly);
    19851922            if (SUCCEEDED(hr))
    19861923            {
    1987                 if (bIsHostOnly)
    1988                 {
    1989                     BSTR ObjPath;
    1990                     hr = netIfWinAdapterConfigPath(pAdapterConfig, &ObjPath);
     1924                if (fIsHostOnly)
     1925                {
     1926                    com::Bstr bstrObjPath;
     1927                    hr = netIfWinAdapterConfigPath(pAdapterConfig, &bstrObjPath);
    19911928                    if (SUCCEEDED(hr))
    19921929                    {
    1993                         hr = netIfWinDhcpRediscover(pSvc, ObjPath);
     1930                        hr = netIfWinEnableDHCP(pSvc, bstrObjPath);
    19941931                        if (SUCCEEDED(hr))
    19951932                        {
    19961933                            //hr = netIfWinUpdateConfig(pIf);
    19971934                        }
    1998                         SysFreeString(ObjPath);
    19991935                    }
    20001936                }
    20011937                else
    2002                 {
    20031938                    hr = E_FAIL;
    2004                 }
    2005             }
    2006         }
    2007     }
    2008 
    2009 
    2010     return hr;
    2011 }
    2012 
    2013 static const char *vboxNetCfgWinAddrToStr(char *pszBuf, LPSOCKADDR pAddr)
     1939            }
     1940        }
     1941    }
     1942    return hr;
     1943}
     1944
     1945VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinDhcpRediscover(IN const GUID *pGuid)
     1946{
     1947    ComPtr<IWbemServices> pSvc;
     1948    HRESULT hr = netIfWinCreateIWbemServices(pSvc.asOutParam());
     1949    if (SUCCEEDED(hr))
     1950    {
     1951        ComPtr<IWbemClassObject> pAdapterConfig;
     1952        hr = netIfWinFindAdapterClassById(pSvc, pGuid, pAdapterConfig.asOutParam());
     1953        if (SUCCEEDED(hr))
     1954        {
     1955            BOOL fIsHostOnly;
     1956            hr = netIfWinIsHostOnly(pAdapterConfig, &fIsHostOnly);
     1957            if (SUCCEEDED(hr))
     1958            {
     1959                if (fIsHostOnly)
     1960                {
     1961                    com::Bstr bstrObjPath;
     1962                    hr = netIfWinAdapterConfigPath(pAdapterConfig, &bstrObjPath);
     1963                    if (SUCCEEDED(hr))
     1964                    {
     1965                        hr = netIfWinDhcpRediscover(pSvc, bstrObjPath);
     1966                        if (SUCCEEDED(hr))
     1967                        {
     1968                            //hr = netIfWinUpdateConfig(pIf);
     1969                        }
     1970                    }
     1971                }
     1972                else
     1973                    hr = E_FAIL;
     1974            }
     1975        }
     1976    }
     1977
     1978
     1979    return hr;
     1980}
     1981
     1982static const char *vboxNetCfgWinAddrToStr(char *pszBuf, size_t cbBuf, LPSOCKADDR pAddr)
    20141983{
    20151984    switch (pAddr->sa_family)
    20161985    {
    20171986        case AF_INET:
    2018             sprintf(pszBuf, "%d.%d.%d.%d",
    2019                     ((PSOCKADDR_IN)pAddr)->sin_addr.S_un.S_un_b.s_b1,
    2020                     ((PSOCKADDR_IN)pAddr)->sin_addr.S_un.S_un_b.s_b2,
    2021                     ((PSOCKADDR_IN)pAddr)->sin_addr.S_un.S_un_b.s_b3,
    2022                     ((PSOCKADDR_IN)pAddr)->sin_addr.S_un.S_un_b.s_b4);
     1987            RTStrPrintf(pszBuf, cbBuf, "%d.%d.%d.%d",
     1988                        ((PSOCKADDR_IN)pAddr)->sin_addr.S_un.S_un_b.s_b1,
     1989                        ((PSOCKADDR_IN)pAddr)->sin_addr.S_un.S_un_b.s_b2,
     1990                        ((PSOCKADDR_IN)pAddr)->sin_addr.S_un.S_un_b.s_b3,
     1991                        ((PSOCKADDR_IN)pAddr)->sin_addr.S_un.S_un_b.s_b4);
    20231992            break;
    20241993        case AF_INET6:
    2025             sprintf(pszBuf, "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",
    2026                  ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[0], ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[1],
    2027                  ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[2], ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[3],
    2028                  ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[4], ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[5],
    2029                  ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[6], ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[7],
    2030                  ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[8], ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[9],
    2031                  ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[10], ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[11],
    2032                  ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[12], ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[13],
    2033                  ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[14], ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[15]);
     1994            RTStrPrintf(pszBuf, cbBuf, "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",
     1995                        ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[0], ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[1],
     1996                        ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[2], ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[3],
     1997                        ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[4], ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[5],
     1998                        ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[6], ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[7],
     1999                        ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[8], ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[9],
     2000                        ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[10], ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[11],
     2001                        ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[12], ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[13],
     2002                        ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[14], ((PSOCKADDR_IN6)pAddr)->sin6_addr.s6_addr[15]);
    20342003            break;
    20352004        default:
    2036             strcpy(pszBuf, "unknown");
     2005            RTStrCopy(pszBuf, cbBuf, "unknown");
    20372006            break;
    20382007    }
     
    20472016    for (pAdapter = pAddresses; pAdapter; pAdapter = pAdapter->Next)
    20482017    {
    2049         char szBuf[80];
    2050 
    20512018        NonStandardLogFlow(("+- Enumerating adapter '%ls' %s\n", pAdapter->FriendlyName, pAdapter->AdapterName));
    20522019        for (PIP_ADAPTER_PREFIX pPrefix = pAdapter->FirstPrefix; pPrefix; pPrefix = pPrefix->Next)
    20532020        {
    2054             const char *pcszAddress = vboxNetCfgWinAddrToStr(szBuf, pPrefix->Address.lpSockaddr);
     2021            char szBuf[80];
     2022            const char *pcszAddress = vboxNetCfgWinAddrToStr(szBuf, sizeof(szBuf), pPrefix->Address.lpSockaddr);
     2023
    20552024            /* We are concerned with IPv4 only, ignore the rest. */
    20562025            if (pPrefix->Address.lpSockaddr->sa_family != AF_INET)
     
    20592028                continue;
    20602029            }
     2030
    20612031            /* Ignore invalid prefixes as well as host addresses. */
    20622032            if (pPrefix->PrefixLength < 1 || pPrefix->PrefixLength > 31)
     
    20652035                continue;
    20662036            }
     2037
    20672038            /* Ignore multicast and beyond. */
    20682039            ULONG ip = ((struct sockaddr_in *)pPrefix->Address.lpSockaddr)->sin_addr.s_addr;
     
    20722043                continue;
    20732044            }
     2045
    20742046            ULONG mask = htonl((~(((ULONG)~0) >> pPrefix->PrefixLength)));
    20752047            bool fContinue = pfnCallback(ip, mask, pContext);
     
    20792051                return;
    20802052            }
    2081             else
    2082                 NonStandardLogFlow(("| +- %s %d: no conflict, moving on\n", pcszAddress, pPrefix->PrefixLength));
     2053
     2054            NonStandardLogFlow(("| +- %s %d: no conflict, moving on\n", pcszAddress, pPrefix->PrefixLength));
    20832055        }
    20842056    }
     
    20882060{
    20892061    ULONG Prefix;
    2090     bool bConflict;
     2062    bool fConflict;
    20912063}IPPROBE_CONTEXT, *PIPPROBE_CONTEXT;
    20922064
    2093 #define IPPROBE_INIT(_pContext, _addr) \
    2094     ((_pContext)->bConflict = false, \
    2095      (_pContext)->Prefix = _addr)
    2096 
    2097 #define IPPROBE_INIT_STR(_pContext, _straddr) \
    2098     IPROBE_INIT(_pContext, inet_addr(_straddr))
     2065#define IPPROBE_INIT(a_pContext, a_addr) \
     2066    do { (a_pContext)->fConflict = false; (a_pContext)->Prefix = (a_addr); } while (0)
     2067
     2068#define IPPROBE_INIT_STR(a_pContext, a_straddr) \
     2069    IPROBE_INIT(a_pContext, inet_addr(_straddr))
    20992070
    21002071static bool vboxNetCfgWinIpProbeCallback (ULONG ip, ULONG mask, PVOID pContext)
     
    21042075    if ((ip & mask) == (pProbe->Prefix & mask))
    21052076    {
    2106         pProbe->bConflict = true;
     2077        pProbe->fConflict = true;
    21072078        return false;
    21082079    }
     
    21132084VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinGenHostOnlyNetworkNetworkIp(OUT PULONG pNetIp, OUT PULONG pNetMask)
    21142085{
    2115     DWORD dwRc;
    21162086    HRESULT hr = S_OK;
     2087
     2088    *pNetIp   = 0;
     2089    *pNetMask = 0;
     2090
    21172091    /*
    21182092     * MSDN recommends to pre-allocate a 15KB buffer.
    21192093     */
    2120     ULONG uBufLen = 15 * 1024;
    2121     PIP_ADAPTER_ADDRESSES pAddresses = (PIP_ADAPTER_ADDRESSES)malloc(uBufLen);
    2122     if (!pAddresses)
    2123         return HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY);
    2124     dwRc = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, pAddresses, &uBufLen);
     2094    ULONG                 cbBuf       = 15 * _1K;
     2095    PIP_ADAPTER_ADDRESSES paAddresses = (PIP_ADAPTER_ADDRESSES)RTMemAllocZ(cbBuf);
     2096    if (!paAddresses)
     2097        return E_OUTOFMEMORY;
     2098    DWORD dwRc = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, paAddresses, &cbBuf);
    21252099    if (dwRc == ERROR_BUFFER_OVERFLOW)
    21262100    {
    21272101        /* Impressive! More than 10 adapters! Get more memory and try again. */
    2128         free(pAddresses);
    2129         pAddresses = (PIP_ADAPTER_ADDRESSES)malloc(uBufLen);
    2130         if (!pAddresses)
    2131             return HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY);
    2132         dwRc = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, pAddresses, &uBufLen);
     2102        RTMemFree(paAddresses);
     2103        paAddresses = (PIP_ADAPTER_ADDRESSES)RTMemAllocZ(cbBuf);
     2104        if (!paAddresses)
     2105            return E_OUTOFMEMORY;
     2106        dwRc = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, paAddresses, &cbBuf);
    21332107    }
    21342108    if (dwRc == NO_ERROR)
    21352109    {
    2136         IPPROBE_CONTEXT Context;
    21372110        const ULONG ip192168 = inet_addr("192.168.0.0");
    2138         srand(GetTickCount());
    2139 
    2140         *pNetIp = 0;
    2141         *pNetMask = 0;
    2142 
    2143         for (int i = 0; i < 255; i++)
    2144         {
    2145             ULONG ipProbe = rand()*255/RAND_MAX;
     2111        for (int i = 0; i < 384; i++)
     2112        {
     2113#if 0
     2114            ULONG ipProbe = rand()*255 / RAND_MAX;
     2115#else
     2116            uint32_t ipProbe = RTRandU32Ex(0, 255);
     2117#endif
    21462118            ipProbe = ip192168 | (ipProbe << 16);
    2147             unsigned char *a = (unsigned char *)&ipProbe;
    2148             NonStandardLogFlow(("probing %d.%d.%d.%d\n", a[0], a[1], a[2], a[3]));
     2119            NonStandardLogFlow(("probing %RTnaipv4\n", ipProbe));
     2120
     2121            IPPROBE_CONTEXT Context;
    21492122            IPPROBE_INIT(&Context, ipProbe);
    2150             vboxNetCfgWinEnumIpConfig(pAddresses, vboxNetCfgWinIpProbeCallback, &Context);
    2151             if (!Context.bConflict)
    2152             {
    2153                 NonStandardLogFlow(("found unused net %d.%d.%d.%d\n", a[0], a[1], a[2], a[3]));
     2123            vboxNetCfgWinEnumIpConfig(paAddresses, vboxNetCfgWinIpProbeCallback, &Context);
     2124            if (!Context.fConflict)
     2125            {
     2126                NonStandardLogFlow(("found unused net %RTnaipv4\n", ipProbe));
    21542127                *pNetIp = ipProbe;
    21552128                *pNetMask = inet_addr("255.255.255.0");
     
    21612134    }
    21622135    else
    2163         NonStandardLogFlow(("GetAdaptersAddresses err (%d)\n", dwRc));
    2164 
    2165     if (pAddresses)
    2166         free(pAddresses);
     2136        NonStandardLogFlow(("GetAdaptersAddresses err (%u)\n", dwRc));
     2137
     2138    RTMemFree(paAddresses);
    21672139
    21682140    if (dwRc != NO_ERROR)
    2169     {
    21702141        hr = HRESULT_FROM_WIN32(dwRc);
    2171     }
    2172 
    21732142    return hr;
    21742143}
     
    21892158
    21902159        hr = VBoxNetCfgWinUninstallComponent(pNc, pNcc);
    2191         NonStandardLogFlow(("NetFlt component uninstallation ended with hr (0x%x)\n", hr));
     2160        NonStandardLogFlow(("NetFlt component uninstallation ended with hr (%Rhrc)\n", hr));
    21922161
    21932162        pNcc->Release();
    21942163    }
    21952164    else if (hr == S_FALSE)
    2196     {
    21972165        NonStandardLog("NetFlt is not installed currently\n");
    2198     }
    21992166    else
    2200     {
    2201         NonStandardLogFlow(("FindComponent failed, hr (0x%x)\n", hr));
    2202     }
     2167        NonStandardLogFlow(("FindComponent failed: %Rhrc\n", hr));
    22032168
    22042169    VBoxDrvCfgInfUninstallAllF(L"NetService", VBOXNETCFGWIN_NETFLT_ID, InfRmFlags);
     
    22132178}
    22142179
    2215 VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinNetFltInstall(IN INetCfg *pNc,
    2216                                                        IN LPCWSTR const *apInfFullPaths, IN UINT cInfFullPaths)
     2180VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinNetFltInstall(IN INetCfg *pNc, IN LPCWSTR const *pwszInfFullPath, IN UINT cInfFullPaths)
    22172181{
    22182182    HRESULT hr = vboxNetCfgWinNetFltUninstall(pNc, SUOI_FORCEDELETE);
     
    22222186        hr = vboxNetCfgWinInstallInfAndComponent(pNc, VBOXNETCFGWIN_NETFLT_ID,
    22232187                                                 &GUID_DEVCLASS_NETSERVICE,
    2224                                                  apInfFullPaths,
     2188                                                 pwszInfFullPath,
    22252189                                                 cInfFullPaths,
    22262190                                                 NULL);
     
    22452209
    22462210VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinNetAdpInstall(IN INetCfg *pNc,
    2247                                                        IN LPCWSTR const pInfFullPath)
     2211                                                       IN LPCWSTR const pwszInfFullPath)
    22482212{
    22492213    NonStandardLog("NetAdp will be installed ...\n");
    2250     HRESULT hr = vboxNetCfgWinInstallInfAndComponent(pNc, VBOXNETCFGWIN_NETADP_ID,
    2251                                              &GUID_DEVCLASS_NET,
    2252                                              &pInfFullPath,
    2253                                              1,
    2254                                              NULL);
    2255     return hr;
    2256 }
    2257 
    2258 #define VBOXNETCFGWIN_NETLWF_ID    L"oracle_VBoxNetLwf"
     2214    HRESULT hr = vboxNetCfgWinInstallInfAndComponent(pNc, VBOXNETCFGWIN_NETADP_ID_WSZ,
     2215                                                     &GUID_DEVCLASS_NET,
     2216                                                     &pwszInfFullPath,
     2217                                                     1,
     2218                                                     NULL);
     2219    return hr;
     2220}
     2221
    22592222
    22602223static HRESULT vboxNetCfgWinNetLwfUninstall(IN INetCfg *pNc, DWORD InfRmFlags)
     
    22772240    else
    22782241    {
    2279         NonStandardLogFlow(("FindComponent failed, hr (0x%x)\n", hr));
     2242        NonStandardLogFlow(("FindComponent failed: %Rhrc\n", hr));
    22802243        hr = S_OK;
    22812244    }
     
    22992262     * See @bugref{7899}.
    23002263     */
    2301     HKEY hNetKey;
    2302     DWORD dwMaxNumFilters = 0;
    2303     DWORD cbMaxNumFilters = sizeof(dwMaxNumFilters);
    2304     LONG hr = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
    2305                            _T("SYSTEM\\CurrentControlSet\\Control\\Network"),
    2306                            0, KEY_QUERY_VALUE | KEY_SET_VALUE, &hNetKey);
    2307     if (SUCCEEDED(hr))
    2308     {
    2309         hr = RegQueryValueEx(hNetKey, _T("MaxNumFilters"), NULL, NULL,
    2310                              (LPBYTE)&dwMaxNumFilters, &cbMaxNumFilters);
    2311         if (SUCCEEDED(hr) && cbMaxNumFilters == sizeof(dwMaxNumFilters) && dwMaxNumFilters == 8)
     2264    /** @todo r=bird: This code was mixing HRESULT and LSTATUS, checking the return
     2265     * codes using SUCCEEDED(lrc) instead of lrc == ERROR_SUCCESS.  So, it might
     2266     * have misbehaved on bogus registry content, but worked fine on sane values. */
     2267    HKEY hKeyNet = NULL;
     2268    LSTATUS lrc = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\Network", 0,
     2269                                KEY_QUERY_VALUE | KEY_SET_VALUE, &hKeyNet);
     2270    if (lrc == ERROR_SUCCESS)
     2271    {
     2272        DWORD dwMaxNumFilters = 0;
     2273        DWORD cbMaxNumFilters = sizeof(dwMaxNumFilters);
     2274        lrc = RegQueryValueExW(hKeyNet, L"MaxNumFilters", NULL, NULL, (LPBYTE)&dwMaxNumFilters, &cbMaxNumFilters);
     2275        if (lrc == ERROR_SUCCESS && cbMaxNumFilters == sizeof(dwMaxNumFilters) && dwMaxNumFilters == 8)
    23122276        {
    23132277            dwMaxNumFilters = 14;
    2314             hr = RegSetValueEx(hNetKey, _T("MaxNumFilters"), 0, REG_DWORD,
    2315                              (LPBYTE)&dwMaxNumFilters, sizeof(dwMaxNumFilters));
    2316             if (SUCCEEDED(hr))
     2278            lrc = RegSetValueExW(hKeyNet, L"MaxNumFilters", 0, REG_DWORD, (LPBYTE)&dwMaxNumFilters, sizeof(dwMaxNumFilters));
     2279            if (lrc == ERROR_SUCCESS)
    23172280                NonStandardLog("Adjusted the installed filter limit to 14...\n");
    23182281            else
    2319                 NonStandardLog("Failed to set MaxNumFilters, error code 0x%x\n", hr);
    2320         }
    2321         RegCloseKey(hNetKey);
     2282                NonStandardLog("Failed to set MaxNumFilters, error code %d\n", lrc);
     2283        }
     2284        RegCloseKey(hKeyNet);
    23222285    }
    23232286    else
    2324     {
    2325         NonStandardLog("Failed to open network key, error code 0x%x\n", hr);
    2326     }
    2327 
    2328 }
    2329 
    2330 VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinNetLwfInstall(IN INetCfg *pNc,
    2331                                                        IN LPCWSTR const pInfFullPath)
     2287        NonStandardLog("Failed to open network key, error code %d\n", lrc);
     2288
     2289}
     2290
     2291VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinNetLwfInstall(IN INetCfg *pNc, IN LPCWSTR const pwszInfFullPath)
    23322292{
    23332293    HRESULT hr = vboxNetCfgWinNetLwfUninstall(pNc, SUOI_FORCEDELETE);
     
    23382298        hr = vboxNetCfgWinInstallInfAndComponent(pNc, VBOXNETCFGWIN_NETLWF_ID,
    23392299                                                 &GUID_DEVCLASS_NETSERVICE,
    2340                                                  &pInfFullPath,
     2300                                                 &pwszInfFullPath,
    23412301                                                 1,
    23422302                                                 NULL);
     
    23452305}
    23462306
    2347 #define VBOX_CONNECTION_NAME L"VirtualBox Host-Only Network"
    2348 VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinGenHostonlyConnectionName(PCWSTR DevName, WCHAR *pBuf, PULONG pcbBuf)
    2349 {
    2350     const WCHAR * pSuffix = wcsrchr( DevName, L'#' );
    2351     ULONG cbSize = sizeof(VBOX_CONNECTION_NAME);
    2352 
    2353     if (pSuffix)
    2354     {
    2355         cbSize += (ULONG)wcslen(pSuffix) * 2;
    2356         cbSize += 2; /* for space */
    2357     }
    2358 
    2359     if (*pcbBuf < cbSize)
    2360     {
    2361         *pcbBuf = cbSize;
    2362         return E_FAIL;
    2363     }
    2364 
    2365     wcscpy(pBuf, VBOX_CONNECTION_NAME);
    2366     if (pSuffix)
    2367     {
    2368         wcscat(pBuf, L" ");
    2369         wcscat(pBuf, pSuffix);
    2370     }
    2371 
    2372     return S_OK;
     2307VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinGenHostonlyConnectionName(IN PCWSTR pwszDevName, OUT WCHAR *pwszBuf,
     2308                                                                   IN ULONG cwcBuf, OUT PULONG pcwcNeeded)
     2309{
     2310    /* Look for a suffix that we need to preserve. */
     2311    size_t const cwcDevName = RTUtf16Len(pwszDevName);
     2312    size_t       offSuffix  = cwcDevName;
     2313    while (offSuffix > 0 && pwszDevName[offSuffix - 1] != '#')
     2314        offSuffix--;
     2315    size_t const cwcSuffix  = pwszDevName[offSuffix] != '#' ? 0 : cwcDevName - offSuffix;
     2316
     2317    /* Calculate required buffer size: */
     2318    size_t cwcNeeded = sizeof(VBOX_CONNECTION_NAME_WSZ) / sizeof(wchar_t) /* includes terminator */
     2319                     + !!cwcSuffix /*space*/ + cwcSuffix;
     2320    if (pcwcNeeded)
     2321        *pcwcNeeded = (ULONG)cwcNeeded;
     2322
     2323    if (cwcNeeded <= cwcBuf)
     2324    {
     2325        memcpy(pwszBuf, VBOX_CONNECTION_NAME_WSZ, sizeof(VBOX_CONNECTION_NAME_WSZ));
     2326        if (cwcSuffix > 0)
     2327        {
     2328            size_t offDst = sizeof(VBOX_CONNECTION_NAME_WSZ) / sizeof(wchar_t) - 1;
     2329            pwszBuf[offDst++] = ' ';
     2330            memcpy(&pwszBuf[offDst], &pwszDevName[offSuffix], cwcSuffix * sizeof(wchar_t));
     2331            pwszBuf[offDst + cwcSuffix] = '\0';
     2332        }
     2333        return S_OK;
     2334    }
     2335    return E_FAIL;
    23732336}
    23742337
    23752338static BOOL vboxNetCfgWinAdjustHostOnlyNetworkInterfacePriority(IN INetCfg *pNc, IN INetCfgComponent *pNcc, PVOID pContext)
    23762339{
     2340    GUID * const pGuid = (GUID*)pContext;
    23772341    RT_NOREF1(pNc);
    2378     INetCfgComponentBindings *pNetCfgBindings;
    2379     GUID *pGuid = (GUID*)pContext;
    23802342
    23812343    /* Get component's binding. */
    2382     HRESULT hr = pNcc->QueryInterface(IID_INetCfgComponentBindings, (PVOID*)&pNetCfgBindings);
     2344    INetCfgComponentBindings *pNetCfgBindings = NULL;
     2345    HRESULT hr = pNcc->QueryInterface(IID_INetCfgComponentBindings, (PVOID *)&pNetCfgBindings);
    23832346    if (SUCCEEDED(hr))
    23842347    {
    23852348        /* Get binding path enumerator reference. */
    2386         IEnumNetCfgBindingPath *pEnumNetCfgBindPath;
     2349        IEnumNetCfgBindingPath *pEnumNetCfgBindPath = NULL;
    23872350        hr = pNetCfgBindings->EnumBindingPaths(EBP_BELOW, &pEnumNetCfgBindPath);
    23882351        if (SUCCEEDED(hr))
    23892352        {
    2390             bool bFoundIface = false;
     2353            bool fFoundIface = false;
    23912354            hr = pEnumNetCfgBindPath->Reset();
    23922355            do
    23932356            {
    2394                 INetCfgBindingPath *pNetCfgBindPath;
     2357                INetCfgBindingPath *pNetCfgBindPath = NULL;
    23952358                hr = pEnumNetCfgBindPath->Next(1, &pNetCfgBindPath, NULL);
    23962359                if (hr == S_OK)
     
    24222385                                            hr = pNetCfgBindings->MoveAfter(pNetCfgBindPath, NULL);
    24232386                                            if (FAILED(hr))
    2424                                                 NonStandardLogFlow(("Unable to move interface, hr (0x%x)\n", hr));
    2425                                             bFoundIface = true;
     2387                                                NonStandardLogFlow(("Unable to move interface: %Rhrc\n", hr));
     2388                                            fFoundIface = true;
     2389
    24262390                                            /*
    24272391                                             * Enable binding paths for host-only adapters bound to bridged filter
     
    24292393                                             */
    24302394                                            HRESULT hr2;
    2431                                             LPWSTR pwszHwId = NULL;
     2395                                            LPWSTR  pwszHwId = NULL;
    24322396                                            if ((hr2 = pNcc->GetId(&pwszHwId)) != S_OK)
    2433                                                 NonStandardLogFlow(("Failed to get HW ID, hr (0x%x)\n", hr2));
    2434                                             else if (_wcsnicmp(pwszHwId, VBOXNETCFGWIN_NETLWF_ID,
    2435                                                                sizeof(VBOXNETCFGWIN_NETLWF_ID)/2))
    2436                                                 NonStandardLogFlow(("Ignoring component %ls\n", pwszHwId));
    2437                                             else if ((hr2 = pNetCfgBindPath->IsEnabled()) != S_FALSE)
    2438                                                 NonStandardLogFlow(("Already enabled binding path, hr (0x%x)\n", hr2));
    2439                                             else if ((hr2 = pNetCfgBindPath->Enable(TRUE)) != S_OK)
    2440                                                 NonStandardLogFlow(("Failed to enable binding path, hr (0x%x)\n", hr2));
     2397                                                NonStandardLogFlow(("Failed to get HW ID: %Rhrc\n", hr2));
    24412398                                            else
    2442                                                 NonStandardLogFlow(("Enabled binding path\n"));
    2443                                             if (pwszHwId)
     2399                                            {
     2400                                                /** @todo r=bird: Original was:
     2401                                                 *    _wcsnicmp(pwszHwId, VBOXNETCFGWIN_NETLWF_ID, sizeof(VBOXNETCFGWIN_NETLWF_ID)/2)
     2402                                                 * which is the same as _wcsicmp. Not sure if this was accidental, but it's not the
     2403                                                 * only one in this code area (VBoxNetFltNobj.cpp had some too IIRC). */
     2404                                                if (RTUtf16ICmp(pwszHwId, VBOXNETCFGWIN_NETLWF_ID) != 0)
     2405                                                    NonStandardLogFlow(("Ignoring component %ls\n", pwszHwId));
     2406                                                else if ((hr2 = pNetCfgBindPath->IsEnabled()) != S_FALSE)
     2407                                                    NonStandardLogFlow(("Already enabled binding path: %Rhrc\n", hr2));
     2408                                                else if ((hr2 = pNetCfgBindPath->Enable(TRUE)) != S_OK)
     2409                                                    NonStandardLogFlow(("Failed to enable binding path: %Rhrc\n", hr2));
     2410                                                else
     2411                                                    NonStandardLogFlow(("Enabled binding path\n"));
    24442412                                                CoTaskMemFree(pwszHwId);
     2413                                            }
    24452414                                        }
    24462415                                    }
     
    24482417                                }
    24492418                                else
    2450                                     NonStandardLogFlow(("GetLowerComponent failed, hr (0x%x)\n", hr));
     2419                                    NonStandardLogFlow(("GetLowerComponent failed: %Rhrc\n", hr));
    24512420                                pNetCfgBindIfce->Release();
    24522421                            }
     
    24562425                                    hr = S_OK;
    24572426                                else
    2458                                     NonStandardLogFlow(("Next binding interface failed, hr (0x%x)\n", hr));
     2427                                    NonStandardLogFlow(("Next binding interface failed: %Rhrc\n", hr));
    24592428                                break;
    24602429                            }
    2461                         } while (!bFoundIface);
     2430                        } while (!fFoundIface);
    24622431                        pEnumNetCfgBindIface->Release();
    24632432                    }
    24642433                    else
    2465                         NonStandardLogFlow(("EnumBindingInterfaces failed, hr (0x%x)\n", hr));
     2434                        NonStandardLogFlow(("EnumBindingInterfaces failed: %Rhrc\n", hr));
    24662435                    pNetCfgBindPath->Release();
    24672436                }
     
    24712440                        hr = S_OK;
    24722441                    else
    2473                         NonStandardLogFlow(("Next bind path failed, hr (0x%x)\n", hr));
     2442                        NonStandardLogFlow(("Next bind path failed: %Rhrc\n", hr));
    24742443                    break;
    24752444                }
    2476             } while (!bFoundIface);
     2445            } while (!fFoundIface);
    24772446            pEnumNetCfgBindPath->Release();
    24782447        }
    24792448        else
    2480             NonStandardLogFlow(("EnumBindingPaths failed, hr (0x%x)\n", hr));
     2449            NonStandardLogFlow(("EnumBindingPaths failed: %Rhrc\n", hr));
    24812450        pNetCfgBindings->Release();
    24822451    }
    24832452    else
    2484         NonStandardLogFlow(("QueryInterface for IID_INetCfgComponentBindings failed, hr (0x%x)\n", hr));
     2453        NonStandardLogFlow(("QueryInterface for IID_INetCfgComponentBindings failed: %Rhrc\n", hr));
    24852454    return TRUE;
    24862455}
    24872456
    2488 static UINT WINAPI vboxNetCfgWinPspFileCallback(
    2489         PVOID Context,
    2490         UINT Notification,
    2491         UINT_PTR Param1,
    2492         UINT_PTR Param2
    2493     )
     2457/** Callback for SetupDiSetDeviceInstallParams used  by
     2458 *  vboxNetCfgWinCreateHostOnlyNetworkInterface */
     2459static UINT WINAPI vboxNetCfgWinPspFileCallback(PVOID Context, UINT Notification, UINT_PTR Param1, UINT_PTR Param2)
    24942460{
    24952461    switch (Notification)
     
    24992465            return TRUE;
    25002466    }
    2501     return SetupDefaultQueueCallback(Context, Notification, Param1, Param2);
    2502 }
    2503 
    2504 /* The original source of the VBoxNetAdp adapter creation/destruction code has the following copyright */
     2467    return SetupDefaultQueueCallbackW(Context, Notification, Param1, Param2);
     2468}
     2469
     2470
     2471
     2472
     2473/* The original source of the VBoxNetAdp adapter creation/destruction code has the following copyright: */
    25052474/*
    25062475   Copyright 2004 by the Massachusetts Institute of Technology
     
    25302499 *  Use the IShellFolder API to rename the connection.
    25312500 */
    2532 static HRESULT rename_shellfolder (PCWSTR wGuid, PCWSTR wNewName)
    2533 {
     2501static HRESULT rename_shellfolder(PCWSTR pwszGuid, PCWSTR pwszNewName)
     2502{
     2503    /* Build the display name in the form "::{GUID}". Do this first in case it overflows. */
     2504    WCHAR wszAdapterGuid[MAX_PATH + 2] = {0};
     2505    ssize_t cwc = RTUtf16Printf(wszAdapterGuid, RT_ELEMENTS(wszAdapterGuid), "::%ls", pwszGuid);
     2506    if (cwc < 0)
     2507        return E_INVALIDARG;
     2508
    25342509    /* This is the GUID for the network connections folder. It is constant.
    25352510     * {7007ACC7-3202-11D1-AAD2-00805FC1270E} */
     
    25402515    };
    25412516
    2542     LPITEMIDLIST pidl = NULL;
     2517    /* Create an instance of the network connections folder. */
    25432518    IShellFolder *pShellFolder = NULL;
    2544     HRESULT hr;
    2545 
    2546     /* Build the display name in the form "::{GUID}". */
    2547     if (wcslen(wGuid) >= MAX_PATH)
    2548         return E_INVALIDARG;
    2549     WCHAR szAdapterGuid[MAX_PATH + 2] = {0};
    2550     swprintf(szAdapterGuid, L"::%ls", wGuid);
    2551 
    2552     /* Create an instance of the network connections folder. */
    2553     hr = CoCreateInstance(MY_CLSID_NetworkConnections, NULL,
    2554                           CLSCTX_INPROC_SERVER, IID_IShellFolder,
    2555                           reinterpret_cast<LPVOID *>(&pShellFolder));
    2556     /* Parse the display name. */
    2557     if (SUCCEEDED (hr))
    2558     {
    2559         hr = pShellFolder->ParseDisplayName (NULL, NULL, szAdapterGuid, NULL,
    2560                                              &pidl, NULL);
    2561     }
    2562     if (SUCCEEDED (hr))
    2563     {
    2564         hr = pShellFolder->SetNameOf (NULL, pidl, wNewName, SHGDN_NORMAL,
    2565                                       &pidl);
    2566     }
    2567 
    2568     CoTaskMemFree (pidl);
    2569 
    2570     if (pShellFolder)
     2519    HRESULT hr = CoCreateInstance(MY_CLSID_NetworkConnections, NULL, CLSCTX_INPROC_SERVER, IID_IShellFolder,
     2520                                  reinterpret_cast<LPVOID *>(&pShellFolder));
     2521    if (SUCCEEDED(hr))
     2522    {
     2523        /* Parse the display name. */
     2524        LPITEMIDLIST pidl = NULL;
     2525        hr = pShellFolder->ParseDisplayName(NULL, NULL, wszAdapterGuid, NULL, &pidl, NULL);
     2526        if (SUCCEEDED(hr))
     2527            hr = pShellFolder->SetNameOf(NULL, pidl, pwszNewName, SHGDN_NORMAL, &pidl);
     2528        CoTaskMemFree(pidl);
    25712529        pShellFolder->Release();
    2572 
     2530    }
    25732531    return hr;
    25742532}
     
    25782536 *
    25792537 * @returns Module handle or NULL
    2580  * @param   pszName             The DLL name.
     2538 * @param   pwszName            The DLL name.
    25812539 */
    2582 static HMODULE loadSystemDll(const char *pszName)
    2583 {
    2584     char   szPath[MAX_PATH];
    2585     UINT   cchPath = GetSystemDirectoryA(szPath, sizeof(szPath));
    2586     size_t cbName  = strlen(pszName) + 1;
    2587     if (cchPath + 1 + cbName > sizeof(szPath))
     2540static HMODULE loadSystemDll(const wchar_t *pwszName)
     2541{
     2542    WCHAR  wszPath[MAX_PATH];
     2543    UINT   cwcPath = GetSystemDirectoryW(wszPath, RT_ELEMENTS(wszPath));
     2544    size_t cwcName = RTUtf16Len(pwszName) + 1;
     2545    if (cwcPath + 1 + cwcName > RT_ELEMENTS(wszPath))
    25882546        return NULL;
    2589     szPath[cchPath] = '\\';
    2590     memcpy(&szPath[cchPath + 1], pszName, cbName);
    2591     return LoadLibraryA(szPath);
    2592 }
    2593 
    2594 static bool vboxNetCfgWinDetectStaleConnection(PCWSTR pName)
    2595 {
    2596     HKEY hkeyConnection, hkeyAdapter, hkeyAdapters;
    2597     WCHAR wszAdaptersKeyName[] = L"SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}";
    2598     WCHAR wszAdapterSubKeyName[MAX_PATH];
    2599     LSTATUS status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, wszAdaptersKeyName, 0, KEY_ALL_ACCESS, &hkeyAdapters);
    2600     if (status != ERROR_SUCCESS)
     2547
     2548    wszPath[cwcPath++] = '\\';
     2549    memcpy(&wszPath[cwcPath], pwszName, cwcName * sizeof(wszPath[0]));
     2550    return LoadLibraryW(wszPath);
     2551}
     2552
     2553static bool vboxNetCfgWinDetectStaleConnection(PCWSTR pwszName)
     2554{
     2555    HKEY    hKeyAdapters = NULL;
     2556    LSTATUS lrc = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
     2557                               L"SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}",
     2558                               0 /*ulOptions*/, KEY_ALL_ACCESS, &hKeyAdapters);
     2559    if (lrc != ERROR_SUCCESS)
    26012560        return false;
    26022561
     
    26042563    for (DWORD i = 0; !fFailureImminent; ++i)
    26052564    {
    2606         DWORD cbName = MAX_PATH;
    2607         status = RegEnumKeyEx(hkeyAdapters, i, wszAdapterSubKeyName, &cbName, NULL, NULL, NULL, NULL);
    2608         // if (status == ERROR_NO_MORE_ITEMS)
    2609         //     break;
    2610         if (status != ERROR_SUCCESS)
     2565        WCHAR wszAdapterSubKeyName[MAX_PATH];
     2566        DWORD cwcAdapterSubKeyName = MAX_PATH;
     2567        lrc = RegEnumKeyEx(hKeyAdapters, i, wszAdapterSubKeyName, &cwcAdapterSubKeyName, NULL, NULL, NULL, NULL);
     2568        if (lrc != ERROR_SUCCESS)
    26112569            break;
    26122570
    2613         status = RegOpenKeyEx(hkeyAdapters, wszAdapterSubKeyName, 0, KEY_ALL_ACCESS, &hkeyAdapter);
    2614         if (status == ERROR_SUCCESS)
    2615         {
    2616             status = RegOpenKeyEx(hkeyAdapter, L"Connection", 0, KEY_ALL_ACCESS, &hkeyConnection);
    2617             if (status == ERROR_SUCCESS)
    2618             {
    2619                 WCHAR wszName[MAX_PATH];
    2620                 cbName = MAX_PATH;
    2621                 status = RegQueryValueEx(hkeyConnection, L"Name", NULL, NULL, (LPBYTE)wszName, &cbName);
    2622                 if (status == ERROR_SUCCESS)
    2623                     if (wcsicmp(wszName, pName) == 0)
     2571        HKEY hKeyAdapter = NULL;
     2572        lrc = RegOpenKeyEx(hKeyAdapters, wszAdapterSubKeyName, 0, KEY_ALL_ACCESS, &hKeyAdapter);
     2573        if (lrc == ERROR_SUCCESS)
     2574        {
     2575            HKEY hKeyConnection = NULL;
     2576            lrc = RegOpenKeyEx(hKeyAdapter, L"Connection", 0, KEY_ALL_ACCESS, &hKeyConnection);
     2577            if (lrc == ERROR_SUCCESS)
     2578            {
     2579                WCHAR wszCurName[MAX_PATH + 1];
     2580                DWORD cbCurName = sizeof(wszCurName) - sizeof(WCHAR);
     2581                DWORD dwType    = REG_SZ;
     2582                lrc = RegQueryValueEx(hKeyConnection, L"Name", NULL, NULL, (LPBYTE)wszCurName, &cbCurName);
     2583                if (   lrc == ERROR_SUCCESS
     2584                    /** @todo r=bird: The original code didn't do any value type checks, thus allowing all SZ types. */
     2585                    && (dwType == REG_SZ || dwType == REG_EXPAND_SZ || dwType == REG_MULTI_SZ))
     2586                {
     2587                    wszCurName[MAX_PATH] = '\0'; /* returned values doesn't necessarily need to be terminated */
     2588
     2589                    if (RTUtf16ICmp(pwszName, pwszName) == 0)
    26242590                        fFailureImminent = true;
    2625                 RegCloseKey(hkeyConnection);
    2626             }
    2627             RegCloseKey(hkeyAdapter);
    2628         }
    2629     }
    2630     RegCloseKey(hkeyAdapters);
     2591                }
     2592                RegCloseKey(hKeyConnection);
     2593            }
     2594            RegCloseKey(hKeyAdapter);
     2595        }
     2596    }
     2597    RegCloseKey(hKeyAdapters);
    26312598
    26322599    return fFailureImminent;
    26332600}
    26342601
    2635 VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinRenameConnection (LPWSTR pGuid, PCWSTR NewName)
    2636 {
    2637     typedef HRESULT (WINAPI *lpHrRenameConnection) (const GUID *, PCWSTR);
    2638     lpHrRenameConnection RenameConnectionFunc = NULL;
    2639     HRESULT status;
    2640 
     2602VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinRenameConnection(LPWSTR pwszGuid, PCWSTR NewName)
     2603{
    26412604    /*
    26422605     * Before attempting to rename the connection, check if there is a stale
     
    26462609    if (vboxNetCfgWinDetectStaleConnection(NewName))
    26472610        return S_OK;
     2611
    26482612    /* First try the IShellFolder interface, which was unimplemented
    26492613     * for the network connections folder before XP. */
    2650     status = rename_shellfolder (pGuid, NewName);
    2651     if (status == E_NOTIMPL)
     2614    HRESULT hrc = rename_shellfolder(pwszGuid, NewName);
     2615    if (hrc == E_NOTIMPL)
    26522616    {
    26532617/** @todo that code doesn't seem to work! */
     
    26552619         * Try the (undocumented) HrRenameConnection API in the netshell
    26562620         * library. */
    2657         CLSID clsid;
    2658         HINSTANCE hNetShell;
    2659         status = CLSIDFromString ((LPOLESTR) pGuid, &clsid);
    2660         if (FAILED(status))
     2621        CLSID     clsid;
     2622        hrc = CLSIDFromString((LPOLESTR)pwszGuid, &clsid);
     2623        if (FAILED(hrc))
    26612624            return E_FAIL;
    2662         hNetShell = loadSystemDll("netshell.dll");
     2625
     2626        HINSTANCE hNetShell = loadSystemDll(L"netshell.dll");
    26632627        if (hNetShell == NULL)
    26642628            return E_FAIL;
    2665         RenameConnectionFunc =
    2666           (lpHrRenameConnection) GetProcAddress (hNetShell,
    2667                                                  "HrRenameConnection");
    2668         if (RenameConnectionFunc == NULL)
    2669         {
    2670             FreeLibrary (hNetShell);
    2671             return E_FAIL;
    2672         }
    2673         status = RenameConnectionFunc (&clsid, NewName);
    2674         FreeLibrary (hNetShell);
    2675     }
    2676     if (FAILED (status))
    2677         return status;
    2678 
     2629
     2630        typedef HRESULT (WINAPI *PFNHRRENAMECONNECTION)(const GUID *, PCWSTR);
     2631        PFNHRRENAMECONNECTION pfnRenameConnection = (PFNHRRENAMECONNECTION)GetProcAddress(hNetShell, "HrRenameConnection");
     2632        if (pfnRenameConnection != NULL)
     2633            hrc = pfnRenameConnection(&clsid, NewName);
     2634        else
     2635            hrc = E_FAIL;
     2636
     2637        FreeLibrary(hNetShell);
     2638    }
     2639    if (FAILED(hrc))
     2640        return hrc;
    26792641    return S_OK;
    26802642}
    26812643
    2682 #define DRIVERHWID _T("sun_VBoxNetAdp")
    2683 
    2684 #define SetErrBreak(strAndArgs) \
    2685     if (1) { \
    2686         hrc = E_FAIL; \
    2687         NonStandardLog strAndArgs; \
    2688         bstrError = bstr_printf strAndArgs; \
    2689         break; \
    2690     } else do {} while (0)
    2691 
    2692 VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinRemoveHostOnlyNetworkInterface(IN const GUID *pGUID, OUT BSTR *pErrMsg)
     2644
     2645VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinRemoveHostOnlyNetworkInterface(IN const GUID *pGUID, OUT BSTR *pBstrErrMsg)
    26932646{
    26942647    HRESULT hrc = S_OK;
    2695     bstr_t bstrError;
    2696 
    2697     do
    2698     {
    2699         TCHAR lszPnPInstanceId [512] = {0};
    2700 
    2701         /* We have to find the device instance ID through a registry search */
    2702 
    2703         HKEY hkeyNetwork = 0;
    2704         HKEY hkeyConnection = 0;
    2705 
    2706         do
    2707         {
    2708             WCHAR strRegLocation [256];
     2648    com::Bstr bstrError;
     2649
     2650    do /* break non-loop */
     2651    {
     2652        WCHAR wszPnPInstanceId[512] = {0};
     2653
     2654        /*
     2655         * We have to find the device instance ID through a registry search
     2656         */
     2657        HKEY hkeyNetwork    = NULL;
     2658        HKEY hkeyConnection = NULL;
     2659        do /* another non-loop for breaking out of */
     2660        {
    27092661            WCHAR wszGuid[50];
    2710 
    2711             int length = StringFromGUID2(*pGUID, wszGuid, RT_ELEMENTS(wszGuid));
    2712             if (!length)
     2662            int cwcGuid = StringFromGUID2(*pGUID, wszGuid, RT_ELEMENTS(wszGuid));
     2663            if (!cwcGuid)
    27132664                SetErrBreak(("Failed to create a Guid string"));
    27142665
    2715             swprintf (strRegLocation,
    2716                      L"SYSTEM\\CurrentControlSet\\Control\\Network\\"
    2717                      L"{4D36E972-E325-11CE-BFC1-08002BE10318}\\%s",
    2718                      wszGuid);
    2719 
    2720             LONG status;
    2721             status = RegOpenKeyExW (HKEY_LOCAL_MACHINE, strRegLocation, 0,
    2722                                     KEY_READ, &hkeyNetwork);
    2723             if ((status != ERROR_SUCCESS) || !hkeyNetwork)
    2724                 SetErrBreak (("Host interface network is not found in registry (%S) [1]",
    2725                     strRegLocation));
    2726 
    2727             status = RegOpenKeyExW (hkeyNetwork, L"Connection", 0,
    2728                                     KEY_READ, &hkeyConnection);
    2729             if ((status != ERROR_SUCCESS) || !hkeyConnection)
    2730                 SetErrBreak (("Host interface network is not found in registry (%S) [2]",
    2731                     strRegLocation));
    2732 
    2733             DWORD len = sizeof (lszPnPInstanceId);
    2734             DWORD dwKeyType;
    2735             status = RegQueryValueExW (hkeyConnection, L"PnPInstanceID", NULL,
    2736                                        &dwKeyType, (LPBYTE) lszPnPInstanceId, &len);
    2737             if ((status != ERROR_SUCCESS) || (dwKeyType != REG_SZ))
    2738                 SetErrBreak (("Host interface network is not found in registry (%S) [3]",
    2739                     strRegLocation));
    2740         }
    2741         while (0);
     2666            WCHAR wszRegLocation[128 + RT_ELEMENTS(wszGuid)];
     2667            RTUtf16Printf(wszRegLocation, RT_ELEMENTS(wszRegLocation),
     2668                          "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\%ls", wszGuid);
     2669
     2670            LSTATUS lrc = RegOpenKeyExW(HKEY_LOCAL_MACHINE, wszRegLocation, 0, KEY_READ, &hkeyNetwork);
     2671            if (lrc != ERROR_SUCCESS || !hkeyNetwork)
     2672                SetErrBreak(("Host interface network is not found in registry (%S): lrc=%u [1]", wszRegLocation, lrc));
     2673
     2674            lrc = RegOpenKeyExW(hkeyNetwork, L"Connection", 0, KEY_READ, &hkeyConnection);
     2675            if (lrc != ERROR_SUCCESS || !hkeyConnection)
     2676                SetErrBreak(("Host interface network is not found in registry (%S): lrc=%u [2]", wszRegLocation, lrc));
     2677
     2678            DWORD cbValue = sizeof(wszPnPInstanceId) - sizeof(WCHAR);
     2679            DWORD dwType  = ~0U;
     2680            lrc = RegQueryValueExW(hkeyConnection, L"PnPInstanceID", NULL, &dwType, (LPBYTE)wszPnPInstanceId, &cbValue);
     2681            if (lrc != ERROR_SUCCESS || dwType != REG_SZ)
     2682                SetErrBreak(("Host interface network is not found in registry (%S): lrc=%u, dwType=%u [3]",
     2683                             wszRegLocation, lrc, dwType));
     2684        } while (0);
    27422685
    27432686        if (hkeyConnection)
    2744             RegCloseKey (hkeyConnection);
     2687            RegCloseKey(hkeyConnection);
    27452688        if (hkeyNetwork)
    2746             RegCloseKey (hkeyNetwork);
    2747 
    2748         if (FAILED (hrc))
     2689            RegCloseKey(hkeyNetwork);
     2690        if (FAILED(hrc))
    27492691            break;
    27502692
     
    27532695         * wait until we encounter the right device instance ID
    27542696         */
    2755 
    27562697        HDEVINFO hDeviceInfo = INVALID_HANDLE_VALUE;
    2757 
    2758         do
    2759         {
    2760             BOOL ok;
     2698        do /* break-only, not-a-loop */
     2699        {
     2700            BOOL  ok;
     2701
     2702            /* initialize the structure size */
     2703            SP_DEVINFO_DATA DeviceInfoData = { sizeof(DeviceInfoData) };
     2704
     2705            /* copy the net class GUID */
    27612706            GUID netGuid;
    2762             SP_DEVINFO_DATA DeviceInfoData;
    2763             DWORD index = 0;
    2764             BOOL found = FALSE;
    2765             DWORD size = 0;
    2766 
    2767             /* initialize the structure size */
    2768             DeviceInfoData.cbSize = sizeof (SP_DEVINFO_DATA);
    2769 
    2770             /* copy the net class GUID */
    2771             memcpy(&netGuid, &GUID_DEVCLASS_NET, sizeof (GUID_DEVCLASS_NET));
     2707            memcpy(&netGuid, &GUID_DEVCLASS_NET, sizeof(GUID_DEVCLASS_NET));
    27722708
    27732709            /* return a device info set contains all installed devices of the Net class */
    27742710            hDeviceInfo = SetupDiGetClassDevs(&netGuid, NULL, NULL, DIGCF_PRESENT);
    2775 
    27762711            if (hDeviceInfo == INVALID_HANDLE_VALUE)
    27772712                SetErrBreak(("SetupDiGetClassDevs failed (0x%08X)", GetLastError()));
    27782713
    2779             /* enumerate the driver info list */
    2780             while (TRUE)
    2781             {
    2782                 TCHAR *deviceHwid;
    2783 
    2784                 ok = SetupDiEnumDeviceInfo(hDeviceInfo, index, &DeviceInfoData);
    2785 
    2786                 if (!ok)
     2714            /* Enumerate the driver info list. */
     2715            bool fFound = false;
     2716            for (DWORD index = 0; !fFound; index++)
     2717            {
     2718                if (!SetupDiEnumDeviceInfo(hDeviceInfo, index, &DeviceInfoData))
    27872719                {
    27882720                    if (GetLastError() == ERROR_NO_MORE_ITEMS)
    27892721                        break;
    2790                     else
    2791                     {
    2792                         index++;
    2793                         continue;
    2794                     }
     2722                    continue;
    27952723                }
    27962724
    27972725                /* try to get the hardware ID registry property */
    2798                 ok = SetupDiGetDeviceRegistryProperty(hDeviceInfo,
     2726                DWORD cbValue = 0;
     2727                if (SetupDiGetDeviceRegistryPropertyW(hDeviceInfo,
    27992728                                                      &DeviceInfoData,
    28002729                                                      SPDRP_HARDWAREID,
     
    28022731                                                      NULL,
    28032732                                                      0,
    2804                                                       &size);
    2805                 if (!ok)
    2806                 {
    2807                     if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
    2808                     {
    2809                         index++;
    2810                         continue;
    2811                     }
    2812 
    2813                     deviceHwid = (TCHAR *) malloc(size);
    2814                     ok = SetupDiGetDeviceRegistryProperty(hDeviceInfo,
    2815                                                           &DeviceInfoData,
    2816                                                           SPDRP_HARDWAREID,
    2817                                                           NULL,
    2818                                                           (PBYTE)deviceHwid,
    2819                                                           size,
    2820                                                           NULL);
    2821                     if (!ok)
    2822                     {
    2823                         free(deviceHwid);
    2824                         deviceHwid = NULL;
    2825                         index++;
    2826                         continue;
    2827                     }
    2828                 }
    2829                 else
    2830                 {
    2831                     /* something is wrong.  This shouldn't have worked with a NULL buffer */
    2832                     index++;
     2733                                                      &cbValue))
     2734                    continue; /* Something is wrong.  This shouldn't have worked with a NULL buffer! */
     2735                if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
    28332736                    continue;
    2834                 }
    2835 
    2836                 for (TCHAR *t = deviceHwid;
    2837                      t && *t && t < &deviceHwid[size / sizeof(TCHAR)];
    2838                      t += _tcslen(t) + 1)
    2839                 {
    2840                     if (!_tcsicmp(DRIVERHWID, t))
    2841                     {
    2842                           /* get the device instance ID */
    2843                           TCHAR devId[MAX_DEVICE_ID_LEN];
    2844                           if (CM_Get_Device_ID(DeviceInfoData.DevInst,
    2845                                                devId, MAX_DEVICE_ID_LEN, 0) == CR_SUCCESS)
    2846                           {
    2847                               /* compare to what we determined before */
    2848                               if (wcscmp(devId, lszPnPInstanceId) == 0)
    2849                               {
    2850                                   found = TRUE;
    2851                                   break;
    2852                               }
    2853                           }
    2854                     }
    2855                 }
    2856 
    2857                 if (deviceHwid)
    2858                 {
    2859                     free (deviceHwid);
    2860                     deviceHwid = NULL;
    2861                 }
    2862 
    2863                 if (found)
     2737
     2738                WCHAR *pwszzDeviceHwId = (WCHAR *)RTMemAllocZ(cbValue + sizeof(WCHAR) * 2);
     2739                if (!pwszzDeviceHwId)
    28642740                    break;
    2865 
    2866                 index++;
    2867             }
    2868 
    2869             if (found == FALSE)
    2870                 SetErrBreak (("Host Interface Network driver not found (0x%08X)",
    2871                               GetLastError()));
    2872 
    2873             ok = SetupDiSetSelectedDevice (hDeviceInfo, &DeviceInfoData);
     2741                if (SetupDiGetDeviceRegistryPropertyW(hDeviceInfo,
     2742                                                      &DeviceInfoData,
     2743                                                      SPDRP_HARDWAREID,
     2744                                                      NULL,
     2745                                                      (PBYTE)pwszzDeviceHwId,
     2746                                                      cbValue,
     2747                                                      &cbValue))
     2748                {
     2749                    /* search the string list. */
     2750                    for (WCHAR *pwszCurHwId = pwszzDeviceHwId;
     2751                         (uintptr_t)pwszCurHwId - (uintptr_t)pwszzDeviceHwId < cbValue && *pwszCurHwId != L'\0';
     2752                         pwszCurHwId += RTUtf16Len(pwszCurHwId) + 1)
     2753                        if (RTUtf16ICmp(DRIVERHWID, pwszCurHwId) == 0)
     2754                        {
     2755                            /* get the device instance ID */
     2756                            WCHAR wszDevId[MAX_DEVICE_ID_LEN];
     2757                            if (CM_Get_Device_IDW(DeviceInfoData.DevInst, wszDevId, MAX_DEVICE_ID_LEN, 0) == CR_SUCCESS)
     2758                            {
     2759                                /* compare to what we determined before */
     2760                                if (RTUtf16Cmp(wszDevId, wszPnPInstanceId) == 0)
     2761                                {
     2762                                    fFound = true;
     2763                                    break;
     2764                                }
     2765                            }
     2766                        }
     2767                }
     2768                RTMemFree(pwszzDeviceHwId);
     2769            }
     2770
     2771            if (!fFound)
     2772                SetErrBreak(("Host Interface Network driver not found (0x%08X)", GetLastError()));
     2773
     2774            ok = SetupDiSetSelectedDevice(hDeviceInfo, &DeviceInfoData);
    28742775            if (!ok)
    2875                 SetErrBreak (("SetupDiSetSelectedDevice failed (0x%08X)",
    2876                               GetLastError()));
    2877 
    2878             ok = SetupDiCallClassInstaller (DIF_REMOVE, hDeviceInfo, &DeviceInfoData);
     2776                SetErrBreak(("SetupDiSetSelectedDevice failed (0x%08X)", GetLastError()));
     2777
     2778            ok = SetupDiCallClassInstaller(DIF_REMOVE, hDeviceInfo, &DeviceInfoData);
    28792779            if (!ok)
    2880                 SetErrBreak (("SetupDiCallClassInstaller (DIF_REMOVE) failed (0x%08X)",
    2881                               GetLastError()));
    2882         }
    2883         while (0);
     2780                SetErrBreak(("SetupDiCallClassInstaller (DIF_REMOVE) failed (0x%08X)", GetLastError()));
     2781        } while (0);
    28842782
    28852783        /* clean up the device info set */
    28862784        if (hDeviceInfo != INVALID_HANDLE_VALUE)
    28872785            SetupDiDestroyDeviceInfoList (hDeviceInfo);
    2888 
    2889         if (FAILED (hrc))
    2890             break;
    2891     }
    2892     while (0);
    2893 
    2894     if (pErrMsg && bstrError.length())
    2895         *pErrMsg = bstrError.Detach();
    2896 
     2786    } while (0);
     2787
     2788    if (pBstrErrMsg)
     2789    {
     2790        *pBstrErrMsg = NULL;
     2791        if (bstrError.isNotEmpty())
     2792            bstrError.detachToEx(pBstrErrMsg);
     2793    }
    28972794    return hrc;
    28982795}
    28992796
    2900 VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinUpdateHostOnlyNetworkInterface(LPCWSTR pcsxwInf, BOOL *pbRebootRequired, LPCWSTR pcsxwId)
    2901 {
    2902     return VBoxDrvCfgDrvUpdate(pcsxwId, pcsxwInf, pbRebootRequired);
     2797VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinUpdateHostOnlyNetworkInterface(LPCWSTR pcsxwInf, BOOL *pfRebootRequired, LPCWSTR pcsxwId)
     2798{
     2799    return VBoxDrvCfgDrvUpdate(pcsxwId, pcsxwInf, pfRebootRequired);
    29032800}
    29042801
     
    29072804    switch (dwState)
    29082805    {
    2909         case SERVICE_STOPPED: return "is not running";
    2910         case SERVICE_STOP_PENDING: return "is stopping";
    2911         case SERVICE_CONTINUE_PENDING: return "continue is pending";
    2912         case SERVICE_PAUSE_PENDING: return "pause is pending";
    2913         case SERVICE_PAUSED: return "is paused";
    2914         case SERVICE_RUNNING: return "is running";
    2915         case SERVICE_START_PENDING: return "is starting";
     2806        case SERVICE_STOPPED:           return "is not running";
     2807        case SERVICE_STOP_PENDING:      return "is stopping";
     2808        case SERVICE_CONTINUE_PENDING:  return "continue is pending";
     2809        case SERVICE_PAUSE_PENDING:     return "pause is pending";
     2810        case SERVICE_PAUSED:            return "is paused";
     2811        case SERVICE_RUNNING:           return "is running";
     2812        case SERVICE_START_PENDING:     return "is starting";
    29162813    }
    29172814    return "state is invalid";
     
    29412838}
    29422839
    2943 typedef struct {
     2840typedef struct
     2841{
    29442842    BSTR bstrName;
    29452843    GUID *pGuid;
     
    29632861}
    29642862
    2965 /* We assume the following name matches the device description in vboxnetadp6.inf */
    2966 #define HOSTONLY_ADAPTER_NAME "VirtualBox Host-Only Ethernet Adapter"
    2967 
    2968 /*
     2863/**
    29692864 * Enumerate all host-only adapters collecting their names into a set, then
    29702865 * come up with the next available name by taking the first unoccupied index.
    29712866 */
    2972 static HRESULT vboxNetCfgWinNextAvailableDevName(bstr_t& bstrName)
    2973 {
    2974     SP_DEVINFO_DATA DeviceInfoData;
    2975     /* initialize the structure size */
    2976     DeviceInfoData.cbSize = sizeof (SP_DEVINFO_DATA);
    2977 
    2978     HDEVINFO DeviceInfoSet = SetupDiGetClassDevs(&GUID_DEVCLASS_NET, NULL, NULL, DIGCF_PRESENT);
    2979     if (DeviceInfoSet == INVALID_HANDLE_VALUE)
    2980         return GetLastError();
    2981 
    2982     DWORD i;
    2983     std::set<bstr_t> aExistingNames;
    2984     for (i = 0; SetupDiEnumDeviceInfo(DeviceInfoSet, i, &DeviceInfoData); ++i)
     2867static HRESULT vboxNetCfgWinNextAvailableDevName(com::Bstr *pbstrName)
     2868{
     2869    SP_DEVINFO_DATA DeviceInfoData = { sizeof(SP_DEVINFO_DATA) };
     2870    HDEVINFO hDeviceInfoSet = SetupDiGetClassDevsW(&GUID_DEVCLASS_NET, NULL, NULL, DIGCF_PRESENT);
     2871    if (hDeviceInfoSet == INVALID_HANDLE_VALUE)
     2872        return HRESULT_FROM_WIN32(GetLastError());
     2873
     2874    typedef struct VBOXDEVNAMEENTRY
     2875    {
     2876        RTLISTNODE  ListEntry;
     2877        WCHAR       wszDevName[64];
     2878        WCHAR       wcZeroParanoia;
     2879    } VBOXDEVNAMEENTRY;
     2880
     2881#if 0
     2882    /*
     2883     * Build a list of names starting with HOSTONLY_ADAPTER_NAME_WSZ belonging to our device.
     2884     */
     2885    RTLISTANCHOR Head; /* VBOXDEVNAMEENTRY */
     2886    RTListInit(&Head);
     2887    HRESULT      hrc = S_OK;
     2888#else
     2889    /*
     2890     * Build a bitmap of in-use index values of devices starting with HOSTONLY_ADAPTER_NAME_WSZ.
     2891     * Reserving 0 for one w/o a suffix, and marking 1 as unusable.
     2892     */
     2893    uint64_t bmIndexes[_32K / 64]; /* 4KB - 32767 device should be sufficient. */
     2894    RT_ZERO(bmIndexes);
     2895    ASMBitSet(&bmIndexes, 1);
     2896#endif
     2897    for (DWORD i = 0; SetupDiEnumDeviceInfo(hDeviceInfoSet, i, &DeviceInfoData); ++i)
    29852898    {
    29862899        /* Should be more than enough for both our device id and our device name, we do not care about the rest */
    2987         WCHAR wszDevName[64];
    2988         if (!SetupDiGetDeviceRegistryProperty(DeviceInfoSet, &DeviceInfoData, SPDRP_HARDWAREID,
    2989                                               NULL, (PBYTE)wszDevName, sizeof(wszDevName), NULL))
     2900        VBOXDEVNAMEENTRY Entry = { { 0, 0 }, L"", 0 }; /* (initialize it to avoid the wrath of asan) */
     2901        if (!SetupDiGetDeviceRegistryPropertyW(hDeviceInfoSet, &DeviceInfoData, SPDRP_HARDWAREID,
     2902                                               NULL, (PBYTE)Entry.wszDevName, sizeof(Entry.wszDevName), NULL))
    29902903            continue;
     2904
    29912905        /* Ignore everything except our host-only adapters */
    2992         if (_wcsicmp(wszDevName, DRIVERHWID))
    2993             continue;
    2994         if (   SetupDiGetDeviceRegistryProperty(DeviceInfoSet, &DeviceInfoData, SPDRP_FRIENDLYNAME,
    2995                                                 NULL, (PBYTE)wszDevName, sizeof(wszDevName), NULL)
    2996             || SetupDiGetDeviceRegistryProperty(DeviceInfoSet, &DeviceInfoData, SPDRP_DEVICEDESC,
    2997                                                 NULL, (PBYTE)wszDevName, sizeof(wszDevName), NULL))
    2998             aExistingNames.insert(bstr_t(wszDevName));
    2999     }
    3000     /* Try the name without index first */
    3001     bstrName = HOSTONLY_ADAPTER_NAME;
    3002     if (aExistingNames.find(bstrName) != aExistingNames.end())
    3003     {
    3004         WCHAR wszSuffix[16];
    3005         /* Try indexed names until we find unused one */
    3006         for (i = 2;; ++i)
    3007         {
    3008             wsprintf(wszSuffix, L" #%u", i);
    3009             if (aExistingNames.find(bstrName + wszSuffix) == aExistingNames.end())
    3010             {
    3011                 bstrName += wszSuffix;
     2906        if (RTUtf16ICmp(Entry.wszDevName, DRIVERHWID) == 0)
     2907        {
     2908            if (   SetupDiGetDeviceRegistryPropertyW(hDeviceInfoSet, &DeviceInfoData, SPDRP_FRIENDLYNAME,
     2909                                                     NULL, (PBYTE)Entry.wszDevName, sizeof(Entry.wszDevName), NULL)
     2910                || SetupDiGetDeviceRegistryPropertyW(hDeviceInfoSet, &DeviceInfoData, SPDRP_DEVICEDESC,
     2911                                                     NULL, (PBYTE)Entry.wszDevName, sizeof(Entry.wszDevName), NULL))
     2912            {
     2913                /* We can ignore any host-only adapter with a non-standard name. */
     2914                if (RTUtf16NICmp(Entry.wszDevName, HOSTONLY_ADAPTER_NAME_WSZ,
     2915                                 RT_ELEMENTS(HOSTONLY_ADAPTER_NAME_WSZ) - 1) == 0)
     2916                {
     2917#if 0
     2918                    VBOXDEVNAMEENTRY *pEntry = (VBOXDEVNAMEENTRY *)RTMemDup(&Entry, sizeof(Entry));
     2919                    if (pEntry)
     2920                        RTListAppend(&Head, &pEntry->ListEntry);
     2921                    else
     2922                    {
     2923                        hrc = E_OUTOFMEMORY;
     2924                        break;
     2925                    }
     2926#else
     2927                    WCHAR const *pwc = &Entry.wszDevName[RT_ELEMENTS(HOSTONLY_ADAPTER_NAME_WSZ) - 1];
     2928
     2929                    /* skip leading space */
     2930                    WCHAR wc = *pwc;
     2931                    while (wc == L' ' || wc == L'\t' || wc == L'\n' || wc == L'\r')
     2932                        wc = *++pwc;
     2933
     2934                    /* If end of string, use index 0. */
     2935                    if (wc == L'\0')
     2936                        ASMBitSet(bmIndexes, 0);
     2937
     2938                    /* Hash and digit? */
     2939                    else if (wc == L'#')
     2940                    {
     2941                        wc = *++pwc;
     2942                        while (wc == L' ' || wc == L'\t' || wc == L'\n' || wc == L'\r') /* just in case */
     2943                            wc = *++pwc;
     2944                        if (wc >= L'0' && wc <= L'9')
     2945                        {
     2946                            /* Convert what we can to a number and mark it as allocated in the bitmap. */
     2947                            uint64_t uIndex = wc - L'0';
     2948                            while ((wc = *++pwc) >= L'0' && wc <= L'9')
     2949                                uIndex = uIndex * 10 + wc - L'0';
     2950                            if (uIndex < sizeof(bmIndexes) * 8 && uIndex > 0)
     2951                                ASMBitSet(bmIndexes, (int32_t)uIndex);
     2952                        }
     2953                    }
     2954#endif
     2955                }
     2956            }
     2957        }
     2958    }
     2959#if 0
     2960    if (SUCCEEDED(hrc))
     2961    {
     2962        /*
     2963         * First try a name w/o an index, then try index #2 and up.
     2964         *
     2965         * Note! We have to use ASCII/UTF-8 strings here as Bstr will confuse WCHAR
     2966         *       with BSTR/OLECHAR strings and use SysAllocString to duplicate it .
     2967         */
     2968        char         szName[sizeof(HOSTONLY_ADAPTER_NAME_SZ " #4294967296") + 32] = HOSTONLY_ADAPTER_NAME_SZ;
     2969        size_t const cchBase = sizeof(HOSTONLY_ADAPTER_NAME_SZ) - 1;
     2970        for (DWORD idx = 2;; idx++)
     2971        {
     2972            bool              fFound = false;
     2973            VBOXDEVNAMEENTRY *pCur;
     2974            RTListForEach(&Head, pCur, VBOXDEVNAMEENTRY, ListEntry)
     2975            {
     2976                fFound = RTUtf16ICmpAscii(pCur->wszDevName, szName) == 0;
     2977                if (fFound)
     2978                {
     2979                    hrc = pbstrName->assignEx(szName);
     2980                    break;
     2981                }
     2982            }
     2983            if (fFound)
    30122984                break;
    3013             }
    3014         }
    3015     }
    3016 
    3017     if (DeviceInfoSet)
    3018         SetupDiDestroyDeviceInfoList(DeviceInfoSet);
    3019     return S_OK;
    3020 }
    3021 
    3022 static HRESULT vboxNetCfgWinCreateHostOnlyNetworkInterface(IN LPCWSTR pInfPath, IN bool bIsInfPathFile, IN BSTR bstrDesiredName,
    3023                                                            OUT GUID *pGuid, OUT BSTR *lppszName, OUT BSTR *pErrMsg)
    3024 {
    3025     HRESULT hrc = S_OK;
    3026 
    3027     HDEVINFO hDeviceInfo = INVALID_HANDLE_VALUE;
    3028     SP_DEVINFO_DATA DeviceInfoData;
    3029     PVOID pQueueCallbackContext = NULL;
    3030     DWORD ret = 0;
    3031     BOOL registered = FALSE;
    3032     BOOL destroyList = FALSE;
    3033     WCHAR pWCfgGuidString [50];
    3034     WCHAR DevName[256];
    3035     HKEY hkey = (HKEY)INVALID_HANDLE_VALUE;
    3036     bstr_t bstrError;
    3037     bstr_t bstrNewInterfaceName;
    3038 
    3039     if (SysStringLen(bstrDesiredName) != 0)
    3040         bstrNewInterfaceName = bstrDesiredName;
     2985            RTStrPrintf(&szName[cchBase], sizeof(szName) - cchBase, " #%u", idx);
     2986        }
     2987    }
     2988
     2989    VBOXDEVNAMEENTRY *pFirst;
     2990    while ((pFirst = RTListRemoveFirst(&Head, VBOXDEVNAMEENTRY, ListEntry)) != NULL)
     2991        RTMemFree(pFirst);
     2992
     2993#else
     2994    /*
     2995     * Find an unused index value and format the corresponding name.
     2996     */
     2997    HRESULT hrc;
     2998    int32_t iBit = ASMBitFirstClear(bmIndexes, sizeof(bmIndexes) * 8);
     2999    if (iBit >= 0)
     3000    {
     3001        if (iBit == 0)
     3002            hrc = pbstrName->assignEx(HOSTONLY_ADAPTER_NAME_SZ); /* Not _WSZ! */
     3003        else
     3004            hrc = pbstrName->printfNoThrow(HOSTONLY_ADAPTER_NAME_SZ " #%u", iBit);
     3005    }
    30413006    else
    30423007    {
    3043         hrc = vboxNetCfgWinNextAvailableDevName(bstrNewInterfaceName);
     3008        NonStandardLogFlow(("vboxNetCfgWinNextAvailableDevName: no unused index in the first 32K!\n"));
     3009        hrc = E_FAIL;
     3010    }
     3011#endif
     3012
     3013    if (hDeviceInfoSet)
     3014        SetupDiDestroyDeviceInfoList(hDeviceInfoSet);
     3015    return hrc;
     3016}
     3017
     3018static HRESULT vboxNetCfgWinCreateHostOnlyNetworkInterface(IN LPCWSTR pwszInfPath, IN bool fIsInfPathFile,
     3019                                                           IN BSTR pBstrDesiredName,
     3020                                                           OUT GUID *pGuid, OUT BSTR *pBstrName, OUT BSTR *pBstrErrMsg)
     3021{
     3022    com::Bstr bstrError;
     3023
     3024    /* Determine the interface name. We make a copy of the input here for
     3025       renaming reasons, see futher down. */
     3026    com::Bstr bstrNewInterfaceName;
     3027    HRESULT   hrc;
     3028    if (SysStringLen(pBstrDesiredName) != 0)
     3029        hrc = bstrNewInterfaceName.assignEx(pBstrDesiredName);
     3030    else
     3031    {
     3032        hrc = vboxNetCfgWinNextAvailableDevName(&bstrNewInterfaceName);
    30443033        if (FAILED(hrc))
    30453034            NonStandardLogFlow(("vboxNetCfgWinNextAvailableDevName failed with 0x%x\n", hrc));
    30463035    }
    3047 
    3048     do
    3049     {
    3050         BOOL found = FALSE;
     3036    if (FAILED(hrc))
     3037        return hrc;
     3038
     3039    WCHAR           wszCfgGuidString[50]  = {0};
     3040    WCHAR           wszDevName[256 + 1]   = {0};
     3041    SP_DEVINFO_DATA DeviceInfoData        = { sizeof(DeviceInfoData) };
     3042    HDEVINFO        hDeviceInfo           = INVALID_HANDLE_VALUE;
     3043    PVOID           pQueueCallbackContext = NULL;
     3044    BOOL            fRegistered           = FALSE;
     3045    BOOL            destroyList           = FALSE;
     3046    HKEY            hkey                  = (HKEY)INVALID_HANDLE_VALUE;
     3047    LSTATUS         lrcRet                = ERROR_SUCCESS; /* the */
     3048
     3049    do /* non-loop, for breaking. */
     3050    {
     3051        /* copy the net class GUID */
    30513052        GUID netGuid;
    3052         SP_DRVINFO_DATA DriverInfoData;
    3053         SP_DEVINSTALL_PARAMS DeviceInstallParams;
    3054         TCHAR className [MAX_PATH];
    3055         DWORD index = 0;
    3056         PSP_DRVINFO_DETAIL_DATA pDriverInfoDetail;
    3057         /* for our purposes, 2k buffer is more
    3058          * than enough to obtain the hardware ID
    3059          * of the VBoxNetAdp driver. */
    3060         DWORD detailBuf [2048];
    3061 
    3062         DWORD cbSize;
    3063         DWORD dwValueType;
    3064 
    3065         /* initialize the structure size */
    3066         DeviceInfoData.cbSize = sizeof (SP_DEVINFO_DATA);
    3067         DriverInfoData.cbSize = sizeof (SP_DRVINFO_DATA);
    3068 
    3069         /* copy the net class GUID */
    30703053        memcpy(&netGuid, &GUID_DEVCLASS_NET, sizeof(GUID_DEVCLASS_NET));
    30713054
    3072         /* create an empty device info set associated with the net class GUID */
     3055        /* Create an empty device info set associated with the net class GUID: */
    30733056        hDeviceInfo = SetupDiCreateDeviceInfoList(&netGuid, NULL);
    30743057        if (hDeviceInfo == INVALID_HANDLE_VALUE)
    3075             SetErrBreak (("SetupDiCreateDeviceInfoList failed (0x%08X)",
    3076                           GetLastError()));
    3077 
    3078         /* get the class name from GUID */
    3079         BOOL fResult = SetupDiClassNameFromGuid (&netGuid, className, MAX_PATH, NULL);
    3080         if (!fResult)
    3081             SetErrBreak (("SetupDiClassNameFromGuid failed (0x%08X)",
    3082                           GetLastError()));
    3083 
    3084         /* create a device info element and add the new device instance
    3085          * key to registry */
    3086         fResult = SetupDiCreateDeviceInfo (hDeviceInfo, className, &netGuid, NULL, NULL,
    3087                                      DICD_GENERATE_ID, &DeviceInfoData);
    3088         if (!fResult)
    3089             SetErrBreak (("SetupDiCreateDeviceInfo failed (0x%08X)",
    3090                           GetLastError()));
    3091 
    3092         /* select the newly created device info to be the currently
    3093            selected member */
    3094         fResult = SetupDiSetSelectedDevice (hDeviceInfo, &DeviceInfoData);
    3095         if (!fResult)
    3096             SetErrBreak (("SetupDiSetSelectedDevice failed (0x%08X)",
    3097                           GetLastError()));
    3098 
    3099         if (pInfPath)
     3058            SetErrBreak(("SetupDiCreateDeviceInfoList failed (%Rwc)", GetLastError()));
     3059
     3060        /* Translate the GUID to a class name: */
     3061        WCHAR wszClassName[MAX_PATH];
     3062        if (!SetupDiClassNameFromGuid(&netGuid, wszClassName, MAX_PATH, NULL))
     3063            SetErrBreak(("SetupDiClassNameFromGuid failed (%Rwc)", GetLastError()));
     3064
     3065        /* Create a device info element and add the new device instance key to registry: */
     3066        if (!SetupDiCreateDeviceInfo(hDeviceInfo, wszClassName, &netGuid, NULL, NULL, DICD_GENERATE_ID, &DeviceInfoData))
     3067            SetErrBreak(("SetupDiCreateDeviceInfo failed (%Rwc)", GetLastError()));
     3068
     3069        /* Select the newly created device info to be the currently selected member: */
     3070        if (!SetupDiSetSelectedDevice(hDeviceInfo, &DeviceInfoData))
     3071            SetErrBreak(("SetupDiSetSelectedDevice failed (%Rwc)", GetLastError()));
     3072
     3073        SP_DEVINSTALL_PARAMS DeviceInstallParams;
     3074        if (pwszInfPath)
    31003075        {
    31013076            /* get the device install parameters and disable filecopy */
    31023077            DeviceInstallParams.cbSize = sizeof(SP_DEVINSTALL_PARAMS);
    3103             fResult = SetupDiGetDeviceInstallParams (hDeviceInfo, &DeviceInfoData,
    3104                                                 &DeviceInstallParams);
    3105             if (fResult)
     3078            if (SetupDiGetDeviceInstallParams(hDeviceInfo, &DeviceInfoData, &DeviceInstallParams))
    31063079            {
    31073080                memset(DeviceInstallParams.DriverPath, 0, sizeof(DeviceInstallParams.DriverPath));
    3108                 size_t pathLenght = wcslen(pInfPath) + 1/* null terminator */;
     3081                size_t pathLenght = wcslen(pwszInfPath) + 1/* null terminator */;
    31093082                if (pathLenght < sizeof(DeviceInstallParams.DriverPath)/sizeof(DeviceInstallParams.DriverPath[0]))
    31103083                {
    3111                     memcpy(DeviceInstallParams.DriverPath, pInfPath, pathLenght*sizeof(DeviceInstallParams.DriverPath[0]));
    3112 
    3113                     if (bIsInfPathFile)
     3084                    memcpy(DeviceInstallParams.DriverPath, pwszInfPath, pathLenght*sizeof(DeviceInstallParams.DriverPath[0]));
     3085
     3086                    if (fIsInfPathFile)
     3087                        DeviceInstallParams.Flags |= DI_ENUMSINGLEINF;
     3088
     3089                    if (!SetupDiSetDeviceInstallParams(hDeviceInfo, &DeviceInfoData, &DeviceInstallParams))
    31143090                    {
    3115                         DeviceInstallParams.Flags |= DI_ENUMSINGLEINF;
    3116                     }
    3117 
    3118                     fResult = SetupDiSetDeviceInstallParams(hDeviceInfo, &DeviceInfoData,
    3119                                                        &DeviceInstallParams);
    3120                     if (!fResult)
    3121                     {
    3122                         DWORD winEr = GetLastError();
    3123                         NonStandardLogFlow(("SetupDiSetDeviceInstallParams failed, winEr (%d)\n", winEr));
     3091                        NonStandardLogFlow(("SetupDiSetDeviceInstallParams failed (%Rwc)\n", GetLastError()));
    31243092                        break;
    31253093                    }
     
    31323100            }
    31333101            else
    3134             {
    3135                 DWORD winEr = GetLastError();
    3136                 NonStandardLogFlow(("SetupDiGetDeviceInstallParams failed, winEr (%d)\n", winEr));
    3137             }
     3102                NonStandardLogFlow(("SetupDiGetDeviceInstallParams failed (%Rwc)\n", GetLastError()));
    31383103        }
    31393104
    31403105        /* build a list of class drivers */
    3141         fResult = SetupDiBuildDriverInfoList (hDeviceInfo, &DeviceInfoData,
    3142                                               SPDIT_CLASSDRIVER);
    3143         if (!fResult)
    3144             SetErrBreak (("SetupDiBuildDriverInfoList failed (0x%08X)",
    3145                           GetLastError()));
     3106        if (!SetupDiBuildDriverInfoList(hDeviceInfo, &DeviceInfoData, SPDIT_CLASSDRIVER))
     3107            SetErrBreak(("SetupDiBuildDriverInfoList failed (%Rwc)", GetLastError()));
    31463108
    31473109        destroyList = TRUE;
    31483110
    3149         /* enumerate the driver info list */
    3150         while (TRUE)
    3151         {
    3152             BOOL fRet = SetupDiEnumDriverInfo(hDeviceInfo, &DeviceInfoData, SPDIT_CLASSDRIVER, index, &DriverInfoData);
    3153 
    3154             /* if the function failed and GetLastError() returns
    3155              * ERROR_NO_MORE_ITEMS, then we have reached the end of the
    3156              * list.  Otherwise there was something wrong with this
    3157              * particular driver. */
    3158             if (!fRet)
     3111        /*
     3112         * Enumerate the driver info list.
     3113         */
     3114        /* For our purposes, 2k buffer is more than enough to obtain the
     3115           hardware ID of the VBoxNetAdp driver. */ /** @todo r=bird: The buffer isn't 2KB, it's 8KB, but whatever. */
     3116        DWORD           detailBuf[2048];
     3117        SP_DRVINFO_DATA DriverInfoData = { sizeof(DriverInfoData) };
     3118        bool            fFound         = false;
     3119        for (DWORD index = 0; !fFound; index++)
     3120        {
     3121            /* If the function fails with last error set to ERROR_NO_MORE_ITEMS,
     3122               then we have reached the end of the list.  Otherwise there was
     3123               something wrong with this particular driver. */
     3124            if (!SetupDiEnumDriverInfo(hDeviceInfo, &DeviceInfoData, SPDIT_CLASSDRIVER, index, &DriverInfoData))
    31593125            {
    31603126                if (GetLastError() == ERROR_NO_MORE_ITEMS)
    31613127                    break;
    3162                 index++;
    31633128                continue;
    31643129            }
    3165 
    3166             pDriverInfoDetail = (PSP_DRVINFO_DETAIL_DATA) detailBuf;
    3167             pDriverInfoDetail->cbSize = sizeof(SP_DRVINFO_DETAIL_DATA);
    31683130
    31693131            /* if we successfully find the hardware ID and it turns out to
    31703132             * be the one for the loopback driver, then we are done. */
    3171             if (SetupDiGetDriverInfoDetail (hDeviceInfo,
     3133            PSP_DRVINFO_DETAIL_DATA_W pDriverInfoDetail = (PSP_DRVINFO_DETAIL_DATA_W)detailBuf;
     3134            pDriverInfoDetail->cbSize = sizeof(SP_DRVINFO_DETAIL_DATA);
     3135            DWORD cbValue = 0;
     3136            if (SetupDiGetDriverInfoDetailW(hDeviceInfo,
    31723137                                            &DeviceInfoData,
    31733138                                            &DriverInfoData,
    31743139                                            pDriverInfoDetail,
    3175                                             sizeof (detailBuf),
    3176                                             NULL))
    3177             {
    3178                 TCHAR * t;
    3179 
    3180                 /* pDriverInfoDetail->HardwareID is a MULTISZ string.  Go through the
    3181                  * whole list and see if there is a match somewhere. */
    3182                 t = pDriverInfoDetail->HardwareID;
    3183                 while (t && *t && t < (TCHAR *) &detailBuf [RT_ELEMENTS(detailBuf)])
    3184                 {
    3185                     if (!_tcsicmp(t, DRIVERHWID))
     3140                                            sizeof(detailBuf) - sizeof(detailBuf[0]),
     3141                                            &cbValue))
     3142            {
     3143                /* Sure that the HardwareID string list is properly zero terminated (paranoia). */
     3144                detailBuf[RT_ELEMENTS(detailBuf) - 1] = 0; AssertCompile(sizeof(detailBuf[0]) == sizeof(WCHAR) * 2);
     3145
     3146                /* pDriverInfoDetail->HardwareID is a MULTISZ string.  Go through the whole
     3147                   list and see if there is a match somewhere: */
     3148                for (WCHAR *pwszCurHwId = pDriverInfoDetail->HardwareID;
     3149                     (uintptr_t)pwszCurHwId - (uintptr_t)pDriverInfoDetail < cbValue && *pwszCurHwId != L'\0';
     3150                     pwszCurHwId += RTUtf16Len(pwszCurHwId) + 1)
     3151                    if (RTUtf16ICmp(DRIVERHWID, pwszCurHwId) == 0)
     3152                    {
     3153                        fFound = true;
    31863154                        break;
    3187 
    3188                     t += _tcslen(t) + 1;
    3189                 }
    3190 
    3191                 if (t && *t && t < (TCHAR *) &detailBuf [RT_ELEMENTS(detailBuf)])
    3192                 {
    3193                     found = TRUE;
    3194                     break;
    3195                 }
    3196             }
    3197 
    3198             index ++;
    3199         }
    3200 
    3201         if (!found)
     3155                    }
     3156            }
     3157        }
     3158
     3159        if (!fFound)
    32023160            SetErrBreak(("Could not find Host Interface Networking driver! Please reinstall"));
    32033161
    32043162        /* set the loopback driver to be the currently selected */
    3205         fResult = SetupDiSetSelectedDriver (hDeviceInfo, &DeviceInfoData,
    3206                                        &DriverInfoData);
    3207         if (!fResult)
    3208             SetErrBreak(("SetupDiSetSelectedDriver failed (0x%08X)",
    3209                          GetLastError()));
     3163        if (!SetupDiSetSelectedDriver(hDeviceInfo, &DeviceInfoData, &DriverInfoData))
     3164            SetErrBreak(("SetupDiSetSelectedDriver failed (%u)", GetLastError()));
    32103165
    32113166        /* register the phantom device to prepare for install */
    3212         fResult = SetupDiCallClassInstaller (DIF_REGISTERDEVICE, hDeviceInfo,
    3213                                              &DeviceInfoData);
    3214         if (!fResult)
    3215         {
    3216             DWORD err = GetLastError();
    3217             SetErrBreak (("SetupDiCallClassInstaller failed (0x%08X)",
    3218                           err));
    3219         }
     3167        if (!SetupDiCallClassInstaller(DIF_REGISTERDEVICE, hDeviceInfo, &DeviceInfoData))
     3168            SetErrBreak(("SetupDiCallClassInstaller failed (%u)", GetLastError()));
    32203169
    32213170        /* registered, but remove if errors occur in the following code */
    3222         registered = TRUE;
     3171        fRegistered = TRUE;
    32233172
    32243173        /* ask the installer if we can install the device */
    3225         fResult = SetupDiCallClassInstaller (DIF_ALLOW_INSTALL, hDeviceInfo,
    3226                                              &DeviceInfoData);
    3227         if (!fResult)
     3174        if (!SetupDiCallClassInstaller(DIF_ALLOW_INSTALL, hDeviceInfo, &DeviceInfoData))
    32283175        {
    32293176            if (GetLastError() != ERROR_DI_DO_DEFAULT)
    3230                 SetErrBreak (("SetupDiCallClassInstaller (DIF_ALLOW_INSTALL) failed (0x%08X)",
    3231                               GetLastError()));
     3177                SetErrBreak(("SetupDiCallClassInstaller (DIF_ALLOW_INSTALL) failed (%u)", GetLastError()));
    32323178            /* that's fine */
    32333179        }
     
    32353181        /* get the device install parameters and disable filecopy */
    32363182        DeviceInstallParams.cbSize = sizeof(SP_DEVINSTALL_PARAMS);
    3237         fResult = SetupDiGetDeviceInstallParams (hDeviceInfo, &DeviceInfoData,
    3238                                                  &DeviceInstallParams);
    3239         if (fResult)
     3183        if (SetupDiGetDeviceInstallParams(hDeviceInfo, &DeviceInfoData, &DeviceInstallParams))
    32403184        {
    32413185            pQueueCallbackContext = SetupInitDefaultQueueCallback(NULL);
     
    32443188                DeviceInstallParams.InstallMsgHandlerContext = pQueueCallbackContext;
    32453189                DeviceInstallParams.InstallMsgHandler = (PSP_FILE_CALLBACK)vboxNetCfgWinPspFileCallback;
    3246                 fResult = SetupDiSetDeviceInstallParams (hDeviceInfo, &DeviceInfoData,
    3247                                                     &DeviceInstallParams);
    3248                 if (!fResult)
     3190                if (!SetupDiSetDeviceInstallParamsW(hDeviceInfo, &DeviceInfoData, &DeviceInstallParams))
    32493191                {
    32503192                    DWORD winEr = GetLastError();
    3251                     NonStandardLogFlow(("SetupDiSetDeviceInstallParams failed, winEr (%d)\n", winEr));
    3252                 }
    3253                 Assert(fResult);
     3193                    NonStandardLogFlow(("SetupDiSetDeviceInstallParamsW failed, winEr (%d)\n", winEr));
     3194                    Assert(0);
     3195                }
    32543196            }
    32553197            else
     
    32663208
    32673209        /* install the files first */
    3268         fResult = SetupDiCallClassInstaller (DIF_INSTALLDEVICEFILES, hDeviceInfo,
    3269                                         &DeviceInfoData);
    3270         if (!fResult)
    3271             SetErrBreak (("SetupDiCallClassInstaller (DIF_INSTALLDEVICEFILES) failed (0x%08X)",
    3272                           GetLastError()));
     3210        if (!SetupDiCallClassInstaller(DIF_INSTALLDEVICEFILES, hDeviceInfo, &DeviceInfoData))
     3211            SetErrBreak(("SetupDiCallClassInstaller (DIF_INSTALLDEVICEFILES) failed (%Rwc)", GetLastError()));
     3212
    32733213        /* get the device install parameters and disable filecopy */
    32743214        DeviceInstallParams.cbSize = sizeof(SP_DEVINSTALL_PARAMS);
    3275         fResult = SetupDiGetDeviceInstallParams (hDeviceInfo, &DeviceInfoData,
    3276                                             &DeviceInstallParams);
    3277         if (fResult)
     3215        if (SetupDiGetDeviceInstallParams(hDeviceInfo, &DeviceInfoData, &DeviceInstallParams))
    32783216        {
    32793217            DeviceInstallParams.Flags |= DI_NOFILECOPY;
    3280             fResult = SetupDiSetDeviceInstallParams(hDeviceInfo, &DeviceInfoData,
    3281                                                     &DeviceInstallParams);
    3282             if (!fResult)
    3283                 SetErrBreak (("SetupDiSetDeviceInstallParams failed (0x%08X)",
    3284                               GetLastError()));
    3285         }
     3218            if (!SetupDiSetDeviceInstallParamsW(hDeviceInfo, &DeviceInfoData, &DeviceInstallParams))
     3219                SetErrBreak(("SetupDiSetDeviceInstallParamsW failed (%Rwc)", GetLastError()));
     3220        }
     3221        /** @todo r=bird: Why isn't SetupDiGetDeviceInstallParams failure fatal here? */
    32863222
    32873223        /*
    32883224         * Register any device-specific co-installers for this device,
    32893225         */
    3290         fResult = SetupDiCallClassInstaller(DIF_REGISTER_COINSTALLERS,
    3291                                             hDeviceInfo,
    3292                                             &DeviceInfoData);
    3293         if (!fResult)
    3294             SetErrBreak (("SetupDiCallClassInstaller (DIF_REGISTER_COINSTALLERS) failed (0x%08X)",
    3295                           GetLastError()));
     3226        if (!SetupDiCallClassInstaller(DIF_REGISTER_COINSTALLERS, hDeviceInfo, &DeviceInfoData))
     3227            SetErrBreak(("SetupDiCallClassInstaller (DIF_REGISTER_COINSTALLERS) failed (%Rwc)", GetLastError()));
    32963228
    32973229        /*
     
    32993231         * and then do the real install
    33003232         */
    3301         fResult = SetupDiCallClassInstaller(DIF_INSTALLINTERFACES,
    3302                                             hDeviceInfo,
    3303                                             &DeviceInfoData);
    3304         if (!fResult)
    3305             SetErrBreak (("SetupDiCallClassInstaller (DIF_INSTALLINTERFACES) failed (0x%08X)",
    3306                           GetLastError()));
    3307 
    3308         fResult = SetupDiCallClassInstaller(DIF_INSTALLDEVICE,
    3309                                             hDeviceInfo,
    3310                                             &DeviceInfoData);
    3311         if (!fResult)
    3312             SetErrBreak (("SetupDiCallClassInstaller (DIF_INSTALLDEVICE) failed (0x%08X)",
    3313                           GetLastError()));
    3314 
    3315         /* Query the instance ID; on Windows 10, the registry key may take a short
     3233        if (!SetupDiCallClassInstaller(DIF_INSTALLINTERFACES, hDeviceInfo, &DeviceInfoData))
     3234            SetErrBreak(("SetupDiCallClassInstaller (DIF_INSTALLINTERFACES) failed (%Rwc)", GetLastError()));
     3235
     3236        if (!SetupDiCallClassInstaller(DIF_INSTALLDEVICE, hDeviceInfo, &DeviceInfoData))
     3237            SetErrBreak(("SetupDiCallClassInstaller (DIF_INSTALLDEVICE) failed (%Rwc)", GetLastError()));
     3238
     3239        /*
     3240         * Query the instance ID; on Windows 10, the registry key may take a short
    33163241         * while to appear. Microsoft recommends waiting for up to 5 seconds, but
    33173242         * we want to be on the safe side, so let's wait for 20 seconds. Waiting
     
    33243249
    33253250            /* Figure out NetCfgInstanceId */
    3326             hkey = SetupDiOpenDevRegKey(hDeviceInfo,
    3327                                         &DeviceInfoData,
    3328                                         DICS_FLAG_GLOBAL,
    3329                                         0,
    3330                                         DIREG_DRV,
    3331                                         KEY_READ);
     3251            hkey = SetupDiOpenDevRegKey(hDeviceInfo, &DeviceInfoData, DICS_FLAG_GLOBAL, 0, DIREG_DRV, KEY_READ);
    33323252            if (hkey == INVALID_HANDLE_VALUE)
    33333253                break;
    33343254
    3335             cbSize = sizeof(pWCfgGuidString);
    3336             ret = RegQueryValueExW (hkey, L"NetCfgInstanceId", NULL,
    3337                                    &dwValueType, (LPBYTE) pWCfgGuidString, &cbSize);
     3255            DWORD cbSize       = sizeof(wszCfgGuidString);
     3256            DWORD dwValueType = 0;
     3257            lrcRet = RegQueryValueExW(hkey, L"NetCfgInstanceId", NULL, &dwValueType, (LPBYTE)wszCfgGuidString, &cbSize);
    33383258            /* As long as the return code is FILE_NOT_FOUND, sleep and retry. */
    3339             if (ret != ERROR_FILE_NOT_FOUND)
     3259            if (lrcRet != ERROR_FILE_NOT_FOUND)
    33403260                break;
    33413261
    3342             RegCloseKey (hkey);
     3262            RegCloseKey(hkey);
    33433263            hkey = (HKEY)INVALID_HANDLE_VALUE;
    33443264        }
    33453265
    3346         if (ret == ERROR_FILE_NOT_FOUND)
     3266        if (lrcRet == ERROR_FILE_NOT_FOUND)
    33473267        {
    33483268            hrc = E_ABORT;
     
    33513271
    33523272        /*
    3353          * We need to check 'hkey' after we check 'ret' to distinguish the case
     3273         * We need to check 'hkey' after we check 'lrcRet' to distinguish the case
    33543274         * of failed SetupDiOpenDevRegKey from the case when we timed out.
    33553275         */
    33563276        if (hkey == INVALID_HANDLE_VALUE)
    3357             SetErrBreak(("SetupDiOpenDevRegKey failed (0x%08X)", GetLastError()));
    3358 
    3359         if (ret != ERROR_SUCCESS)
    3360             SetErrBreak(("Querying NetCfgInstanceId failed (0x%08X)", ret));
     3277            SetErrBreak(("SetupDiOpenDevRegKey failed (%Rwc)", GetLastError()));
     3278
     3279        if (lrcRet != ERROR_SUCCESS)
     3280            SetErrBreak(("Querying NetCfgInstanceId failed (%Rwc)", lrcRet));
    33613281
    33623282        NET_LUID luid;
    3363         HRESULT hSMRes = vboxNetCfgWinGetInterfaceLUID(hkey, &luid);
     3283        HRESULT hrcSMRes = vboxNetCfgWinGetInterfaceLUID(hkey, &luid);
    33643284
    33653285        /* Close the key as soon as possible. See @bugref{7973}. */
    3366         RegCloseKey (hkey);
     3286        RegCloseKey(hkey);
    33673287        hkey = (HKEY)INVALID_HANDLE_VALUE;
    33683288
    3369         if (FAILED(hSMRes))
     3289        if (FAILED(hrcSMRes))
    33703290        {
    33713291            /*
    3372             The setting of Metric is not very important functionality,
    3373             So we will not break installation process due to this error.
    3374             */
    3375             NonStandardLogFlow(("vboxNetCfgWinCreateHostOnlyNetworkInterface Warning! "
    3376                                 "vboxNetCfgWinGetInterfaceLUID failed, default metric "
    3377                                 "for new interface will not be set, hr (0x%x)\n", hSMRes));
     3292             * The setting of Metric is not very important functionality,
     3293             * So we will not break installation process due to this error.
     3294             */
     3295            NonStandardLogFlow(("vboxNetCfgWinCreateHostOnlyNetworkInterface: Warning! "
     3296                                "vboxNetCfgWinGetInterfaceLUID failed, default metric for new interface will not be set: %Rhrc\n",
     3297                                hrcSMRes));
    33783298        }
    33793299        else
    33803300        {
    33813301            /*
    3382              *   Set default metric value of interface to fix multicast issue
    3383              *   See @bugref{6379} for details.
     3302             * Set default metric value of interface to fix multicast issue
     3303             * See @bugref{6379} for details.
    33843304             */
    3385             hSMRes = vboxNetCfgWinSetupMetric(&luid);
    3386             if (FAILED(hSMRes))
     3305            hrcSMRes = vboxNetCfgWinSetupMetric(&luid);
     3306            if (FAILED(hrcSMRes))
    33873307            {
    33883308                /*
    3389                  *   The setting of Metric is not very important functionality,
    3390                  *   So we will not break installation process due to this error.
     3309                 * The setting of Metric is not very important functionality,
     3310                 * So we will not break installation process due to this error.
    33913311                 */
    3392                 NonStandardLogFlow(("vboxNetCfgWinCreateHostOnlyNetworkInterface Warning! "
    3393                                     "vboxNetCfgWinSetupMetric failed, default metric "
    3394                                     "for new interface will not be set, hr (0x%x)\n", hSMRes));
    3395             }
    3396         }
    3397 
     3312                NonStandardLogFlow(("vboxNetCfgWinCreateHostOnlyNetworkInterface: Warning! "
     3313                                    "vboxNetCfgWinSetupMetric failed, default metric for new interface will not be set: %Rhrc\n",
     3314                                    hrcSMRes));
     3315            }
     3316        }
    33983317
    33993318        /*
     
    34043323                                               SPDRP_FRIENDLYNAME , /* IN DWORD Property,*/
    34053324                                               NULL, /*OUT PDWORD PropertyRegDataType, OPTIONAL*/
    3406                                                (PBYTE)DevName, /*OUT PBYTE PropertyBuffer,*/
    3407                                                sizeof(DevName), /* IN DWORD PropertyBufferSize,*/
    3408                                                NULL /*OUT PDWORD RequiredSize OPTIONAL*/))
    3409         {
    3410             int err = GetLastError();
    3411             if (err != ERROR_INVALID_DATA)
    3412             {
    3413                 SetErrBreak (("SetupDiGetDeviceRegistryProperty failed (0x%08X)",
    3414                               err));
    3415             }
    3416 
     3325                                               (PBYTE)wszDevName, /*OUT PBYTE PropertyBuffer,*/
     3326                                               sizeof(wszDevName) - sizeof(WCHAR), /* IN DWORD PropertyBufferSize,*/
     3327                                               NULL /*OUT PDWORD RequiredSize OPTIONAL*/ ))
     3328        {
     3329            DWORD dwErr = GetLastError();
     3330            if (dwErr != ERROR_INVALID_DATA)
     3331                SetErrBreak(("SetupDiGetDeviceRegistryProperty failed (%Rwc)", dwErr));
     3332
     3333            RT_ZERO(wszDevName);
    34173334            if (!SetupDiGetDeviceRegistryPropertyW(hDeviceInfo, &DeviceInfoData,
    3418                               SPDRP_DEVICEDESC, /* IN DWORD Property,*/
    3419                               NULL, /*OUT PDWORD PropertyRegDataType, OPTIONAL*/
    3420                               (PBYTE)DevName, /*OUT PBYTE PropertyBuffer,*/
    3421                               sizeof(DevName), /* IN DWORD PropertyBufferSize,*/
    3422                               NULL /*OUT PDWORD RequiredSize OPTIONAL*/
    3423                             ))
    3424             {
    3425                 err = GetLastError();
    3426                 SetErrBreak (("SetupDiGetDeviceRegistryProperty failed (0x%08X)",
    3427                                               err));
    3428             }
    3429         }
     3335                                                   SPDRP_DEVICEDESC, /* IN DWORD Property,*/
     3336                                                   NULL, /*OUT PDWORD PropertyRegDataType, OPTIONAL*/
     3337                                                   (PBYTE)wszDevName, /*OUT PBYTE PropertyBuffer,*/
     3338                                                   sizeof(wszDevName) - sizeof(WCHAR), /* IN DWORD PropertyBufferSize,*/
     3339                                                   NULL /*OUT PDWORD RequiredSize OPTIONAL*/ ))
     3340                SetErrBreak(("SetupDiGetDeviceRegistryProperty failed (%Rwc)", GetLastError()));
     3341        }
     3342
    34303343        /* No need to rename the device if the names match. */
    3431         if (!wcscmp(bstrNewInterfaceName.GetBSTR(), DevName))
    3432             bstrNewInterfaceName.Assign(NULL);
     3344        if (RTUtf16Cmp(bstrNewInterfaceName.raw(), wszDevName) == 0)
     3345            bstrNewInterfaceName.setNull();
     3346
    34333347#ifdef VBOXNETCFG_DELAYEDRENAME
    3434         /* Re-use DevName for device instance id retrieval. */
    3435         if (!SetupDiGetDeviceInstanceId(hDeviceInfo, &DeviceInfoData, DevName, RT_ELEMENTS(DevName), &cbSize))
    3436             SetErrBreak (("SetupDiGetDeviceInstanceId failed (0x%08X)",
    3437                           GetLastError()));
     3348        /* Re-use wszDevName for device instance id retrieval. */
     3349        DWORD cwcReturned = 0;
     3350        RT_ZERO(wszDevName);
     3351        if (!SetupDiGetDeviceInstanceIdW(hDeviceInfo, &DeviceInfoData, wszDevName, RT_ELEMENTS(wszDevName) - 1, &cwcReturned))
     3352            SetErrBreak(("SetupDiGetDeviceInstanceId failed (%Rwc)", GetLastError()));
    34383353#endif /* VBOXNETCFG_DELAYEDRENAME */
    3439     }
    3440     while (0);
     3354    } while (0);
    34413355
    34423356    /*
    3443      * cleanup
     3357     * Cleanup.
    34443358     */
    34453359    if (hkey != INVALID_HANDLE_VALUE)
    3446         RegCloseKey (hkey);
     3360        RegCloseKey(hkey);
    34473361
    34483362    if (pQueueCallbackContext)
     
    34523366    {
    34533367        /* an error has occurred, but the device is registered, we must remove it */
    3454         if (ret != 0 && registered)
     3368        if (lrcRet != ERROR_SUCCESS && fRegistered)
    34553369            SetupDiCallClassInstaller(DIF_REMOVE, hDeviceInfo, &DeviceInfoData);
    34563370
     
    34583372
    34593373        /* destroy the driver info list */
     3374#if 0
     3375        /* I've remove this, as I was consistently getting crashes in
     3376         * SetupDiDestroyDeviceInfoList otherwise during MSI installation
     3377         * (W10 build 19044, VBox r153431 + nocrt changes).
     3378         *
     3379         * Some details from windbg:
     3380         *
     3381         * (175e8.1596c): Access violation - code c0000005 (first chance)
     3382         * First chance exceptions are reported before any exception handling.
     3383         * This exception may be expected and handled.
     3384         * SETUPAPI!DereferenceClassDriverList+0x4e:
     3385         * 00007ffa`83e2a42a 834008ff        add     dword ptr [rax+8],0FFFFFFFFh ds:00000000`00000008=????????
     3386         * 0:006> k
     3387         *  # Child-SP          RetAddr           Call Site
     3388         * 00 0000007e`ccd7c070 00007ffa`83e2a287 SETUPAPI!DereferenceClassDriverList+0x4e
     3389         * 01 0000007e`ccd7c0a0 00007ffa`56b96bd3 SETUPAPI!SetupDiDestroyDriverInfoList+0x117
     3390         * 02 0000007e`ccd7c0f0 00007ffa`56b982a3 MSIF170!vboxNetCfgWinCreateHostOnlyNetworkInterface+0xb23 [E:\vbox\svn\trunk\src\VBox\HostDrivers\VBoxNetFlt\win\cfg\VBoxNetCfg.cpp @ 3378]
     3391         * 03 0000007e`ccd7ef10 00007ffa`56b92cb8 MSIF170!VBoxNetCfgWinCreateHostOnlyNetworkInterface+0x53 [E:\vbox\svn\trunk\src\VBox\HostDrivers\VBoxNetFlt\win\cfg\VBoxNetCfg.cpp @ 3479]
     3392         * 04 0000007e`ccd7efc0 00007ffa`610f59d3 MSIF170!_createHostOnlyInterface+0x218 [E:\vbox\svn\trunk\src\VBox\Installer\win\InstallHelper\VBoxInstallHelper.cpp @ 1453]
     3393         * 05 0000007e`ccd7f260 00007ffa`610d80ac msi!CallCustomDllEntrypoint+0x2b
     3394         * 06 0000007e`ccd7f2d0 00007ffa`84567034 msi!CMsiCustomAction::CustomActionThread+0x34c
     3395         * 07 0000007e`ccd7f8c0 00007ffa`849a2651 KERNEL32!BaseThreadInitThunk+0x14
     3396         * 08 0000007e`ccd7f8f0 00000000`00000000 ntdll!RtlUserThreadStart+0x21
     3397         * 0:006> r
     3398         * rax=0000000000000000 rbx=0000025f4f03af90 rcx=00007ffa83f23b40
     3399         * rdx=0000025f4f03af90 rsi=0000025f5108be50 rdi=0000025f4f066f10
     3400         * rip=00007ffa83e2a42a rsp=0000007eccd7c070 rbp=00007ffa83f23000
     3401         *  r8=0000007eccd7c0a8  r9=0000007eccd7c1f0 r10=0000000000000000
     3402         * r11=0000007eccd7c020 r12=0000007eccd7c3d0 r13=00007ffa83f23000
     3403         * r14=0000000000000000 r15=0000025f4f03af90
     3404         * iopl=0         nv up ei pl nz na po nc
     3405         * cs=0033  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010206
     3406         * SETUPAPI!DereferenceClassDriverList+0x4e:
     3407         * 00007ffa`83e2a42a 834008ff        add     dword ptr [rax+8],0FFFFFFFFh ds:00000000`00000008=????????
     3408         *
     3409         */
    34603410        if (destroyList)
    3461             SetupDiDestroyDriverInfoList(hDeviceInfo, &DeviceInfoData,
    3462                                          SPDIT_CLASSDRIVER);
     3411            SetupDiDestroyDriverInfoList(hDeviceInfo, &DeviceInfoData, SPDIT_CLASSDRIVER);
     3412#else
     3413        RT_NOREF(destroyList);
     3414#endif
     3415
    34633416        /* clean up the device info set */
    3464         SetupDiDestroyDeviceInfoList (hDeviceInfo);
    3465     }
    3466 
    3467     /* return the network connection GUID on success */
     3417        SetupDiDestroyDeviceInfoList(hDeviceInfo);
     3418    }
     3419
     3420    /*
     3421     * Return the network connection GUID on success.
     3422     */
    34683423    if (SUCCEEDED(hrc))
    34693424    {
    3470         HRESULT hr;
    3471         INetCfg *pNetCfg = NULL;
    3472         LPWSTR lpszApp = NULL;
    3473 
     3425        /** @todo r=bird: Some please explain this mess. It's not just returning a
     3426         *        GUID here, it's a bit more than that. */
    34743427        RENAMING_CONTEXT context;
    34753428        context.hr = E_FAIL;
     
    34773430        if (pGuid)
    34783431        {
    3479             hrc = CLSIDFromString(pWCfgGuidString, (LPCLSID)pGuid);
     3432            hrc = CLSIDFromString(wszCfgGuidString, (LPCLSID)pGuid);
    34803433            if (FAILED(hrc))
    34813434                NonStandardLogFlow(("CLSIDFromString failed, hrc (0x%x)\n", hrc));
    34823435        }
    34833436
    3484         hr = VBoxNetCfgWinQueryINetCfg(&pNetCfg, TRUE, L"VirtualBox Host-Only Creation",
    3485                                        30 * 1000, /* on Vista we often get 6to4svc.dll holding the lock, wait for 30 sec.  */
    3486                                        /** @todo special handling for 6to4svc.dll ???, i.e. several retrieves */
    3487                                        &lpszApp);
    3488         if (hr == S_OK)
    3489         {
    3490             if (!!bstrNewInterfaceName)
     3437        INetCfg *pNetCfg = NULL;
     3438        LPWSTR   pwszApp = NULL;
     3439        HRESULT hrc2 = VBoxNetCfgWinQueryINetCfg(&pNetCfg, TRUE, L"VirtualBox Host-Only Creation",
     3440                                                 30 * 1000, /* on Vista we often get 6to4svc.dll holding the lock, wait for 30 sec.  */
     3441                                                 /** @todo special handling for 6to4svc.dll ???, i.e. several retrieves */
     3442                                                 &pwszApp);
     3443        if (hrc2 == S_OK)
     3444        {
     3445            if (bstrNewInterfaceName.isNotEmpty())
    34913446            {
    34923447                /* The assigned name does not match the desired one, rename the device */
    3493                 context.bstrName = bstrNewInterfaceName.GetBSTR();
    3494                 context.pGuid = pGuid;
    3495                 hr = vboxNetCfgWinEnumNetCfgComponents(pNetCfg,
    3496                                                        &GUID_DEVCLASS_NET,
    3497                                                        vboxNetCfgWinRenameHostOnlyNetworkInterface,
    3498                                                        &context);
    3499             }
    3500             if (SUCCEEDED(hr))
    3501                 hr = vboxNetCfgWinEnumNetCfgComponents(pNetCfg,
    3502                                                        &GUID_DEVCLASS_NETSERVICE,
    3503                                                        vboxNetCfgWinAdjustHostOnlyNetworkInterfacePriority,
    3504                                                        pGuid);
    3505             if (SUCCEEDED(hr))
    3506                 hr = vboxNetCfgWinEnumNetCfgComponents(pNetCfg,
    3507                                                        &GUID_DEVCLASS_NETTRANS,
    3508                                                        vboxNetCfgWinAdjustHostOnlyNetworkInterfacePriority,
    3509                                                        pGuid);
    3510             if (SUCCEEDED(hr))
    3511                 hr = vboxNetCfgWinEnumNetCfgComponents(pNetCfg,
    3512                                                        &GUID_DEVCLASS_NETCLIENT,
    3513                                                        vboxNetCfgWinAdjustHostOnlyNetworkInterfacePriority,
    3514                                                        pGuid);
    3515             if (SUCCEEDED(hr))
    3516             {
    3517                 hr = pNetCfg->Apply();
    3518             }
     3448                context.bstrName = bstrNewInterfaceName.raw();
     3449                context.pGuid    = pGuid;
     3450                hrc2 = vboxNetCfgWinEnumNetCfgComponents(pNetCfg, &GUID_DEVCLASS_NET,
     3451                                                         vboxNetCfgWinRenameHostOnlyNetworkInterface, &context);
     3452            }
     3453            if (SUCCEEDED(hrc2))
     3454                hrc2 = vboxNetCfgWinEnumNetCfgComponents(pNetCfg, &GUID_DEVCLASS_NETSERVICE,
     3455                                                         vboxNetCfgWinAdjustHostOnlyNetworkInterfacePriority, pGuid);
     3456            if (SUCCEEDED(hrc2))
     3457                hrc2 = vboxNetCfgWinEnumNetCfgComponents(pNetCfg, &GUID_DEVCLASS_NETTRANS,
     3458                                                         vboxNetCfgWinAdjustHostOnlyNetworkInterfacePriority, pGuid);
     3459            if (SUCCEEDED(hrc2))
     3460                hrc2 = vboxNetCfgWinEnumNetCfgComponents(pNetCfg, &GUID_DEVCLASS_NETCLIENT,
     3461                                                         vboxNetCfgWinAdjustHostOnlyNetworkInterfacePriority, pGuid);
     3462            if (SUCCEEDED(hrc2))
     3463                hrc2 = pNetCfg->Apply();
    35193464            else
    3520                 NonStandardLogFlow(("Enumeration failed, hr 0x%x\n", hr));
     3465                NonStandardLogFlow(("Enumeration failed, hrc2=%Rhrc\n", hrc2));
     3466
    35213467            VBoxNetCfgWinReleaseINetCfg(pNetCfg, TRUE);
    35223468        }
    3523         else if (hr == NETCFG_E_NO_WRITE_LOCK && lpszApp)
    3524         {
    3525             NonStandardLogFlow(("Application %ws is holding the lock, failed\n", lpszApp));
    3526             CoTaskMemFree(lpszApp);
     3469        else if (hrc2 == NETCFG_E_NO_WRITE_LOCK && pwszApp)
     3470        {
     3471            NonStandardLogFlow(("Application '%ls' is holding the lock, failed\n", pwszApp));
     3472            CoTaskMemFree(pwszApp);
     3473            pwszApp = NULL;
    35273474        }
    35283475        else
    3529             NonStandardLogFlow(("VBoxNetCfgWinQueryINetCfg failed, hr 0x%x\n", hr));
     3476            NonStandardLogFlow(("VBoxNetCfgWinQueryINetCfg failed, hrc2=%Rhrc\n", hrc2));
    35303477
    35313478#ifndef VBOXNETCFG_DELAYEDRENAME
    3532         if (SUCCEEDED(hr) && SUCCEEDED(context.hr))
    3533         {
    3534             /* The device has been successfully renamed, replace the name now. */
    3535             wcscpy_s(DevName, RT_ELEMENTS(DevName), bstrDesiredName);
    3536         }
    3537 
    3538         WCHAR ConnectionName[128];
    3539         ULONG cbName = sizeof(ConnectionName);
    3540 
    3541         hr = VBoxNetCfgWinGenHostonlyConnectionName(DevName, ConnectionName, &cbName);
    3542         if (SUCCEEDED(hr))
    3543             hr = VBoxNetCfgWinRenameConnection(pWCfgGuidString, ConnectionName);
     3479        /* If the device has been successfully renamed, replace the name now. */
     3480        if (SUCCEEDED(hrc2) && SUCCEEDED(context.hr))
     3481            RTUtf16Copy(wszDevName, RT_ELEMENTS(wszDevName), pBstrDesiredName);
     3482
     3483        WCHAR wszConnectionName[128];
     3484        hrc2 = VBoxNetCfgWinGenHostonlyConnectionName(wszDevName, wszConnectionName, RT_ELEMENTS(wszConnectionName), NULL);
     3485        if (SUCCEEDED(hrc2))
     3486            hrc2 = VBoxNetCfgWinRenameConnection(wszCfgGuidString, wszConnectionName);
    35443487#endif
    3545         if (lppszName)
    3546         {
    3547             *lppszName = SysAllocString((const OLECHAR *) DevName);
    3548             if (!*lppszName)
     3488
     3489        /*
     3490         * Now, return the network connection GUID/name.
     3491         */
     3492        if (pBstrName)
     3493        {
     3494            *pBstrName = SysAllocString((const OLECHAR *)wszDevName);
     3495            if (!*pBstrName)
    35493496            {
    35503497                NonStandardLogFlow(("SysAllocString failed\n"));
    3551                 hrc = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY);
    3552             }
    3553         }
    3554     }
    3555 
    3556     if (pErrMsg && bstrError.length())
    3557         *pErrMsg = bstrError.Detach();
    3558 
     3498                hrc = E_OUTOFMEMORY;
     3499            }
     3500        }
     3501    }
     3502
     3503    if (pBstrErrMsg)
     3504    {
     3505        *pBstrErrMsg = NULL;
     3506        if (bstrError.isNotEmpty())
     3507            bstrError.detachToEx(pBstrErrMsg);
     3508    }
    35593509    return hrc;
    35603510}
    35613511
    3562 VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinCreateHostOnlyNetworkInterface(IN LPCWSTR pInfPath, IN bool bIsInfPathFile, IN BSTR pwsDesiredName,
    3563                                                                         OUT GUID *pGuid, OUT BSTR *lppszName, OUT BSTR *pErrMsg)
    3564 {
    3565     HRESULT hrc = vboxNetCfgWinCreateHostOnlyNetworkInterface(pInfPath, bIsInfPathFile, pwsDesiredName, pGuid, lppszName, pErrMsg);
     3512VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinCreateHostOnlyNetworkInterface(IN LPCWSTR pwszInfPath, IN bool fIsInfPathFile,
     3513                                                                        IN BSTR pwszDesiredName, OUT GUID *pGuid,
     3514                                                                        OUT BSTR *pBstrName, OUT BSTR *pBstrErrMsg)
     3515{
     3516    HRESULT hrc = vboxNetCfgWinCreateHostOnlyNetworkInterface(pwszInfPath, fIsInfPathFile, pwszDesiredName,
     3517                                                              pGuid, pBstrName, pBstrErrMsg);
    35663518    if (hrc == E_ABORT)
    35673519    {
    35683520        NonStandardLogFlow(("Timed out while waiting for NetCfgInstanceId, try again immediately...\n"));
     3521
    35693522        /*
    35703523         * This is the first time we fail to obtain NetCfgInstanceId, let us
     
    35753528         * See @bugref{7973} for details.
    35763529         */
    3577         hrc = vboxNetCfgWinCreateHostOnlyNetworkInterface(pInfPath, bIsInfPathFile, pwsDesiredName, pGuid, lppszName, pErrMsg);
     3530        hrc = vboxNetCfgWinCreateHostOnlyNetworkInterface(pwszInfPath, fIsInfPathFile, pwszDesiredName,
     3531                                                          pGuid, pBstrName, pBstrErrMsg);
    35783532        if (hrc == E_ABORT)
    35793533        {
    35803534            NonStandardLogFlow(("Timed out again while waiting for NetCfgInstanceId, try again after a while...\n"));
     3535
    35813536            /*
    35823537             * This is the second time we fail to obtain NetCfgInstanceId, let us
     
    35853540             * conditions. See @bugref{7973} for details.
    35863541             */
    3587 
    3588             SC_HANDLE hSCM = NULL;
    3589             SC_HANDLE hService = NULL;
    3590 
    3591             hSCM = OpenSCManager(NULL, NULL, GENERIC_READ);
     3542            SC_HANDLE hSCM = OpenSCManagerW(NULL, NULL, GENERIC_READ);
    35923543            if (hSCM)
    35933544            {
    3594                 hService = OpenService(hSCM, _T("NetSetupSvc"), GENERIC_READ);
     3545                SC_HANDLE hService = OpenServiceW(hSCM, L"NetSetupSvc", GENERIC_READ);
    35953546                if (hService)
    35963547                {
     
    35983549                        Sleep(1000);
    35993550                    CloseServiceHandle(hService);
    3600                     hrc = vboxNetCfgWinCreateHostOnlyNetworkInterface(pInfPath, bIsInfPathFile, pwsDesiredName, pGuid, lppszName, pErrMsg);
     3551                    hrc = vboxNetCfgWinCreateHostOnlyNetworkInterface(pwszInfPath, fIsInfPathFile, pwszDesiredName,
     3552                                                                      pGuid, pBstrName, pBstrErrMsg);
    36013553                }
    36023554                else
    3603                     NonStandardLogFlow(("OpenService failed (0x%x)\n", GetLastError()));
     3555                    NonStandardLogFlow(("OpenService failed (%Rwc)\n", GetLastError()));
    36043556                CloseServiceHandle(hSCM);
    36053557            }
    36063558            else
    3607                 NonStandardLogFlow(("OpenSCManager failed (0x%x)", GetLastError()));
     3559                NonStandardLogFlow(("OpenSCManager failed (%Rwc)", GetLastError()));
     3560
    36083561            /* Give up and report the error. */
    36093562            if (hrc == E_ABORT)
    36103563            {
    3611                 if (pErrMsg)
    3612                 {
    3613                     bstr_t bstrError = bstr_printf("Querying NetCfgInstanceId failed (0x%08X)", ERROR_FILE_NOT_FOUND);
    3614                     *pErrMsg = bstrError.Detach();
     3564                if (pBstrErrMsg)
     3565                {
     3566                    com::Bstr bstrError;
     3567                    bstrError.printfNoThrow("Querying NetCfgInstanceId failed (ERROR_FILE_NOT_FOUND)");
     3568                    bstrError.detachToEx(pBstrErrMsg);
    36153569                }
    36163570                hrc = E_FAIL;
     
    36213575}
    36223576
    3623 
    3624 HRESULT vboxLoadIpHelpFunctions(HINSTANCE& pIpHlpInstance)
    3625 {
    3626     Assert(pIpHlpInstance != NULL);
    3627 
    3628     pIpHlpInstance = loadSystemDll("Iphlpapi.dll");
    3629     if (pIpHlpInstance == NULL)
    3630         return E_FAIL;
    3631 
    3632     g_pfnInitializeIpInterfaceEntry =
    3633         (PFNINITIALIZEIPINTERFACEENTRY)GetProcAddress(pIpHlpInstance, "InitializeIpInterfaceEntry");
    3634     Assert(g_pfnInitializeIpInterfaceEntry);
    3635 
    3636     if (g_pfnInitializeIpInterfaceEntry)
    3637     {
    3638         g_pfnGetIpInterfaceEntry =
    3639             (PFNGETIPINTERFACEENTRY)GetProcAddress(pIpHlpInstance, "GetIpInterfaceEntry");
    3640         Assert(g_pfnGetIpInterfaceEntry);
    3641     }
    3642 
    3643     if (g_pfnGetIpInterfaceEntry)
    3644     {
    3645         g_pfnSetIpInterfaceEntry =
    3646             (PFNSETIPINTERFACEENTRY)GetProcAddress(pIpHlpInstance, "SetIpInterfaceEntry");
    3647         Assert(g_pfnSetIpInterfaceEntry);
    3648     }
    3649 
    3650     if (g_pfnInitializeIpInterfaceEntry == NULL)
    3651     {
    3652         FreeLibrary(pIpHlpInstance);
    3653         pIpHlpInstance = NULL;
    3654         return E_FAIL;
    3655     }
    3656 
    3657     return S_OK;
    3658 }
    3659 
    3660 
    3661 HRESULT vboxNetCfgWinGetLoopbackMetric(OUT int* Metric)
    3662 {
    3663     HRESULT rc = S_OK;
    3664     MIB_IPINTERFACE_ROW row;
    3665 
     3577static HRESULT vboxNetCfgWinGetLoopbackMetric(OUT DWORD *Metric)
     3578{
    36663579    Assert(g_pfnInitializeIpInterfaceEntry != NULL);
    36673580    Assert(g_pfnGetIpInterfaceEntry != NULL);
    36683581
     3582    MIB_IPINTERFACE_ROW row;
     3583    RT_ZERO(row); /* paranoia */
    36693584    g_pfnInitializeIpInterfaceEntry(&row);
     3585
    36703586    row.Family = AF_INET;
    36713587    row.InterfaceLuid.Info.IfType = IF_TYPE_SOFTWARE_LOOPBACK;
    36723588
    3673     rc = g_pfnGetIpInterfaceEntry(&row);
    3674     if (rc != NO_ERROR)
    3675         return HRESULT_FROM_WIN32(rc);
    3676 
    3677     *Metric = row.Metric;
    3678 
    3679     return rc;
    3680 }
    3681 
    3682 
    3683 HRESULT vboxNetCfgWinSetInterfaceMetric(
    3684     IN NET_LUID* pInterfaceLuid,
    3685     IN DWORD metric)
    3686 {
    3687     MIB_IPINTERFACE_ROW newRow;
    3688 
     3589    NETIO_STATUS dwErr = g_pfnGetIpInterfaceEntry(&row);
     3590    if (dwErr == NO_ERROR)
     3591    {
     3592        *Metric = row.Metric;
     3593        return S_OK;
     3594    }
     3595    return HRESULT_FROM_WIN32(dwErr);
     3596}
     3597
     3598static HRESULT vboxNetCfgWinSetInterfaceMetric(IN NET_LUID *pInterfaceLuid, IN DWORD metric)
     3599{
    36893600    Assert(g_pfnInitializeIpInterfaceEntry != NULL);
    36903601    Assert(g_pfnSetIpInterfaceEntry != NULL);
    36913602
     3603    MIB_IPINTERFACE_ROW newRow;
     3604    RT_ZERO(newRow); /* paranoia */
    36923605    g_pfnInitializeIpInterfaceEntry(&newRow);
     3606
    36933607    // identificate the interface to change
    36943608    newRow.InterfaceLuid = *pInterfaceLuid;
    36953609    newRow.Family = AF_INET;
     3610
    36963611    // changed settings
    36973612    newRow.UseAutomaticMetric = false;
     
    36993614
    37003615    // change settings
    3701     return HRESULT_FROM_WIN32(g_pfnSetIpInterfaceEntry(&newRow));
    3702 }
    3703 
    3704 
    3705 HRESULT vboxNetCfgWinGetInterfaceLUID(IN HKEY hKey, OUT NET_LUID* pLUID)
    3706 {
    3707     HRESULT res = S_OK;
    3708     DWORD luidIndex = 0;
    3709     DWORD ifType = 0;
    3710     DWORD cbSize = sizeof(luidIndex);
    3711     DWORD dwValueType = REG_DWORD;
    3712 
     3616    NETIO_STATUS dwErr = g_pfnSetIpInterfaceEntry(&newRow);
     3617    if (dwErr == NO_ERROR)
     3618        return S_OK;
     3619    return HRESULT_FROM_WIN32(dwErr);
     3620}
     3621
     3622static HRESULT vboxNetCfgWinSetupMetric(IN NET_LUID* pLuid)
     3623{
     3624    HRESULT  hrc  = E_FAIL;
     3625    HMODULE  hmod = loadSystemDll(L"Iphlpapi.dll");
     3626    if (hmod)
     3627    {
     3628        g_pfnInitializeIpInterfaceEntry = (PFNINITIALIZEIPINTERFACEENTRY)GetProcAddress(hmod, "InitializeIpInterfaceEntry");
     3629        g_pfnGetIpInterfaceEntry        = (PFNGETIPINTERFACEENTRY)       GetProcAddress(hmod, "GetIpInterfaceEntry");
     3630        g_pfnSetIpInterfaceEntry        = (PFNSETIPINTERFACEENTRY)       GetProcAddress(hmod, "SetIpInterfaceEntry");
     3631        Assert(g_pfnInitializeIpInterfaceEntry);
     3632        Assert(g_pfnGetIpInterfaceEntry);
     3633        Assert(g_pfnSetIpInterfaceEntry);
     3634
     3635        if (   g_pfnInitializeIpInterfaceEntry
     3636            && g_pfnGetIpInterfaceEntry
     3637            && g_pfnSetIpInterfaceEntry)
     3638        {
     3639            DWORD loopbackMetric = 0;
     3640            hrc = vboxNetCfgWinGetLoopbackMetric(&loopbackMetric);
     3641            if (SUCCEEDED(hrc))
     3642                hrc = vboxNetCfgWinSetInterfaceMetric(pLuid, loopbackMetric - 1);
     3643        }
     3644
     3645        g_pfnInitializeIpInterfaceEntry = NULL;
     3646        g_pfnSetIpInterfaceEntry        = NULL;
     3647        g_pfnGetIpInterfaceEntry        = NULL;
     3648
     3649        FreeLibrary(hmod);
     3650    }
     3651    return hrc;
     3652}
     3653
     3654static HRESULT vboxNetCfgWinGetInterfaceLUID(IN HKEY hKey, OUT NET_LUID *pLUID)
     3655{
    37133656    if (pLUID == NULL)
    37143657        return E_INVALIDARG;
    37153658
    3716     res = RegQueryValueExW(hKey, L"NetLuidIndex", NULL,
    3717         &dwValueType, (LPBYTE)&luidIndex, &cbSize);
    3718     if (res != 0)
    3719         return HRESULT_FROM_WIN32(res);
    3720 
    3721     cbSize = sizeof(ifType);
    3722     dwValueType = REG_DWORD;
    3723     res = RegQueryValueExW(hKey, L"*IfType", NULL,
    3724         &dwValueType, (LPBYTE)&ifType, &cbSize);
    3725     if (res != 0)
    3726         return HRESULT_FROM_WIN32(res);
    3727 
    3728     ZeroMemory(pLUID, sizeof(NET_LUID));
    3729     pLUID->Info.IfType = ifType;
    3730     pLUID->Info.NetLuidIndex = luidIndex;
    3731 
    3732     return res;
    3733 }
    3734 
    3735 
    3736 HRESULT vboxNetCfgWinSetupMetric(IN NET_LUID* pLuid)
    3737 {
    3738     HINSTANCE hModule = NULL;
    3739     HRESULT rc = vboxLoadIpHelpFunctions(hModule);
    3740     if (SUCCEEDED(rc))
    3741     {
    3742         int loopbackMetric;
    3743         rc = vboxNetCfgWinGetLoopbackMetric(&loopbackMetric);
    3744         if (SUCCEEDED(rc))
    3745             rc = vboxNetCfgWinSetInterfaceMetric(pLuid, loopbackMetric - 1);
    3746     }
    3747 
    3748     g_pfnInitializeIpInterfaceEntry = NULL;
    3749     g_pfnSetIpInterfaceEntry = NULL;
    3750     g_pfnGetIpInterfaceEntry = NULL;
    3751 
    3752     FreeLibrary(hModule);
    3753     return rc;
    3754 }
     3659    DWORD dwLuidIndex = 0;
     3660    DWORD cbSize      = sizeof(dwLuidIndex);
     3661    DWORD dwValueType = REG_DWORD; /** @todo r=bird: This is output only. No checked after the call. So, only for debugging? */
     3662    LSTATUS lrc = RegQueryValueExW(hKey, L"NetLuidIndex", NULL, &dwValueType, (LPBYTE)&dwLuidIndex, &cbSize);
     3663    if (lrc == ERROR_SUCCESS)
     3664    {
     3665        DWORD dwIfType = 0;
     3666        cbSize         = sizeof(dwIfType);
     3667        dwValueType    = REG_DWORD; /** @todo r=bird: This is output only. No checked after the call. So, only for debugging? */
     3668        lrc = RegQueryValueExW(hKey, L"*IfType", NULL, &dwValueType, (LPBYTE)&dwIfType, &cbSize);
     3669        if (lrc == ERROR_SUCCESS)
     3670        {
     3671            RT_ZERO(*pLUID);
     3672            pLUID->Info.IfType       = dwIfType;
     3673            pLUID->Info.NetLuidIndex = dwLuidIndex;
     3674            return S_OK;
     3675        }
     3676    }
     3677
     3678    RT_ZERO(*pLUID);
     3679    return HRESULT_FROM_WIN32(lrc);
     3680}
     3681
     3682
    37553683#ifdef VBOXNETCFG_DELAYEDRENAME
    37563684VBOXNETCFGWIN_DECL(HRESULT) VBoxNetCfgWinRenameHostOnlyConnection(IN const GUID *pGuid, IN LPCWSTR pwszId, OUT BSTR *pDevName)
    37573685{
    3758     HRESULT hr = S_OK;
    3759     WCHAR wszDevName[256];
    3760     WCHAR wszConnectionNewName[128];
    3761     ULONG cbName = sizeof(wszConnectionNewName);
    3762 
     3686    if (pDevName)
     3687        *pDevName = NULL;
     3688
     3689    HRESULT  hr = S_OK; /** @todo r=bird: ODD return status for SetupDiCreateDeviceInfoList failures! */
    37633690    HDEVINFO hDevInfo = SetupDiCreateDeviceInfoList(&GUID_DEVCLASS_NET, NULL);
    37643691    if (hDevInfo != INVALID_HANDLE_VALUE)
    37653692    {
    3766         SP_DEVINFO_DATA DevInfoData;
    3767 
    3768         DevInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
     3693        SP_DEVINFO_DATA DevInfoData = { sizeof(SP_DEVINFO_DATA) };
    37693694        if (SetupDiOpenDeviceInfo(hDevInfo, pwszId, NULL, 0, &DevInfoData))
    37703695        {
     3696            WCHAR wszDevName[256 + 1] = {0};
    37713697            DWORD err = ERROR_SUCCESS;
    3772             if (!SetupDiGetDeviceRegistryPropertyW(hDevInfo, &DevInfoData,
    3773                                                    SPDRP_FRIENDLYNAME, NULL,
    3774                                                    (PBYTE)wszDevName, RT_ELEMENTS(wszDevName), NULL))
     3698            if (!SetupDiGetDeviceRegistryPropertyW(hDevInfo, &DevInfoData, SPDRP_FRIENDLYNAME, NULL /*PropertyRegDataType*/,
     3699                                                   (PBYTE)wszDevName, sizeof(wszDevName) - sizeof(WCHAR) /*yes, bytes*/,
     3700                                                   NULL /*RequiredSize*/))
    37753701            {
    37763702                err = GetLastError();
    37773703                if (err == ERROR_INVALID_DATA)
    37783704                {
    3779                     err = SetupDiGetDeviceRegistryPropertyW(hDevInfo, &DevInfoData,
    3780                                                             SPDRP_DEVICEDESC, NULL,
    3781                                                             (PBYTE)wszDevName, RT_ELEMENTS(wszDevName), NULL)
    3782                         ? ERROR_SUCCESS
    3783                         : GetLastError();
     3705                    RT_ZERO(wszDevName);
     3706                    if (SetupDiGetDeviceRegistryPropertyW(hDevInfo, &DevInfoData, SPDRP_DEVICEDESC, NULL /*PropertyRegDataType*/,
     3707                                                          (PBYTE)wszDevName, sizeof(wszDevName) - sizeof(WCHAR) /*yes, bytes*/,
     3708                                                          NULL /*RequiredSize*/))
     3709                        err = ERROR_SUCCESS;
     3710                    else
     3711                        err = GetLastError();
    37843712                }
    37853713            }
    37863714            if (err == ERROR_SUCCESS)
    37873715            {
    3788                 hr = VBoxNetCfgWinGenHostonlyConnectionName(wszDevName, wszConnectionNewName, &cbName);
     3716                WCHAR wszConnectionNewName[128] = {0};
     3717                hr = VBoxNetCfgWinGenHostonlyConnectionName(wszDevName, wszConnectionNewName,
     3718                                                            RT_ELEMENTS(wszConnectionNewName), NULL);
    37893719                if (SUCCEEDED(hr))
    37903720                {
  • trunk/src/VBox/HostDrivers/VBoxNetFlt/win/nobj/VBoxNetFltNobj.cpp

    r96407 r96572  
    22/** @file
    33 * VBoxNetFltNobj.cpp - Notify Object for Bridged Networking Driver.
     4 *
    45 * Used to filter Bridged Networking Driver bindings
    56 */
     7
    68/*
    79 * Copyright (C) 2011-2022 Oracle and/or its affiliates.
     
    3436 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
    3537 */
     38
     39
     40/*********************************************************************************************************************************
     41*   Header Files                                                                                                                 *
     42*********************************************************************************************************************************/
    3643#include "VBoxNetFltNobj.h"
    3744#include <iprt/win/ntddndis.h>
    38 #include <assert.h>
    39 #include <stdio.h>
     45#include <iprt/win/windows.h>
     46#include <winreg.h>
     47#include <Olectl.h>
    4048
    4149#include <VBoxNetFltNobjT_i.c>
    4250
    43 #include <Olectl.h>
    44 
     51#include <iprt/assert.h>
     52#include <iprt/utf16.h>
     53#include <iprt/string.h>
     54
     55
     56/*********************************************************************************************************************************
     57*   Defined Constants And Macros                                                                                                 *
     58*********************************************************************************************************************************/
    4559//# define VBOXNETFLTNOTIFY_DEBUG_BIND
    4660
    4761#ifdef DEBUG
    48 # define NonStandardAssert(a) assert(a)
    49 # define NonStandardAssertBreakpoint() assert(0)
     62# define NonStandardAssert(a)           Assert(a)
     63# define NonStandardAssertBreakpoint()  AssertFailed()
    5064#else
    5165# define NonStandardAssert(a) do{}while (0)
     
    5367#endif
    5468
    55 VBoxNetFltNobj::VBoxNetFltNobj() :
    56     mpNetCfg(NULL),
    57     mpNetCfgComponent(NULL),
    58     mbInstalling(FALSE)
     69
     70/*********************************************************************************************************************************
     71*   Global Variables                                                                                                             *
     72*********************************************************************************************************************************/
     73static HMODULE g_hModSelf = (HMODULE)~(uintptr_t)0;
     74
     75
     76VBoxNetFltNobj::VBoxNetFltNobj()
     77    : mpNetCfg(NULL)
     78    , mpNetCfgComponent(NULL)
     79    , mbInstalling(FALSE)
    5980{
    6081}
     
    126147static HRESULT vboxNetFltWinQueryInstanceKey(IN INetCfgComponent *pComponent, OUT PHKEY phKey)
    127148{
    128     LPWSTR pPnpId;
    129     HRESULT hr = pComponent->GetPnpDevNodeId(&pPnpId);
    130     if (hr == S_OK)
    131     {
    132         WCHAR KeyName[MAX_PATH];
    133         wcscpy(KeyName, L"SYSTEM\\CurrentControlSet\\Enum\\");
    134         wcscat(KeyName,pPnpId);
    135 
    136         LONG winEr = RegOpenKeyExW(HKEY_LOCAL_MACHINE, KeyName,
    137           0, /*__reserved DWORD ulOptions*/
    138           KEY_READ, /*__in REGSAM samDesired*/
    139           phKey);
    140 
    141         if (winEr != ERROR_SUCCESS)
    142         {
    143             hr = HRESULT_FROM_WIN32(winEr);
     149    LPWSTR pwszPnpId;
     150    HRESULT hrc = pComponent->GetPnpDevNodeId(&pwszPnpId);
     151    if (hrc == S_OK)
     152    {
     153        WCHAR wszKeyName[MAX_PATH];
     154        RTUtf16Copy(wszKeyName, MAX_PATH, L"SYSTEM\\CurrentControlSet\\Enum\\");
     155        int rc = RTUtf16Cat(wszKeyName, MAX_PATH, pwszPnpId);
     156        if (RT_SUCCESS(rc))
     157        {
     158            LSTATUS lrc = RegOpenKeyExW(HKEY_LOCAL_MACHINE, wszKeyName, 0 /*ulOptions*/, KEY_READ, phKey);
     159            if (lrc != ERROR_SUCCESS)
     160            {
     161                hrc = HRESULT_FROM_WIN32(lrc);
     162                NonStandardAssertBreakpoint();
     163            }
     164        }
     165        else
     166            AssertRCStmt(rc, hrc = ERROR_BUFFER_OVERFLOW);
     167
     168        CoTaskMemFree(pwszPnpId);
     169    }
     170    else
     171        NonStandardAssertBreakpoint();
     172    return hrc;
     173}
     174
     175static HRESULT vboxNetFltWinQueryDriverKey(IN HKEY InstanceKey, OUT PHKEY phKey)
     176{
     177    HRESULT hrc = S_OK;
     178
     179    WCHAR   wszValue[MAX_PATH];
     180    DWORD   cbValue = sizeof(wszValue) - sizeof(WCHAR);
     181    DWORD   dwType  = REG_SZ;
     182    LSTATUS lrc = RegQueryValueExW(InstanceKey, L"Driver", NULL /*lpReserved*/, &dwType, (LPBYTE)wszValue, &cbValue);
     183    if (lrc == ERROR_SUCCESS)
     184    {
     185        if (dwType == REG_SZ)
     186        {
     187            wszValue[RT_ELEMENTS(wszValue) - 1] = '\0'; /* registry strings does not need to be zero terminated. */
     188
     189            WCHAR wszKeyName[MAX_PATH];
     190            RTUtf16Copy(wszKeyName, MAX_PATH, L"SYSTEM\\CurrentControlSet\\Control\\Class\\");
     191            int rc = RTUtf16Cat(wszKeyName, MAX_PATH, wszValue);
     192            if (RT_SUCCESS(rc))
     193            {
     194                lrc = RegOpenKeyExW(HKEY_LOCAL_MACHINE, wszKeyName, 0 /*ulOptions*/, KEY_READ, phKey);
     195                if (lrc != ERROR_SUCCESS)
     196                {
     197                    hrc = HRESULT_FROM_WIN32(lrc);
     198                    NonStandardAssertBreakpoint();
     199                }
     200            }
     201            else
     202                AssertRCStmt(rc, hrc = ERROR_BUFFER_OVERFLOW);
     203        }
     204        else
     205        {
     206            hrc = HRESULT_FROM_WIN32(ERROR_DATATYPE_MISMATCH);
    144207            NonStandardAssertBreakpoint();
    145208        }
    146 
    147         CoTaskMemFree(pPnpId);
    148209    }
    149210    else
    150211    {
    151         NonStandardAssertBreakpoint();
    152     }
    153 
    154     return hr;
    155 }
    156 
    157 static HRESULT vboxNetFltWinQueryDriverKey(IN HKEY InstanceKey, OUT PHKEY phKey)
    158 {
    159     DWORD Type = REG_SZ;
    160     WCHAR Value[MAX_PATH];
    161     DWORD cbValue = sizeof(Value);
    162     HRESULT hr = S_OK;
    163     LONG winEr = RegQueryValueExW(InstanceKey,
    164             L"Driver", /*__in_opt LPCTSTR lpValueName*/
    165             0, /*__reserved LPDWORD lpReserved*/
    166             &Type, /*__out_opt LPDWORD lpType*/
    167             (LPBYTE)Value, /*__out_opt LPBYTE lpData*/
    168             &cbValue/*__inout_opt LPDWORD lpcbData*/
    169             );
    170 
    171     if (winEr == ERROR_SUCCESS)
    172     {
    173         WCHAR KeyName[MAX_PATH];
    174         wcscpy(KeyName, L"SYSTEM\\CurrentControlSet\\Control\\Class\\");
    175         wcscat(KeyName,Value);
    176 
    177         winEr = RegOpenKeyExW(HKEY_LOCAL_MACHINE, KeyName,
    178           0, /*__reserved DWORD ulOptions*/
    179           KEY_READ, /*__in REGSAM samDesired*/
    180           phKey);
    181 
    182         if (winEr != ERROR_SUCCESS)
    183         {
    184             hr = HRESULT_FROM_WIN32(winEr);
     212        hrc = HRESULT_FROM_WIN32(lrc);
     213        NonStandardAssertBreakpoint();
     214    }
     215
     216    return hrc;
     217}
     218
     219static HRESULT vboxNetFltWinQueryDriverKey(IN INetCfgComponent *pComponent, OUT PHKEY phKey)
     220{
     221    HKEY    hKeyInstance = NULL;
     222    HRESULT hrc = vboxNetFltWinQueryInstanceKey(pComponent, &hKeyInstance);
     223    if (hrc == S_OK)
     224    {
     225        hrc = vboxNetFltWinQueryDriverKey(hKeyInstance, phKey);
     226        if (hrc != S_OK)
    185227            NonStandardAssertBreakpoint();
    186         }
     228        RegCloseKey(hKeyInstance);
    187229    }
    188230    else
    189     {
    190         hr = HRESULT_FROM_WIN32(winEr);
    191         NonStandardAssertBreakpoint();
    192     }
    193 
    194     return hr;
    195 }
    196 
    197 static HRESULT vboxNetFltWinQueryDriverKey(IN INetCfgComponent *pComponent, OUT PHKEY phKey)
    198 {
    199     HKEY InstanceKey;
    200     HRESULT hr = vboxNetFltWinQueryInstanceKey(pComponent, &InstanceKey);
    201     if (hr == S_OK)
    202     {
    203         hr = vboxNetFltWinQueryDriverKey(InstanceKey, phKey);
    204         if (hr != S_OK)
    205         {
    206             NonStandardAssertBreakpoint();
    207         }
    208         RegCloseKey(InstanceKey);
     231        NonStandardAssertBreakpoint();
     232    return hrc;
     233}
     234
     235static HRESULT vboxNetFltWinNotifyCheckNetAdp(IN INetCfgComponent *pComponent, OUT bool *pfShouldBind)
     236{
     237    *pfShouldBind = false;
     238
     239    LPWSTR  pwszDevId = NULL;
     240    HRESULT hrc = pComponent->GetId(&pwszDevId);
     241    if (hrc == S_OK)
     242    {
     243        /** @todo r=bird: This was _wcsnicmp(pwszDevId, L"sun_VBoxNetAdp", sizeof(L"sun_VBoxNetAdp")/2))
     244         * which includes the terminator, so it translates to a full compare. Goes way back. */
     245        if (RTUtf16ICmpAscii(pwszDevId, "sun_VBoxNetAdp") == 0)
     246            *pfShouldBind = false;
     247        else
     248            hrc = S_FALSE;
     249        CoTaskMemFree(pwszDevId);
    209250    }
    210251    else
    211     {
    212         NonStandardAssertBreakpoint();
    213     }
    214 
    215     return hr;
    216 }
    217 
    218 static HRESULT vboxNetFltWinNotifyCheckNetAdp(IN INetCfgComponent *pComponent, OUT bool * pbShouldBind)
    219 {
    220     HRESULT hr;
    221     LPWSTR pDevId;
    222     hr = pComponent->GetId(&pDevId);
    223     if (hr == S_OK)
    224     {
    225         if (!_wcsnicmp(pDevId, L"sun_VBoxNetAdp", sizeof(L"sun_VBoxNetAdp")/2))
    226         {
    227             *pbShouldBind = false;
    228         }
    229         else
    230         {
    231             hr = S_FALSE;
    232         }
    233         CoTaskMemFree(pDevId);
    234     }
    235     else
    236     {
    237         NonStandardAssertBreakpoint();
    238     }
    239 
    240     return hr;
    241 }
    242 
    243 static HRESULT vboxNetFltWinNotifyCheckMsLoop(IN INetCfgComponent *pComponent, OUT bool * pbShouldBind)
    244 {
    245     HRESULT hr;
    246     LPWSTR pDevId;
    247     hr = pComponent->GetId(&pDevId);
    248     if (hr == S_OK)
    249     {
    250         if (!_wcsnicmp(pDevId, L"*msloop", sizeof(L"*msloop")/2))
     252        NonStandardAssertBreakpoint();
     253
     254    return hrc;
     255}
     256
     257static HRESULT vboxNetFltWinNotifyCheckMsLoop(IN INetCfgComponent *pComponent, OUT bool *pfShouldBind)
     258{
     259    *pfShouldBind = false;
     260
     261    LPWSTR  pwszDevId = NULL;
     262    HRESULT hrc = pComponent->GetId(&pwszDevId);
     263    if (hrc == S_OK)
     264    {
     265        /** @todo r=bird: This was _wcsnicmp(pwszDevId, L"*msloop", sizeof(L"*msloop")/2)
     266         * which includes the terminator, making it a full compare. Goes way back. */
     267        if (RTUtf16ICmpAscii(pwszDevId, "*msloop") == 0)
    251268        {
    252269            /* we need to detect the medium the adapter is presenting
    253270             * to do that we could examine in the registry the *msloop params */
    254             HKEY DriverKey;
    255             hr = vboxNetFltWinQueryDriverKey(pComponent, &DriverKey);
    256             if (hr == S_OK)
     271            HKEY hKeyDriver;
     272            hrc = vboxNetFltWinQueryDriverKey(pComponent, &hKeyDriver);
     273            if (hrc == S_OK)
    257274            {
    258                 DWORD Type = REG_SZ;
    259                 WCHAR Value[64]; /* 2 should be enough actually, paranoid check for extra spaces */
    260                 DWORD cbValue = sizeof(Value);
    261                 LONG winEr = RegQueryValueExW(DriverKey,
    262                             L"Medium", /*__in_opt LPCTSTR lpValueName*/
    263                             0, /*__reserved LPDWORD lpReserved*/
    264                             &Type, /*__out_opt LPDWORD lpType*/
    265                             (LPBYTE)Value, /*__out_opt LPBYTE lpData*/
    266                             &cbValue/*__inout_opt LPDWORD lpcbData*/
    267                             );
    268                 if (winEr == ERROR_SUCCESS)
     275                WCHAR wszValue[64]; /* 2 should be enough actually, paranoid check for extra spaces */
     276                DWORD cbValue = sizeof(wszValue) - sizeof(WCHAR);
     277                DWORD dwType  = REG_SZ;
     278                LSTATUS lrc = RegQueryValueExW(hKeyDriver, L"Medium", NULL /*lpReserved*/, &dwType, (LPBYTE)wszValue, &cbValue);
     279                if (lrc == ERROR_SUCCESS)
    269280                {
    270                     PWCHAR endPrt;
    271                     ULONG enmMedium = wcstoul(Value,
    272                        &endPrt,
    273                        0 /* base*/);
    274 
    275                     winEr = errno;
    276                     if (winEr == ERROR_SUCCESS)
     281                    if (dwType == REG_SZ)
    277282                    {
    278                         if (enmMedium == 0) /* 0 is Ethernet */
     283                        wszValue[RT_ELEMENTS(wszValue) - 1] = '\0';
     284
     285                        char szUtf8[256];
     286                        char *pszUtf8 = szUtf8;
     287                        RTUtf16ToUtf8Ex(wszValue, RTSTR_MAX, &pszUtf8, sizeof(szUtf8), NULL);
     288                        pszUtf8 = RTStrStrip(pszUtf8);
     289
     290                        uint64_t uValue = 0;
     291                        int rc = RTStrToUInt64Ex(pszUtf8, NULL, 0, &uValue);
     292                        if (RT_SUCCESS(rc))
    279293                        {
    280                             *pbShouldBind = true;
     294                            if (uValue == 0) /* 0 is Ethernet */
     295                                *pfShouldBind = true;
     296                            else
     297                                *pfShouldBind = false;
    281298                        }
    282299                        else
    283300                        {
    284                             *pbShouldBind = false;
     301                            NonStandardAssertBreakpoint();
     302                            *pfShouldBind = true;
    285303                        }
    286304                    }
    287305                    else
    288                     {
    289306                        NonStandardAssertBreakpoint();
    290                         *pbShouldBind = true;
    291                     }
    292307                }
    293308                else
     
    295310                    /** @todo we should check the default medium in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002bE10318}\<driver_id>\Ndi\Params\Medium, REG_SZ "Default" value */
    296311                    NonStandardAssertBreakpoint();
    297                     *pbShouldBind = true;
     312                    *pfShouldBind = true;
    298313                }
    299314
    300                 RegCloseKey(DriverKey);
     315                RegCloseKey(hKeyDriver);
    301316            }
    302317            else
     318                NonStandardAssertBreakpoint();
     319        }
     320        else
     321            hrc = S_FALSE;
     322        CoTaskMemFree(pwszDevId);
     323    }
     324    else
     325        NonStandardAssertBreakpoint();
     326    return hrc;
     327}
     328
     329static HRESULT vboxNetFltWinNotifyCheckLowerRange(IN INetCfgComponent *pComponent, OUT bool *pfShouldBind)
     330{
     331    *pfShouldBind = false;
     332
     333    HKEY    hKeyDriver = NULL;
     334    HRESULT hrc = vboxNetFltWinQueryDriverKey(pComponent, &hKeyDriver);
     335    if (hrc == S_OK)
     336    {
     337        HKEY    hKeyInterfaces = NULL;
     338        LSTATUS lrc = RegOpenKeyExW(hKeyDriver, L"Ndi\\Interfaces", 0 /*ulOptions*/, KEY_READ, &hKeyInterfaces);
     339        if (lrc == ERROR_SUCCESS)
     340        {
     341            WCHAR wszValue[MAX_PATH];
     342            DWORD cbValue = sizeof(wszValue) - sizeof(WCHAR);
     343            DWORD dwType  = REG_SZ;
     344            lrc = RegQueryValueExW(hKeyInterfaces, L"LowerRange", NULL /*lpReserved*/, &dwType, (LPBYTE)wszValue, &cbValue);
     345            if (lrc == ERROR_SUCCESS)
    303346            {
    304                 NonStandardAssertBreakpoint();
    305             }
    306         }
    307         else
    308         {
    309             hr = S_FALSE;
    310         }
    311         CoTaskMemFree(pDevId);
    312     }
    313     else
    314     {
    315         NonStandardAssertBreakpoint();
    316     }
    317 
    318     return hr;
    319 }
    320 
    321 static HRESULT vboxNetFltWinNotifyCheckLowerRange(IN INetCfgComponent *pComponent, OUT bool * pbShouldBind)
    322 {
    323     HKEY DriverKey;
    324     HKEY InterfacesKey;
    325     HRESULT hr = vboxNetFltWinQueryDriverKey(pComponent, &DriverKey);
    326     if (hr == S_OK)
    327     {
    328         LONG winEr = RegOpenKeyExW(DriverKey, L"Ndi\\Interfaces",
    329                         0, /*__reserved DWORD ulOptions*/
    330                         KEY_READ, /*__in REGSAM samDesired*/
    331                         &InterfacesKey);
    332         if (winEr == ERROR_SUCCESS)
    333         {
    334             DWORD Type = REG_SZ;
    335             WCHAR Value[MAX_PATH];
    336             DWORD cbValue = sizeof(Value);
    337             winEr = RegQueryValueExW(InterfacesKey,
    338                     L"LowerRange", /*__in_opt LPCTSTR lpValueName*/
    339                     0, /*__reserved LPDWORD lpReserved*/
    340                     &Type, /*__out_opt LPDWORD lpType*/
    341                     (LPBYTE)Value, /*__out_opt LPBYTE lpData*/
    342                     &cbValue/*__inout_opt LPDWORD lpcbData*/
    343                     );
    344             if (winEr == ERROR_SUCCESS)
    345             {
    346                 if (wcsstr(Value,L"ethernet") || wcsstr(Value, L"wan"))
     347                if (dwType == REG_SZ)
    347348                {
    348                     *pbShouldBind = true;
    349                 }
    350                 else
    351                 {
    352                     *pbShouldBind = false;
     349                    if (RTUtf16FindAscii(wszValue, "ethernet") >= 0 || RTUtf16FindAscii(wszValue, "wan") >= 0)
     350                        *pfShouldBind = true;
     351                    else
     352                        *pfShouldBind = false;
    353353                }
    354354            }
     
    356356            {
    357357                /* do not set err status to it */
    358                 *pbShouldBind = false;
     358                *pfShouldBind = false;
    359359                NonStandardAssertBreakpoint();
    360360            }
    361361
    362             RegCloseKey(InterfacesKey);
     362            RegCloseKey(hKeyInterfaces);
    363363        }
    364364        else
    365365        {
    366             hr = HRESULT_FROM_WIN32(winEr);
     366            hrc = HRESULT_FROM_WIN32(lrc);
    367367            NonStandardAssertBreakpoint();
    368368        }
    369369
    370         RegCloseKey(DriverKey);
     370        RegCloseKey(hKeyDriver);
    371371    }
    372372    else
    373     {
    374         NonStandardAssertBreakpoint();
    375     }
    376 
    377     return hr;
    378 }
    379 
    380 static HRESULT vboxNetFltWinNotifyShouldBind(IN INetCfgComponent *pComponent, OUT bool *pbShouldBind)
    381 {
    382     DWORD fCharacteristics;
    383     HRESULT hr;
    384 
    385     do
    386     {
    387         /* filter out only physical adapters */
    388         hr = pComponent->GetCharacteristics(&fCharacteristics);
    389         if (hr != S_OK)
    390         {
    391             NonStandardAssertBreakpoint();
    392             break;
    393         }
    394 
    395 
    396         if (fCharacteristics & NCF_HIDDEN)
    397         {
    398             /* we are not binding to hidden adapters */
    399             *pbShouldBind = false;
    400             break;
    401         }
    402 
    403         hr = vboxNetFltWinNotifyCheckMsLoop(pComponent, pbShouldBind);
    404         if (hr == S_OK)
    405         {
    406             /* this is a loopback adapter,
    407              * the pbShouldBind already contains the result */
    408             break;
    409         }
    410         else if (hr != S_FALSE)
    411         {
    412             /* error occurred */
    413             break;
    414         }
    415 
    416         hr = vboxNetFltWinNotifyCheckNetAdp(pComponent, pbShouldBind);
    417         if (hr == S_OK)
    418         {
    419             /* this is a VBoxNetAdp adapter,
    420              * the pbShouldBind already contains the result */
    421             break;
    422         }
    423         else if (hr != S_FALSE)
    424         {
    425             /* error occurred */
    426             break;
    427         }
    428 
    429         /* hr == S_FALSE means this is not a loopback adpater, set it to S_OK */
    430         hr = S_OK;
    431 
    432 //        if (!(fCharacteristics & NCF_PHYSICAL))
    433 //        {
    434 //            /* we are binding to physical adapters only */
    435 //            *pbShouldBind = false;
    436 //            break;
    437 //        }
    438 
    439         hr = vboxNetFltWinNotifyCheckLowerRange(pComponent, pbShouldBind);
    440         if (hr == S_OK)
    441         {
    442             /* the vboxNetFltWinNotifyCheckLowerRange ccucceeded,
    443              * the pbShouldBind already contains the result */
    444             break;
    445         }
    446         /* we are here because of the fail, nothing else to do */
    447     } while (0);
    448 
    449     return hr;
    450 }
    451 
    452 
    453 static HRESULT vboxNetFltWinNotifyShouldBind(IN INetCfgBindingInterface *pIf, OUT bool *pbShouldBind)
    454 {
    455     INetCfgComponent * pAdapterComponent;
    456     HRESULT hr = pIf->GetLowerComponent(&pAdapterComponent);
    457     if (hr == S_OK)
    458     {
    459         hr = vboxNetFltWinNotifyShouldBind(pAdapterComponent, pbShouldBind);
     373        NonStandardAssertBreakpoint();
     374    return hrc;
     375}
     376
     377static HRESULT vboxNetFltWinNotifyShouldBind(IN INetCfgComponent *pComponent, OUT bool *pfShouldBind)
     378{
     379    *pfShouldBind = false;
     380
     381    /* filter out only physical adapters */
     382    DWORD fCharacteristics = 0;
     383    HRESULT hrc = pComponent->GetCharacteristics(&fCharacteristics);
     384    if (hrc != S_OK)
     385    {
     386        NonStandardAssertBreakpoint();
     387        return hrc;
     388    }
     389
     390    /* we are not binding to hidden adapters */
     391    if (fCharacteristics & NCF_HIDDEN)
     392        return S_OK;
     393
     394    hrc = vboxNetFltWinNotifyCheckMsLoop(pComponent, pfShouldBind);
     395    if (   hrc == S_OK /* this is a loopback adapter, the pfShouldBind already contains the result */
     396        || hrc != S_FALSE /* error occurred */)
     397        return hrc;
     398
     399    hrc = vboxNetFltWinNotifyCheckNetAdp(pComponent, pfShouldBind);
     400    if (   hrc == S_OK /* this is a VBoxNetAdp adapter, the pfShouldBind already contains the result */
     401        || hrc != S_FALSE /* error occurred */)
     402        return hrc;
     403
     404    //if (!(fCharacteristics & NCF_PHYSICAL))
     405    //{
     406    //    *pfShouldBind = false; /* we are binding to physical adapters only */
     407    //    return S_OK;
     408    //}
     409
     410    return vboxNetFltWinNotifyCheckLowerRange(pComponent, pfShouldBind);
     411}
     412
     413
     414static HRESULT vboxNetFltWinNotifyShouldBind(IN INetCfgBindingInterface *pIf, OUT bool *pfShouldBind)
     415{
     416    INetCfgComponent *pAdapterComponent = NULL;
     417    HRESULT hrc = pIf->GetLowerComponent(&pAdapterComponent);
     418    if (hrc == S_OK)
     419    {
     420        hrc = vboxNetFltWinNotifyShouldBind(pAdapterComponent, pfShouldBind);
    460421
    461422        pAdapterComponent->Release();
     
    464425    {
    465426        NonStandardAssertBreakpoint();
    466     }
    467 
    468     return hr;
    469 }
    470 
    471 static HRESULT vboxNetFltWinNotifyShouldBind(IN INetCfgBindingPath *pPath, OUT bool *pbDoBind)
    472 {
    473     IEnumNetCfgBindingInterface *pEnumBindingIf;
    474     HRESULT hr = pPath->EnumBindingInterfaces(&pEnumBindingIf);
    475     if (hr == S_OK)
    476     {
    477         hr = pEnumBindingIf->Reset();
    478         if (hr == S_OK)
    479         {
    480             ULONG ulCount;
    481             INetCfgBindingInterface *pBindingIf;
    482             do
     427        *pfShouldBind = false;
     428    }
     429    return hrc;
     430}
     431
     432static HRESULT vboxNetFltWinNotifyShouldBind(IN INetCfgBindingPath *pPath, OUT bool *pfShouldBind)
     433{
     434    *pfShouldBind = false;
     435
     436    IEnumNetCfgBindingInterface *pIEnumBinding = NULL;
     437    HRESULT hrc = pPath->EnumBindingInterfaces(&pIEnumBinding);
     438    if (hrc == S_OK)
     439    {
     440        hrc = pIEnumBinding->Reset();
     441        if (hrc == S_OK)
     442        {
     443            for (;;)
    483444            {
    484                 hr = pEnumBindingIf->Next(1, &pBindingIf, &ulCount);
    485                 if (hr == S_OK)
     445                ULONG                    uCount    = 0;
     446                INetCfgBindingInterface *pIBinding = NULL;
     447                hrc = pIEnumBinding->Next(1, &pIBinding, &uCount);
     448                if (hrc == S_OK)
    486449                {
    487                     hr = vboxNetFltWinNotifyShouldBind(pBindingIf, pbDoBind);
    488 
    489                     pBindingIf->Release();
    490 
    491                     if (hr == S_OK)
    492                     {
    493                         if (!(*pbDoBind))
    494                         {
    495                             break;
    496                         }
    497                     }
    498                     else
    499                     {
    500                         /* break on failure */
     450                    hrc = vboxNetFltWinNotifyShouldBind(pIBinding, pfShouldBind);
     451                    pIBinding->Release();
     452
     453                    if (hrc != S_OK)
     454                        break; /* break on failure. */
     455                    if (!*pfShouldBind)
    501456                        break;
    502                     }
    503457                }
    504                 else if (hr == S_FALSE)
     458                else if (hrc == S_FALSE)
    505459                {
    506460                    /* no more elements */
    507                     hr = S_OK;
     461                    hrc = S_OK;
    508462                    break;
    509463                }
     
    514468                    break;
    515469                }
    516             } while (true);
     470            }
    517471        }
    518472        else
    519         {
    520473            NonStandardAssertBreakpoint();
    521         }
    522 
    523         pEnumBindingIf->Release();
     474
     475        pIEnumBinding->Release();
    524476    }
    525477    else
    526     {
    527         NonStandardAssertBreakpoint();
    528     }
    529 
    530     return hr;
     478        NonStandardAssertBreakpoint();
     479    return hrc;
    531480}
    532481
     
    536485    return VBOXNETFLTNOTIFY_DEBUG_BIND;
    537486#else
    538     bool bShouldBind;
    539     HRESULT hr = vboxNetFltWinNotifyShouldBind(pPath, &bShouldBind) ;
    540     if (hr != S_OK)
    541     {
    542         bShouldBind = VBOXNETFLTNOTIFY_ONFAIL_BINDDEFAULT;
    543     }
    544 
    545     return bShouldBind;
     487    bool fShouldBind;
     488    HRESULT hrc = vboxNetFltWinNotifyShouldBind(pPath, &fShouldBind);
     489    if (hrc != S_OK)
     490        fShouldBind = VBOXNETFLTNOTIFY_ONFAIL_BINDDEFAULT;
     491
     492    return fShouldBind;
    546493#endif
    547494}
     
    571518END_OBJECT_MAP()
    572519
     520
    573521extern "C"
    574522BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/)
     
    576524    if (dwReason == DLL_PROCESS_ATTACH)
    577525    {
     526        g_hModSelf = (HMODULE)hInstance;
     527
    578528        _Module.Init(ObjectMap, hInstance);
    579529        DisableThreadLibraryCalls(hInstance);
     
    586536}
    587537
    588 STDAPI DllCanUnloadNow()
    589 {
    590     return (_Module.GetLockCount() == 0) ? S_OK : S_FALSE;
    591 }
    592 
    593 STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv)
     538STDAPI DllCanUnloadNow(void)
     539{
     540    return _Module.GetLockCount() == 0 ? S_OK : S_FALSE;
     541}
     542
     543STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
    594544{
    595545    return _Module.GetClassObject(rclsid, riid, ppv);
    596546}
     547
    597548
    598549/*
     
    602553 */
    603554
     555#ifdef RT_EXCEPTIONS_ENABLED
    604556/* Someday we may want to log errors. */
    605557class AdHocRegError
     
    608560    AdHocRegError(LSTATUS rc) { RT_NOREF1(rc); };
    609561};
    610 
    611 /* A simple wrapper on Windows registry functions. */
     562#endif
     563
     564/**
     565 * A simple wrapper on Windows registry functions.
     566 */
    612567class AdHocRegKey
    613568{
     
    617572    ~AdHocRegKey() { RegCloseKey(m_hKey); };
    618573
    619     AdHocRegKey *create(LPCWSTR pcwszSubkey, LPCWSTR pcwszDefaultValue = NULL);
    620     void remove(LPCWSTR pcwszSubkey);
    621     void setValue(LPCWSTR pcwszName, LPCWSTR pcwszValue);
     574    AdHocRegKey *create(LPCWSTR pcwszSubkey);
     575    LSTATUS setValue(LPCWSTR pcwszName, LPCWSTR pcwszValue);
    622576    HKEY getKey(void) { return m_hKey; };
    623577private:
     
    625579};
    626580
    627 AdHocRegKey::AdHocRegKey(LPCWSTR pcwszName, HKEY hParent)
     581AdHocRegKey::AdHocRegKey(LPCWSTR pcwszName, HKEY hParent) : m_hKey(NULL)
    628582{
    629583    LSTATUS rc = RegOpenKeyExW(hParent, pcwszName, 0, KEY_ALL_ACCESS, &m_hKey);
    630584    if (rc != ERROR_SUCCESS)
     585#ifdef RT_EXCEPTIONS_ENABLED
    631586        throw AdHocRegError(rc);
    632 }
    633 
    634 void AdHocRegKey::remove(LPCWSTR pcwszSubkey)
    635 {
    636     LSTATUS rc;
    637     WCHAR wszName[256];
    638     DWORD dwName;
    639 
    640     /* Remove all subkeys of subkey first */
    641     AdHocRegKey *subkey = new AdHocRegKey(pcwszSubkey, m_hKey);
    642     for (;;)
    643     {
    644         /* Always ask for the first subkey, because we remove it before calling RegEnumKeyEx again */
    645         dwName = 255;
    646         rc = RegEnumKeyExW(subkey->getKey(), 0, wszName, &dwName, NULL, NULL, NULL, NULL);
    647         if (rc != ERROR_SUCCESS)
    648             break;
    649         subkey->remove(wszName);
    650     }
    651     delete subkey;
    652 
    653     /* Remove the subkey itself */
    654     rc = RegDeleteKeyW(m_hKey, pcwszSubkey);
    655     if (rc != ERROR_SUCCESS)
    656         throw AdHocRegError(rc);
    657 }
    658 
    659 AdHocRegKey *AdHocRegKey::create(LPCWSTR pcwszSubkey, LPCWSTR pcwszDefaultValue)
     587#else
     588        m_hKey = NULL;
     589#endif
     590}
     591
     592AdHocRegKey *AdHocRegKey::create(LPCWSTR pcwszSubkey)
    660593{
    661594    HKEY hSubkey;
     
    664597                                 KEY_ALL_ACCESS, NULL /*pSecAttr*/, &hSubkey, NULL /*pdwDisposition*/);
    665598    if (rc != ERROR_SUCCESS)
     599#ifdef RT_EXCEPTIONS_ENABLED
    666600        throw AdHocRegError(rc);
     601#else
     602        return NULL;
     603#endif
    667604    AdHocRegKey *pSubkey = new AdHocRegKey(hSubkey);
    668     if (pcwszDefaultValue)
    669         pSubkey->setValue(NULL, pcwszDefaultValue);
     605    if (!pSubkey)
     606        RegCloseKey(hSubkey);
    670607    return pSubkey;
    671608}
    672609
    673 void AdHocRegKey::setValue(LPCWSTR pcwszName, LPCWSTR pcwszValue)
     610LSTATUS AdHocRegKey::setValue(LPCWSTR pcwszName, LPCWSTR pcwszValue)
    674611{
    675612    LSTATUS rc = RegSetValueExW(m_hKey, pcwszName, 0, REG_SZ, (const BYTE *)pcwszValue,
    676                                 (DWORD)((wcslen(pcwszValue) + 1) * sizeof(WCHAR)));
     613                                (DWORD)((RTUtf16Len(pcwszValue) + 1) * sizeof(WCHAR)));
     614#ifdef RT_EXCEPTIONS_ENABLED
    677615    if (rc != ERROR_SUCCESS)
    678616        throw AdHocRegError(rc);
    679 }
    680 
    681 /*
     617#endif
     618    return rc;
     619}
     620
     621/**
    682622 * Auxiliary class that facilitates automatic destruction of AdHocRegKey objects
    683623 * allocated in heap. No reference counting here!
     
    687627public:
    688628    AdHocRegKeyPtr(AdHocRegKey *pKey) : m_pKey(pKey) {};
    689     ~AdHocRegKeyPtr() { delete m_pKey; };
    690 
    691     AdHocRegKey *create(LPCWSTR pcwszSubkey, LPCWSTR pcwszDefaultValue = NULL)
    692         { return m_pKey->create(pcwszSubkey, pcwszDefaultValue); };
    693     void remove(LPCWSTR pcwszSubkey)
    694         { return m_pKey->remove(pcwszSubkey); };
    695     void setValue(LPCWSTR pcwszName, LPCWSTR pcwszValue)
    696         { return m_pKey->setValue(pcwszName, pcwszValue); };
     629    ~AdHocRegKeyPtr()
     630    {
     631        if (m_pKey)
     632        {
     633            delete m_pKey;
     634            m_pKey = NULL;
     635        }
     636    }
     637
     638    AdHocRegKey *create(LPCWSTR pcwszSubkey)
     639    { return m_pKey ? m_pKey->create(pcwszSubkey) : NULL; };
     640
     641    LSTATUS setValue(LPCWSTR pcwszName, LPCWSTR pcwszValue)
     642    { return m_pKey ? m_pKey->setValue(pcwszName, pcwszValue) : ERROR_INVALID_STATE; };
     643
    697644private:
    698645    AdHocRegKey *m_pKey;
     
    703650
    704651
    705 STDAPI DllRegisterServer()
    706 {
     652STDAPI DllRegisterServer(void)
     653{
     654    /* Get the path to the DLL we're running inside. */
    707655    WCHAR wszModule[MAX_PATH + 1];
    708     if (GetModuleFileNameW(GetModuleHandleW(L"VBoxNetFltNobj"), wszModule, MAX_PATH) == 0)
     656    UINT  cwcModule = GetModuleFileNameW(g_hModSelf, wszModule, MAX_PATH);
     657    if (cwcModule == 0 || cwcModule > MAX_PATH)
    709658        return SELFREG_E_CLASS;
    710 
    711     try {
     659    wszModule[MAX_PATH] = '\0';
     660
     661    /*
     662     * Create registry keys and values.  When exceptions are disabled, we depend
     663     * on setValue() to propagate fail key creation failures.
     664     */
     665#ifdef RT_EXCEPTIONS_ENABLED
     666    try
     667#endif
     668    {
    712669        AdHocRegKey keyCLSID(L"CLSID");
    713         AdHocRegKeyPtr pkeyNobjClass(keyCLSID.create(L"{f374d1a0-bf08-4bdc-9cb2-c15ddaeef955}",
    714                                                      L"VirtualBox Bridged Networking Driver Notify Object v1.1"));
    715         AdHocRegKeyPtr pkeyNobjSrv(pkeyNobjClass.create(L"InProcServer32", wszModule));
    716         pkeyNobjSrv.setValue(L"ThreadingModel", L"Both");
    717     }
    718     catch (AdHocRegError)
    719     {
    720         return SELFREG_E_CLASS;
    721     }
    722 
    723     try {
     670        AdHocRegKeyPtr pkeyNobjClass(keyCLSID.create(L"{f374d1a0-bf08-4bdc-9cb2-c15ddaeef955}"));
     671        LSTATUS lrc = pkeyNobjClass.setValue(NULL, L"VirtualBox Bridged Networking Driver Notify Object v1.1");
     672        if (lrc != ERROR_SUCCESS)
     673            return SELFREG_E_CLASS;
     674
     675        AdHocRegKeyPtr pkeyNobjSrv(pkeyNobjClass.create(L"InProcServer32"));
     676        lrc = pkeyNobjSrv.setValue(NULL, wszModule);
     677        if (lrc != ERROR_SUCCESS)
     678            return SELFREG_E_CLASS;
     679        lrc = pkeyNobjSrv.setValue(L"ThreadingModel", L"Both");
     680        if (lrc != ERROR_SUCCESS)
     681            return SELFREG_E_CLASS;
     682    }
     683#ifdef RT_EXCEPTIONS_ENABLED
     684    catch (AdHocRegError) { return SELFREG_E_CLASS; }
     685#endif
     686
     687#ifdef RT_EXCEPTIONS_ENABLED
     688    try
     689#endif
     690    {
    724691        AdHocRegKey keyTypeLib(L"TypeLib");
    725         AdHocRegKeyPtr pkeyNobjLib(keyTypeLib.create(L"{2A0C94D1-40E1-439C-8FE8-24107CAB0840}\\1.1",
    726                                                      L"VirtualBox Bridged Networking Driver Notify Object v1.1 Type Library"));
    727         AdHocRegKeyPtr pkeyNobjLib0(pkeyNobjLib.create(L"0\\win64", wszModule));
    728         AdHocRegKeyPtr pkeyNobjLibFlags(pkeyNobjLib.create(L"FLAGS", L"0"));
     692        AdHocRegKeyPtr pkeyNobjLib(keyTypeLib.create(L"{2A0C94D1-40E1-439C-8FE8-24107CAB0840}\\1.1"));
     693        LSTATUS lrc = pkeyNobjLib.setValue(NULL, L"VirtualBox Bridged Networking Driver Notify Object v1.1 Type Library");
     694        if (lrc != ERROR_SUCCESS)
     695            return SELFREG_E_TYPELIB;
     696
     697        AdHocRegKeyPtr pkeyNobjLib0(pkeyNobjLib.create(L"0\\win64"));
     698        lrc = pkeyNobjLib0.setValue(NULL, wszModule);
     699        if (lrc != ERROR_SUCCESS)
     700            return SELFREG_E_TYPELIB;
     701        AdHocRegKeyPtr pkeyNobjLibFlags(pkeyNobjLib.create(L"FLAGS"));
     702        lrc = pkeyNobjLibFlags.setValue(NULL, L"0");
     703        if (lrc != ERROR_SUCCESS)
     704            return SELFREG_E_TYPELIB;
     705
    729706        if (GetSystemDirectoryW(wszModule, MAX_PATH) == 0)
    730707            return SELFREG_E_TYPELIB;
    731         AdHocRegKeyPtr pkeyNobjLibHelpDir(pkeyNobjLib.create(L"HELPDIR", wszModule));
    732     }
    733     catch (AdHocRegError)
    734     {
    735         return SELFREG_E_CLASS;
    736     }
     708        AdHocRegKeyPtr pkeyNobjLibHelpDir(pkeyNobjLib.create(L"HELPDIR"));
     709        lrc = pkeyNobjLibHelpDir.setValue(NULL, wszModule);
     710        if (lrc != ERROR_SUCCESS)
     711            return SELFREG_E_TYPELIB;
     712    }
     713#ifdef RT_EXCEPTIONS_ENABLED
     714    catch (AdHocRegError) { return SELFREG_E_TYPELIB; }
     715#endif
    737716
    738717    return S_OK;
    739718}
    740719
    741 STDAPI DllUnregisterServer()
    742 {
    743     try {
    744         AdHocRegKey keyTypeLib(L"TypeLib");
    745         keyTypeLib.remove(L"{2A0C94D1-40E1-439C-8FE8-24107CAB0840}");
    746     }
    747     catch (AdHocRegError) { return SELFREG_E_TYPELIB; }
    748 
    749     try {
    750         AdHocRegKey keyCLSID(L"CLSID");
    751         keyCLSID.remove(L"{f374d1a0-bf08-4bdc-9cb2-c15ddaeef955}");
    752     }
    753     catch (AdHocRegError) { return SELFREG_E_CLASS; }
     720
     721STDAPI DllUnregisterServer(void)
     722{
     723    static struct { HKEY hKeyRoot; wchar_t const *pwszParentKey; wchar_t const *pwszKeyToDelete; HRESULT hrcFail; }
     724    s_aKeys[] =
     725    {
     726        { HKEY_CLASSES_ROOT, L"TypeLib", L"{2A0C94D1-40E1-439C-8FE8-24107CAB0840}", SELFREG_E_TYPELIB },
     727        { HKEY_CLASSES_ROOT, L"CLSID",   L"{f374d1a0-bf08-4bdc-9cb2-c15ddaeef955}", SELFREG_E_CLASS },
     728    };
     729
     730    HRESULT hrc = S_OK;
     731    for (size_t i = 0; i < RT_ELEMENTS(s_aKeys); i++)
     732    {
     733        HKEY hKey = NULL;
     734        LSTATUS lrc = RegOpenKeyExW(s_aKeys[i].hKeyRoot, s_aKeys[i].pwszParentKey, 0, KEY_ALL_ACCESS, &hKey);
     735        if (lrc == ERROR_SUCCESS)
     736        {
     737            lrc = RegDeleteTreeW(hKey, s_aKeys[i].pwszKeyToDelete); /* Vista and later */
     738            RegCloseKey(hKey);
     739        }
     740
     741        if (lrc != ERROR_SUCCESS && lrc != ERROR_FILE_NOT_FOUND && hrc == S_OK)
     742            hrc = s_aKeys[i].hrcFail;
     743    }
    754744
    755745    return S_OK;
    756746}
     747
  • trunk/src/VBox/HostDrivers/VBoxNetFlt/win/nobj/VBoxNetFltNobj.h

    r96407 r96572  
    5353 * Needed to make our driver bind to "real" host adapters only
    5454 */
    55 class ATL_NO_VTABLE VBoxNetFltNobj :
    56     public ATL::CComObjectRootEx<ATL::CComMultiThreadModel>,
    57     public ATL::CComCoClass<VBoxNetFltNobj, &CLSID_VBoxNetFltNobj>,
    58     public INetCfgComponentControl,
    59     public INetCfgComponentNotifyBinding
     55class ATL_NO_VTABLE VBoxNetFltNobj
     56    : public ATL::CComObjectRootEx<ATL::CComMultiThreadModel>
     57    , public ATL::CComCoClass<VBoxNetFltNobj, &CLSID_VBoxNetFltNobj>
     58    , public INetCfgComponentControl
     59    , public INetCfgComponentNotifyBinding
    6060{
    6161public:
  • trunk/src/VBox/HostDrivers/VBoxNetFlt/win/tools/VBoxNetAdpInstall.cpp

    r96407 r96572  
    4141#include <VBox/VBoxNetCfg-win.h>
    4242#include <VBox/VBoxDrvCfg-win.h>
    43 #include <stdio.h>
    4443#include <devguid.h>
     44
     45#include <iprt/initterm.h>
     46#include <iprt/message.h>
     47#include <iprt/process.h>
     48#include <iprt/stream.h>
    4549
    4650
     
    6064static DECLCALLBACK(void) winNetCfgLogger(const char *pszString)
    6165{
    62     printf("%s\n", pszString);
     66    RTMsgInfo("%s", pszString);
    6367}
    6468
     
    109113static int VBoxNetAdpInstall(void)
    110114{
    111     VBoxNetCfgWinSetLogging(winNetCfgLogger);
    112 
    113     HRESULT hr = CoInitialize(NULL);
    114     if (SUCCEEDED(hr))
    115     {
    116         wprintf(L"adding host-only interface..\n");
    117 
     115    RTMsgInfo("Adding host-only interface...");
     116    VBoxNetCfgWinSetLogging(winNetCfgLogger);
     117
     118    HRESULT hr = CoInitialize(NULL);
     119    if (SUCCEEDED(hr))
     120    {
    118121        WCHAR wszInfFile[MAX_PATH];
    119122        DWORD cwcInfFile = MyGetfullPathNameW(VBOX_NETADP_INF, RT_ELEMENTS(wszInfFile), wszInfFile);
     
    129132
    130133                if (hr == S_OK)
    131                     wprintf(L"installed successfully\n");
     134                    RTMsgInfo("Installed successfully!");
    132135                else
    133                     wprintf(L"error installing VBoxNetAdp (%#lx)\n", hr);
     136                    RTMsgError("failed to install VBoxNetAdp: %Rhrc", hr);
    134137
    135138                VBoxNetCfgWinReleaseINetCfg(pnc, TRUE);
    136139            }
    137140            else
    138                 wprintf(L"VBoxNetCfgWinQueryINetCfg failed: hr=%#lx\n", hr);
     141                RTMsgError("VBoxNetCfgWinQueryINetCfg failed: %Rhrc", hr);
    139142            /*
    140143            hr = VBoxDrvCfgInfInstall(MpInf);
     
    171174        {
    172175            DWORD dwErr = GetLastError();
    173             wprintf(L"GetFullPathNameW failed: winEr = %lu\n", dwErr);
     176            RTMsgError("MyGetfullPathNameW failed: %Rwc", dwErr);
    174177            hr = HRESULT_FROM_WIN32(dwErr);
    175178        }
     
    177180    }
    178181    else
    179         wprintf(L"Error initializing COM (%#lx)\n", hr);
     182        RTMsgError("Failed initializing COM: %Rhrc", hr);
    180183
    181184    VBoxNetCfgWinSetLogging(NULL);
     
    186189static int VBoxNetAdpUninstall(void)
    187190{
    188     VBoxNetCfgWinSetLogging(winNetCfgLogger);
    189 
    190     printf("uninstalling all host-only interfaces..\n");
     191    RTMsgInfo("Uninstalling all host-only interfaces...");
     192    VBoxNetCfgWinSetLogging(winNetCfgLogger);
    191193
    192194    HRESULT hr = CoInitialize(NULL);
     
    198200            hr = VBoxDrvCfgInfUninstallAllSetupDi(&GUID_DEVCLASS_NET, L"Net", VBOX_NETADP_HWID, 0/* could be SUOI_FORCEDELETE */);
    199201            if (SUCCEEDED(hr))
    200                 printf("uninstallation successful\n");
     202                RTMsgInfo("Uninstallation successful!");
    201203            else
    202                 printf("uninstalled successfully, but failed to remove infs\n");
    203         }
    204         else
    205             printf("uninstall failed, hr=%#lx\n", hr);
    206         CoUninitialize();
    207     }
    208     else
    209         printf("Error initializing COM (%#lx)\n", hr);
     204                RTMsgWarning("uninstalled successfully, but failed to remove infs (%Rhrc)\n", hr);
     205        }
     206        else
     207            RTMsgError("uninstall failed: %Rhrc", hr);
     208        CoUninitialize();
     209    }
     210    else
     211        RTMsgError("Failed initializing COM: %Rhrc", hr);
    210212
    211213    VBoxNetCfgWinSetLogging(NULL);
     
    216218static int VBoxNetAdpUpdate(void)
    217219{
    218     VBoxNetCfgWinSetLogging(winNetCfgLogger);
    219 
    220     printf("uninstalling all host-only interfaces..\n");
     220    RTMsgInfo("Uninstalling all host-only interfaces...");
     221    VBoxNetCfgWinSetLogging(winNetCfgLogger);
    221222
    222223    HRESULT hr = CoInitialize(NULL);
     
    235236        {
    236237            if (fRebootRequired)
    237                 printf("!!REBOOT REQUIRED!!\n");
    238             printf("updated successfully\n");
    239         }
    240         else
    241             printf("update failed, hr=%#lx\n", hr);
    242 
    243         CoUninitialize();
    244     }
    245     else
    246         printf("Error initializing COM (%#lx)\n", hr);
     238                RTMsgWarning("!!REBOOT REQUIRED!!");
     239            RTMsgInfo("Updated successfully!");
     240        }
     241        else
     242            RTMsgError("update failed: %Rhrc", hr);
     243
     244        CoUninitialize();
     245    }
     246    else
     247        RTMsgError("Failed initializing COM: %Rhrc", hr);
    247248
    248249    VBoxNetCfgWinSetLogging(NULL);
     
    253254static int VBoxNetAdpDisable(void)
    254255{
    255     VBoxNetCfgWinSetLogging(winNetCfgLogger);
    256 
    257     printf("disabling all host-only interfaces..\n");
     256    RTMsgInfo("Disabling all host-only interfaces...");
     257    VBoxNetCfgWinSetLogging(winNetCfgLogger);
    258258
    259259    HRESULT hr = CoInitialize(NULL);
     
    262262        hr = VBoxNetCfgWinPropChangeAllNetDevicesOfId(VBOX_NETADP_HWID, VBOXNECTFGWINPROPCHANGE_TYPE_DISABLE);
    263263        if (SUCCEEDED(hr))
    264             printf("disabling successful\n");
    265         else
    266             printf("disable failed, hr=%#lx\n", hr);
    267 
    268         CoUninitialize();
    269     }
    270     else
    271         printf("Error initializing COM (%#lx)\n", hr);
     264            RTMsgInfo("Disabling successful");
     265        else
     266            RTMsgError("disable failed: %Rhrc", hr);
     267
     268        CoUninitialize();
     269    }
     270    else
     271        RTMsgError("Failed initializing COM: %Rhrc", hr);
    272272
    273273    VBoxNetCfgWinSetLogging(NULL);
     
    278278static int VBoxNetAdpEnable(void)
    279279{
    280     VBoxNetCfgWinSetLogging(winNetCfgLogger);
    281 
    282     printf("enabling all host-only interfaces..\n");
     280    RTMsgInfo("Enabling all host-only interfaces...");
     281    VBoxNetCfgWinSetLogging(winNetCfgLogger);
    283282
    284283    HRESULT hr = CoInitialize(NULL);
     
    287286        hr = VBoxNetCfgWinPropChangeAllNetDevicesOfId(VBOX_NETADP_HWID, VBOXNECTFGWINPROPCHANGE_TYPE_ENABLE);
    288287        if (SUCCEEDED(hr))
    289             printf("enabling successful\n");
    290         else
    291             printf("enabling failed, hr=%#lx\n", hr);
    292 
    293         CoUninitialize();
    294     }
    295     else
    296         printf("Error initializing COM (%#lx)\n", hr);
     288            RTMsgInfo("Enabling successful!");
     289        else
     290            RTMsgError("enabling failed: %hrc", hr);
     291
     292        CoUninitialize();
     293    }
     294    else
     295        RTMsgError("Failed initializing COM: %Rhrc", hr);
    297296
    298297    VBoxNetCfgWinSetLogging(NULL);
     
    303302static void printUsage(void)
    304303{
    305     printf("host-only network adapter configuration tool\n"
    306             "  Usage: VBoxNetAdpInstall [cmd]\n"
    307             "    cmd can be one of the following values:\n"
    308             "       i  - install a new host-only interface (default command)\n"
    309             "       u  - uninstall all host-only interfaces\n"
    310             "       a  - update the host-only driver\n"
    311             "       d  - disable all host-only interfaces\n"
    312             "       e  - enable all host-only interfaces\n"
    313             "       h  - print this message\n");
     304    RTPrintf("host-only network adapter configuration tool\n"
     305             "  Usage: %s [cmd]\n"
     306             "    cmd can be one of the following values:\n"
     307             "       i  - install a new host-only interface (default command)\n"
     308             "       u  - uninstall all host-only interfaces\n"
     309             "       a  - update the host-only driver\n"
     310             "       d  - disable all host-only interfaces\n"
     311             "       e  - enable all host-only interfaces\n"
     312             "       h  - print this message\n",
     313             RTProcShortName());
    314314}
    315315
    316316int __cdecl main(int argc, char **argv)
    317317{
     318    RTR3InitExe(argc, &argv, 0);
     319
    318320    if (argc < 2)
    319321        return VBoxNetAdpInstall();
  • trunk/src/VBox/HostDrivers/VBoxNetFlt/win/tools/VBoxNetAdpUninstall.cpp

    r96407 r96572  
    3535 */
    3636
     37
     38/*********************************************************************************************************************************
     39*   Header Files                                                                                                                 *
     40*********************************************************************************************************************************/
    3741#include <VBox/VBoxNetCfg-win.h>
    3842#include <VBox/VBoxDrvCfg-win.h>
    39 #include <stdio.h>
    4043
    4144#include <devguid.h>
    4245
     46#include <iprt/initterm.h>
     47#include <iprt/message.h>
     48
     49
     50/*********************************************************************************************************************************
     51*   Defined Constants And Macros                                                                                                 *
     52*********************************************************************************************************************************/
    4353#ifdef NDIS60
    4454# define VBOX_NETADP_HWID L"sun_VBoxNetAdp6"
     
    4757#endif
    4858
     59
    4960static DECLCALLBACK(void) winNetCfgLogger(const char *pszString)
    5061{
    51     printf("%s", pszString);
     62    RTMsgInfo("%s", pszString);
    5263}
    5364
    5465static int VBoxNetAdpUninstall(void)
    5566{
     67    RTMsgInfo("Uninstalling all Host-Only interfaces ...");
     68
    5669    int rcExit = RTEXITCODE_FAILURE;
    5770    VBoxNetCfgWinSetLogging(winNetCfgLogger);
    58 
    59     printf("uninstalling all Host-Only interfaces..\n");
    6071
    6172    HRESULT hr = CoInitialize(NULL);
     
    6778            hr = VBoxDrvCfgInfUninstallAllSetupDi(&GUID_DEVCLASS_NET, L"Net", VBOX_NETADP_HWID, 0/* could be SUOI_FORCEDELETE */);
    6879            if (hr == S_OK)
    69                 printf("uninstalled successfully\n");
     80                RTMsgInfo("Uninstalled successfully!");
    7081            else
    71                 printf("uninstalled successfully, but failed to remove infs\n");
     82                RTMsgError("uninstalled successfully, but failed to remove infs (%Rhrc)\n", hr);
    7283            rcExit = RTEXITCODE_SUCCESS;
    7384        }
    7485        else
    75             printf("uninstall failed, hr=%#lx\n", hr);
     86            RTMsgError("uninstall failed: %Rhrc", hr);
    7687
    7788        CoUninitialize();
    7889    }
    7990    else
    80         wprintf(L"Error initializing COM (%#lx)\n", hr);
     91        RTMsgError("Failed initializing COM: %Rhrc", hr);
    8192
    8293    VBoxNetCfgWinSetLogging(NULL);
     
    8798int __cdecl main(int argc, char **argv)
    8899{
    89     RT_NOREF2(argc, argv);
     100    RTR3InitExeNoArguments(0);
     101    if (argc != 1)
     102        return RTMsgErrorExit(RTEXITCODE_SYNTAX, "This utility takes no arguments\n");
     103    NOREF(argv);
     104
    90105    return VBoxNetAdpUninstall();
    91106}
     107
  • trunk/src/VBox/HostDrivers/VBoxNetFlt/win/tools/VBoxNetFltInstall.cpp

    r96407 r96572  
    3535 */
    3636
     37
     38/*********************************************************************************************************************************
     39*   Header Files                                                                                                                 *
     40*********************************************************************************************************************************/
    3741#include <VBox/VBoxNetCfg-win.h>
    3842#include <devguid.h>
    3943#include <stdio.h>
    4044
     45#include <iprt/initterm.h>
     46#include <iprt/message.h>
     47
     48
     49/*********************************************************************************************************************************
     50*   Header Files                                                                                                                 *
     51*********************************************************************************************************************************/
    4152#define NETFLT_ID L"sun_VBoxNetFlt"
    4253#define VBOX_NETCFG_APP_NAME L"NetFltInstall"
     
    181192int __cdecl main(int argc, char **argv)
    182193{
    183     RT_NOREF2(argc, argv);
     194    RTR3InitExeNoArguments(0);
     195    if (argc != 1)
     196        return RTMsgErrorExit(RTEXITCODE_SYNTAX, "This utility takes no arguments\n");
     197    NOREF(argv);
     198
    184199    return VBoxNetFltInstall();
    185200}
     201
  • trunk/src/VBox/HostDrivers/VBoxNetFlt/win/tools/VBoxNetFltUninstall.cpp

    r96407 r96572  
    3535 */
    3636
     37
     38/*********************************************************************************************************************************
     39*   Header Files                                                                                                                 *
     40*********************************************************************************************************************************/
    3741#include <VBox/VBoxNetCfg-win.h>
    3842#include <stdio.h>
    3943
     44#include <iprt/initterm.h>
     45#include <iprt/message.h>
     46
     47
     48/*********************************************************************************************************************************
     49*   Defined Constants And Macros                                                                                                 *
     50*********************************************************************************************************************************/
    4051#define NETFLT_ID L"sun_VBoxNetFlt"
    4152#define VBOX_NETCFG_APP_NAME L"NetFltUninstall"
     
    4354#define VBOX_NETFLT_MP_INF L".\\VBoxNetFltM.inf"
    4455#define VBOX_NETFLT_RETRIES 10
     56
    4557
    4658static DECLCALLBACK(void) winNetCfgLogger(const char *pszString)
     
    112124int __cdecl main(int argc, char **argv)
    113125{
    114     RT_NOREF2(argc, argv);
     126    RTR3InitExeNoArguments(0);
     127    if (argc != 1)
     128        return RTMsgErrorExit(RTEXITCODE_SYNTAX, "This utility takes no arguments\n");
     129    NOREF(argv);
     130
    115131    return VBoxNetFltUninstall();
    116132}
     133
  • trunk/src/VBox/HostDrivers/VBoxNetFlt/win/tools/VBoxNetLwfInstall.cpp

    r96407 r96572  
    3535 */
    3636
     37
     38/*********************************************************************************************************************************
     39*   Header Files                                                                                                                 *
     40*********************************************************************************************************************************/
    3741#include <VBox/VBoxNetCfg-win.h>
    3842#include <devguid.h>
    39 #include <stdio.h>
    4043
     44#include <iprt/initterm.h>
     45#include <iprt/message.h>
     46#include <iprt/utf16.h>
     47
     48
     49/*********************************************************************************************************************************
     50*   Defined Constants And Macros                                                                                                 *
     51*********************************************************************************************************************************/
    4152#define VBOX_NETCFG_APP_NAME L"NetLwfInstall"
    4253#define VBOX_NETLWF_INF L".\\VBoxNetLwf.inf"
     
    4657static DECLCALLBACK(void) winNetCfgLogger(const char *pszString)
    4758{
    48     printf("%s", pszString);
     59    RTMsgInfo("%s", pszString);
    4960}
    5061
     
    116127                    if (hr == S_OK)
    117128                    {
    118                         wprintf(L"installed successfully\n");
     129                        RTMsgInfo("Installed successfully!");
    119130                        rcExit = RTEXITCODE_SUCCESS;
    120131                    }
    121132                    else
    122                         wprintf(L"error installing VBoxNetLwf (%#lx)\n", hr);
     133                        RTMsgError("Failed installing VBoxNetLwf: %Rhrc", hr);
    123134                }
    124135                else
    125136                {
    126137                    hr = HRESULT_FROM_WIN32(GetLastError());
    127                     wprintf(L"error getting full inf path for VBoxNetLwf.inf (%#lx)\n", hr);
     138                    RTMsgError("Failed getting full inf path for VBoxNetLwf.inf: %Rhrc", hr);
    128139                }
    129140
     
    134145            if (hr == NETCFG_E_NO_WRITE_LOCK && pwszLockedBy)
    135146            {
    136                 if (i < VBOX_NETLWF_RETRIES && !wcscmp(pwszLockedBy, L"6to4svc.dll"))
     147                if (i < VBOX_NETLWF_RETRIES && RTUtf16ICmpAscii(pwszLockedBy, "6to4svc.dll") == 0)
    137148                {
    138                     wprintf(L"6to4svc.dll is holding the lock, retrying %d out of %d\n", i + 1, VBOX_NETLWF_RETRIES);
     149                    RTMsgInfo("6to4svc.dll is holding the lock - retrying %d out of %d\n", i + 1, VBOX_NETLWF_RETRIES);
    139150                    CoTaskMemFree(pwszLockedBy);
    140151                }
    141152                else
    142153                {
    143                     wprintf(L"Error: write lock is owned by another application (%s), close the application and retry installing\n",
    144                             pwszLockedBy);
     154                    RTMsgError("write lock is owned by another application (%ls), close the application and retry installing",
     155                               pwszLockedBy);
    145156                    CoTaskMemFree(pwszLockedBy);
    146157                    break;
     
    149160            else
    150161            {
    151                 wprintf(L"Error getting the INetCfg interface (%#lx)\n", hr);
     162                RTMsgError("Failed getting the INetCfg interface: %Rhrc", hr);
    152163                break;
    153164            }
     
    157168    }
    158169    else
    159         wprintf(L"Error initializing COM (%#lx)\n", hr);
     170        RTMsgError("Failed initializing COM: %Rhrc", hr);
    160171
    161172    VBoxNetCfgWinSetLogging(NULL);
     
    166177int __cdecl main(int argc, char **argv)
    167178{
    168     RT_NOREF2(argc, argv);
     179    RTR3InitExeNoArguments(0);
     180    if (argc != 1)
     181        return RTMsgErrorExit(RTEXITCODE_SYNTAX, "This utility takes no arguments\n");
     182    NOREF(argv);
     183
    169184    return VBoxNetLwfInstall();
    170185}
     186
  • trunk/src/VBox/HostDrivers/VBoxNetFlt/win/tools/VBoxNetLwfUninstall.cpp

    r96407 r96572  
    3535 */
    3636
     37
     38/*********************************************************************************************************************************
     39*   Header Files                                                                                                                 *
     40*********************************************************************************************************************************/
    3741#include <VBox/VBoxNetCfg-win.h>
    38 #include <stdio.h>
    3942
     43#include <iprt/initterm.h>
     44#include <iprt/message.h>
     45#include <iprt/utf16.h>
     46
     47
     48/*********************************************************************************************************************************
     49*   Defined Constants And Macros                                                                                                 *
     50*********************************************************************************************************************************/
    4051#define VBOX_NETCFG_APP_NAME L"NetLwfUninstall"
    4152#define VBOX_NETLWF_RETRIES 10
    4253
     54
    4355static DECLCALLBACK(void) winNetCfgLogger(const char *pszString)
    4456{
    45     printf("%s", pszString);
     57    RTMsgInfo("%s", pszString);
    4658}
    4759
    4860static int VBoxNetLwfUninstall()
    4961{
    50     INetCfg *pnc;
    5162    int rcExit = RTEXITCODE_FAILURE;
    5263
     
    5970        {
    6071            LPWSTR pwszLockedBy = NULL;
     72            INetCfg *pnc = NULL;
    6173            hr = VBoxNetCfgWinQueryINetCfg(&pnc, TRUE, VBOX_NETCFG_APP_NAME, 10000, &pwszLockedBy);
    6274            if (hr == S_OK)
     
    6577                if (hr == S_OK)
    6678                {
    67                     wprintf(L"uninstalled successfully\n");
     79                    RTMsgInfo("uninstalled successfully!");
    6880                    rcExit = RTEXITCODE_SUCCESS;
    6981                }
    7082                else
    71                     wprintf(L"error uninstalling VBoxNetLwf (%#lx)\n", hr);
     83                    RTMsgError("error uninstalling VBoxNetLwf: %Rhrc");
    7284
    7385                VBoxNetCfgWinReleaseINetCfg(pnc, TRUE);
     
    7789            if (hr == NETCFG_E_NO_WRITE_LOCK && pwszLockedBy)
    7890            {
    79                 if (i < VBOX_NETLWF_RETRIES && !wcscmp(pwszLockedBy, L"6to4svc.dll"))
     91                if (i < VBOX_NETLWF_RETRIES && RTUtf16ICmpAscii(pwszLockedBy, "6to4svc.dll") == 0)
    8092                {
    81                     wprintf(L"6to4svc.dll is holding the lock, retrying %d out of %d\n", i + 1, VBOX_NETLWF_RETRIES);
     93                    RTMsgInfo("6to4svc.dll is holding the lock - retry %d out of %d ...", i + 1, VBOX_NETLWF_RETRIES);
    8294                    CoTaskMemFree(pwszLockedBy);
    8395                }
    8496                else
    8597                {
    86                     wprintf(L"Error: write lock is owned by another application (%s), close the application and retry uninstalling\n",
    87                              pwszLockedBy);
     98                    RTMsgError("Write lock is owned by another application (%ls), close the application and retry uninstalling",
     99                               pwszLockedBy);
    88100                    CoTaskMemFree(pwszLockedBy);
    89101                    break;
     
    92104            else
    93105            {
    94                 wprintf(L"Error getting the INetCfg interface (%#lx)\n", hr);
     106                RTMsgError("Failed getting the INetCfg interface: %Rhrc", hr);
    95107                break;
    96108            }
     
    100112    }
    101113    else
    102         wprintf(L"Error initializing COM (%#lx)\n", hr);
     114        RTMsgError("Failed initializing COM: %Rhrc", hr);
    103115
    104116    VBoxNetCfgWinSetLogging(NULL);
     
    109121int __cdecl main(int argc, char **argv)
    110122{
    111     RT_NOREF2(argc, argv);
     123    RTR3InitExeNoArguments(0);
     124    if (argc != 1)
     125        return RTMsgErrorExit(RTEXITCODE_SYNTAX, "This utility takes no arguments\n");
     126    NOREF(argv);
     127
    112128    return VBoxNetLwfUninstall();
    113129}
     130
  • trunk/src/VBox/HostDrivers/VBoxUSB/win/Install/USBInstall.cpp

    r96407 r96572  
    7575
    7676
    77 static DECLCALLBACK(void) vboxUsbLog(VBOXDRVCFG_LOG_SEVERITY enmSeverity, char *pszMsg, void *pvContext)
     77static DECLCALLBACK(void) vboxUsbLog(VBOXDRVCFG_LOG_SEVERITY_T enmSeverity, char *pszMsg, void *pvContext)
    7878{
    7979    RT_NOREF1(pvContext);
     
    8484            break;
    8585        case VBOXDRVCFG_LOG_SEVERITY_REL:
    86             RTPrintf("%s", pszMsg);
     86            RTMsgInfo("%s", pszMsg);
    8787            break;
    8888        default:
     
    106106        return RTMsgInitFailure(rc);
    107107
     108    RTMsgInfo("USB installation");
     109
    108110    VBoxDrvCfgLoggerSet(vboxUsbLog, NULL);
    109111    VBoxDrvCfgPanicSet(vboxUsbPanic, NULL);
    110 
    111     RTPrintf("USB installation\n");
    112112
    113113    rc = usblibOsCreateService();
     
    130130            HRESULT hr = VBoxDrvCfgInfInstall(pwszInfFile);
    131131            if (hr == S_OK)
    132                 RTPrintf("Installation successful.\n");
     132                RTMsgInfo("Installation successful!");
    133133            else
    134                 rc = -1;
     134            {
     135                RTMsgError("Installation failed: %Rhrc", hr);
     136                rc = VERR_GENERAL_FAILURE;
     137            }
    135138
    136139            RTUtf16Free(pwszInfFile);
     
    139142            RTMsgError("Failed to construct INF path: %Rrc", rc);
    140143    }
     144    else
     145        RTMsgError("Service creation failed: %Rrc", rc);
    141146
    142147    return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
  • trunk/src/VBox/HostDrivers/VBoxUSB/win/Install/USBUninstall.cpp

    r96407 r96572  
    4545#include <iprt/assert.h>
    4646#include <iprt/errcore.h>
     47#include <iprt/initterm.h>
     48#include <iprt/message.h>
    4749#include <iprt/param.h>
    4850#include <iprt/path.h>
    4951#include <iprt/string.h>
    50 #include <iprt/errcore.h>
    5152#include <VBox/VBoxDrvCfg-win.h>
    52 #include <stdio.h>
    53 
    54 
    55 int usblibOsStopService(void);
    56 int usblibOsDeleteService(void);
    57 
    58 static DECLCALLBACK(void) vboxUsbLog(VBOXDRVCFG_LOG_SEVERITY enmSeverity, char *pszMsg, void *pvContext)
    59 {
    60     RT_NOREF1(pvContext);
    61     switch (enmSeverity)
    62     {
    63         case VBOXDRVCFG_LOG_SEVERITY_FLOW:
    64         case VBOXDRVCFG_LOG_SEVERITY_REGULAR:
    65             break;
    66         case VBOXDRVCFG_LOG_SEVERITY_REL:
    67             printf("%s", pszMsg);
    68             break;
    69         default:
    70             break;
    71     }
    72 }
    73 
    74 static DECLCALLBACK(void) vboxUsbPanic(void *pvPanic)
    75 {
    76     RT_NOREF1(pvPanic);
    77 #ifndef DEBUG_bird
    78     AssertFailed();
    79 #endif
    80 }
    81 
    82 
    83 int __cdecl main(int argc, char **argv)
    84 {
    85     RT_NOREF2(argc, argv);
    86     printf("USB uninstallation\n");
    87 
    88     VBoxDrvCfgLoggerSet(vboxUsbLog, NULL);
    89     VBoxDrvCfgPanicSet(vboxUsbPanic, NULL);
    90 
    91     usblibOsStopService();
    92     usblibOsDeleteService();
    93 
    94     HRESULT hr = VBoxDrvCfgInfUninstallAllF(L"USB", L"USB\\VID_80EE&PID_CAFE", SUOI_FORCEDELETE);
    95     if (hr != S_OK)
    96     {
    97         printf("SetupUninstallOEMInf failed with hr=0x%lx\n", hr);
    98         return 1;
    99     }
    100 
    101     printf("USB uninstallation succeeded!\n");
    102 
    103     return 0;
    104 }
    105 
     53
     54
     55/*********************************************************************************************************************************
     56*   Defined Constants And Macros                                                                                                 *
     57*********************************************************************************************************************************/
    10658/** The support service name. */
    10759#define SERVICE_NAME    "VBoxUSBMon"
     
    11365#define DEVICE_NAME_DOS  L"\\DosDevices\\VBoxUSBMon"
    11466
     67
     68/*********************************************************************************************************************************
     69*   Internal Functions                                                                                                           *
     70*********************************************************************************************************************************/
     71static int usblibOsStopService(void);
     72static int usblibOsDeleteService(void);
     73
     74
     75static DECLCALLBACK(void) vboxUsbLog(VBOXDRVCFG_LOG_SEVERITY_T enmSeverity, char *pszMsg, void *pvContext)
     76{
     77    RT_NOREF1(pvContext);
     78    switch (enmSeverity)
     79    {
     80        case VBOXDRVCFG_LOG_SEVERITY_FLOW:
     81        case VBOXDRVCFG_LOG_SEVERITY_REGULAR:
     82            break;
     83        case VBOXDRVCFG_LOG_SEVERITY_REL:
     84            RTMsgInfo("%s", pszMsg);
     85            break;
     86        default:
     87            break;
     88    }
     89}
     90
     91static DECLCALLBACK(void) vboxUsbPanic(void *pvPanic)
     92{
     93    RT_NOREF1(pvPanic);
     94#ifndef DEBUG_bird
     95    AssertFailed();
     96#endif
     97}
     98
     99
     100int __cdecl main(int argc, char **argv)
     101{
     102    RTR3InitExeNoArguments(0);
     103    if (argc != 1)
     104        return RTMsgErrorExit(RTEXITCODE_SYNTAX, "This utility takes no arguments\n");
     105    NOREF(argv);
     106    RTMsgInfo("USB uninstallation\n");
     107
     108    VBoxDrvCfgLoggerSet(vboxUsbLog, NULL);
     109    VBoxDrvCfgPanicSet(vboxUsbPanic, NULL);
     110
     111    usblibOsStopService();
     112    usblibOsDeleteService();
     113
     114    HRESULT hr = VBoxDrvCfgInfUninstallAllF(L"USB", L"USB\\VID_80EE&PID_CAFE", SUOI_FORCEDELETE);
     115    if (hr != S_OK)
     116        return RTMsgErrorExitFailure("SetupUninstallOEMInf failed: %Rhrc\n", hr);
     117
     118    RTMsgInfo("USB uninstallation succeeded!");
     119    return 0;
     120}
     121
     122
    115123/**
    116124 * Stops a possibly running service.
     
    119127 * @returns -1 on failure.
    120128 */
    121 int usblibOsStopService(void)
     129static int usblibOsStopService(void)
    122130{
    123131    /*
     
    176184 * @returns -1 on failure.
    177185 */
    178 int usblibOsDeleteService(void)
     186static int usblibOsDeleteService(void)
    179187{
    180188    /*
  • trunk/src/VBox/HostDrivers/VBoxUSB/win/Makefile.kmk

    r96407 r96572  
    122122#
    123123TEMPLATE_VBoxUsbR3 = Template for USBInstalls, USBUninstall and USBTest
    124 TEMPLATE_VBoxUsbR3_EXTENDS  = VBoxR3Static
    125 TEMPLATE_VBoxUsbR3_SDKS     = $(TEMPLATE_VBoxR3Static_SDKS) ReorderCompilerIncs $(VBOX_WINPSDK) $(VBOX_WINDDK) VBOX_WIN_NEWDEV
    126 TEMPLATE_VBoxUsbR3_CXXFLAGS = $(TEMPLATE_VBoxR3Static_CXXFLAGS) -Gz
    127 TEMPLATE_VBoxUsbR3_CFLAGS   = $(TEMPLATE_VBoxR3Static_CFLAGS) -Gz
    128 TEMPLATE_VBoxUsbR3_LIBS     = $(TEMPLATE_VBoxR3Static_LIBS) \
    129         $(PATH_STAGE_LIB)/VBoxDrvCfg$(VBOX_SUFF_LIB)
     124TEMPLATE_VBoxUsbR3_EXTENDS  = VBOXR3EXE
     125TEMPLATE_VBoxUsbR3_SDKS     = $(TEMPLATE_VBOXR3EXE_SDKS) ReorderCompilerIncs $(VBOX_WINPSDK) $(VBOX_WINDDK) VBOX_WIN_NEWDEV
     126TEMPLATE_VBoxUsbR3_CXXFLAGS = $(TEMPLATE_VBOXR3EXE_CXXFLAGS) -Gz
     127TEMPLATE_VBoxUsbR3_CFLAGS   = $(TEMPLATE_VBOXR3EXE_CFLAGS) -Gz
     128TEMPLATE_VBoxUsbR3_LIBS     = $(TEMPLATE_VBOXR3EXE_LIBS) \
     129        $(PATH_STAGE_LIB)/VBoxDrvCfgExe$(VBOX_SUFF_LIB) \
     130       $(LIB_RUNTIME)
    130131
    131132#
  • trunk/src/VBox/HostDrivers/VBoxUSB/win/testcase/USBTest.cpp

    r96407 r96572  
    4242#include <iprt/win/setupapi.h>
    4343#include <newdev.h>
     44
    4445#include <iprt/assert.h>
    45 #include <iprt/err.h>
     46#include <VBox/err.h>
    4647#include <iprt/param.h>
    4748#include <iprt/path.h>
     49#include <iprt/stream.h>
    4850#include <iprt/string.h>
    49 #include <VBox/err.h>
    50 #include <stdio.h>
    5151#include <VBox/usblib.h>
    5252#include <VBox/VBoxDrvCfg-win.h>
    5353
     54
     55/*********************************************************************************************************************************
     56*   Global Variables                                                                                                             *
     57*********************************************************************************************************************************/
    5458/** Handle to the open device. */
    5559static HANDLE   g_hUSBMonitor = INVALID_HANDLE_VALUE;
     
    5761static bool     g_fStartedService = false;
    5862
     63
    5964/**
    6065 * Attempts to start the service, creating it if necessary.
     
    8388int usbMonStopService(void)
    8489{
    85     printf("usbMonStopService\n");
     90    RTPrintf("usbMonStopService\n");
     91
    8692    /*
    8793     * Assume it didn't exist, so we'll create the service.
     
    141147    DWORD          cbReturned = 0;
    142148
    143     printf("usbLibReleaseDevice %x %x %x\n", usVendorId, usProductId, usRevision);
     149    RTPrintf("usbLibReleaseDevice %x %x %x\n", usVendorId, usProductId, usRevision);
    144150
    145151    release.usVendorId  = usVendorId;
     
    174180    Assert(g_hUSBMonitor);
    175181
    176     printf("usblibInsertFilter %04X %04X %04X\n", usVendorId, usProductId, usRevision);
     182    RTPrintf("usblibInsertFilter %04X %04X %04X\n", usVendorId, usProductId, usRevision);
    177183
    178184    USBFilterInit(&filter, USBFILTERTYPE_CAPTURE);
     
    222228    Assert(g_hUSBMonitor);
    223229
    224     printf("usblibRemoveFilter %p\n", aID);
     230    RTPrintf("usblibRemoveFilter %p\n", aID);
    225231
    226232    uId = (uintptr_t)aID;
     
    244250    DWORD          cbReturned;
    245251
    246     printf("usbproxy: usbLibInit\n");
     252    RTPrintf("usbproxy: usbLibInit\n");
    247253
    248254    g_hUSBMonitor = CreateFile (USBMON_DEVICE_NAME,
     
    269275        {
    270276            /* AssertFailed(); */
    271             printf("usbproxy: Unable to open filter driver!! (rc=%lu)\n", GetLastError());
     277            RTPrintf("usbproxy: Unable to open filter driver!! (rc=%lu)\n", GetLastError());
    272278            rc = VERR_FILE_NOT_FOUND;
    273279            goto failure;
     
    281287    if (!DeviceIoControl(g_hUSBMonitor, SUPUSBFLT_IOCTL_GET_VERSION, NULL, 0,&version, sizeof(version),  &cbReturned, NULL))
    282288    {
    283         printf("usbproxy: Unable to query filter version!! (rc=%lu)\n", GetLastError());
     289        RTPrintf("usbproxy: Unable to query filter version!! (rc=%lu)\n", GetLastError());
    284290        rc = VERR_VERSION_MISMATCH;
    285291        goto failure;
     
    292298        )
    293299    {
    294         printf("usbproxy: Filter driver version mismatch!!\n");
     300        RTPrintf("usbproxy: Filter driver version mismatch!!\n");
    295301        rc = VERR_VERSION_MISMATCH;
    296302        goto failure;
     
    344350    RT_NOREF2(argc, argv);
    345351
    346     printf("USB test\n");
     352    RTPrintf("USB test\n");
    347353
    348354    rc = usbMonitorInit();
     
    355361    usbMonInsertFilter(0x80EE, 0x0030, 0x0110, &pId3);
    356362
    357     printf("Waiting to capture devices... enter 'r' to run filters\n");
    358     c = getchar();
     363    RTPrintf("Waiting to capture devices... enter 'r' to run filters\n");
     364    c = RTStrmGetCh(g_pStdIn);
    359365    if (c == 'r')
    360366    {
    361367        usbMonRunFilters();
    362         printf("Waiting to capture devices...\n");
    363         getchar();  /* eat the '\n' */
    364         getchar();  /* wait for more input */
    365     }
    366 
    367     printf("Releasing device\n");
     368        RTPrintf("Waiting to capture devices...\n");
     369        RTStrmGetCh(g_pStdIn);  /* eat the '\n' */
     370        RTStrmGetCh(g_pStdIn);  /* wait for more input */
     371    }
     372
     373    RTPrintf("Releasing device\n");
    368374    usbMonReleaseDevice(0xA16, 0x2499, 0x100);
    369375
     
    376382    return 0;
    377383}
     384
  • trunk/src/VBox/HostDrivers/win/Makefile.kmk

    r96407 r96572  
    3838include $(KBUILD_PATH)/subheader.kmk
    3939
    40 # For the installer helpers
    41 LIBRARIES += VBoxDrvCfg
    42 VBoxDrvCfg_TEMPLATE       = VBoxR3StaticDllNoAsan
    43 VBoxDrvCfg_SDKS           = ReorderCompilerIncs $(VBOX_WINPSDK) $(VBOX_WINDDK)
    44 VBoxDrvCfg_DEFS           = _WIN32_WINNT=0x0501 _UNICODE UNICODE
    45 VBoxDrvCfg_SOURCES        = cfg/VBoxDrvCfg.cpp
     40# For the installer helper DLL.
     41LIBRARIES += VBoxDrvCfgSharedStatic
     42VBoxDrvCfgSharedStatic_TEMPLATE := VBoxR3StaticDllNoAsan
     43VBoxDrvCfgSharedStatic_SDKS     = ReorderCompilerIncs $(VBOX_WINPSDK) $(VBOX_WINDDK)
     44VBoxDrvCfgSharedStatic_DEFS     := _WIN32_WINNT=0x0501 _UNICODE UNICODE
     45VBoxDrvCfgSharedStatic_SOURCES  := cfg/VBoxDrvCfg.cpp
     46
     47# For the driver installer/uninstaller executables.
     48LIBRARIES += VBoxDrvCfgExe
     49VBoxDrvCfgExe_TEMPLATE := VBOXR3EXE
     50VBoxDrvCfgExe_EXTENDS  := VBoxDrvCfgSharedStatic
     51
     52# For the regular VBox DLLs.
     53LIBRARIES += VBoxDrvCfgDll
     54VBoxDrvCfgDll_TEMPLATE := VBoxR3Dll
     55VBoxDrvCfgDll_EXTENDS  := VBoxDrvCfgSharedStatic
    4656
    4757
  • trunk/src/VBox/HostDrivers/win/cfg/VBoxDrvCfg.cpp

    r96407 r96572  
    11/* $Id$ */
    22/** @file
    3  * VBoxDrvCfg.cpp - Windows Driver Manipulation API implementation
     3 * VBoxDrvCfg.cpp - Windows Driver Manipulation API implementation.
     4 *
     5 * @note This is EXTREMELY BADLY documented code. Please help improve by
     6 *       adding comments whenever you've got a chance!
    47 */
    58
     
    4346#include <iprt/win/setupapi.h>
    4447#include <iprt/win/shlobj.h>
    45 
    46 #include <string.h>
    47 
    48 #include <stdlib.h>
    49 #include <malloc.h>
    50 #include <stdio.h>
    51 
    5248#include <Newdev.h>
     49
     50#include <iprt/alloca.h>
     51#include <iprt/mem.h>
     52#include <iprt/path.h>
     53#include <iprt/string.h>
     54#include <iprt/utf16.h>
    5355
    5456
     
    5658*   Global Variables                                                                                                             *
    5759*********************************************************************************************************************************/
    58 static PFNVBOXDRVCFG_LOG g_pfnVBoxDrvCfgLog;
     60static PFNVBOXDRVCFGLOG g_pfnVBoxDrvCfgLog;
    5961static void *g_pvVBoxDrvCfgLog;
    6062
    61 static PFNVBOXDRVCFG_PANIC g_pfnVBoxDrvCfgPanic;
     63static PFNVBOXDRVCFGPANIC g_pfnVBoxDrvCfgPanic;
    6264static void *g_pvVBoxDrvCfgPanic;
    6365
    6466
    65 VBOXDRVCFG_DECL(void) VBoxDrvCfgLoggerSet(PFNVBOXDRVCFG_LOG pfnLog, void *pvLog)
     67VBOXDRVCFG_DECL(void) VBoxDrvCfgLoggerSet(PFNVBOXDRVCFGLOG pfnLog, void *pvLog)
    6668{
    6769    g_pfnVBoxDrvCfgLog = pfnLog;
     
    6971}
    7072
    71 VBOXDRVCFG_DECL(void) VBoxDrvCfgPanicSet(PFNVBOXDRVCFG_PANIC pfnPanic, void *pvPanic)
     73VBOXDRVCFG_DECL(void) VBoxDrvCfgPanicSet(PFNVBOXDRVCFGPANIC pfnPanic, void *pvPanic)
    7274{
    7375    g_pfnVBoxDrvCfgPanic = pfnPanic;
     
    7577}
    7678
    77 static void vboxDrvCfgLogRel(LPCSTR szString, ...)
    78 {
    79     PFNVBOXDRVCFG_LOG pfnLog = g_pfnVBoxDrvCfgLog;
    80     void * pvLog = g_pvVBoxDrvCfgLog;
     79static void vboxDrvCfgLogRel(const char *pszFormat, ...)
     80{
     81    PFNVBOXDRVCFGLOG pfnLog = g_pfnVBoxDrvCfgLog;
     82    void *pvLog = g_pvVBoxDrvCfgLog;
    8183    if (pfnLog)
    8284    {
    83         char szBuffer[4096] = {0};
    84         va_list pArgList;
    85         va_start(pArgList, szString);
    86         _vsnprintf(szBuffer, RT_ELEMENTS(szBuffer), szString, pArgList);
    87         va_end(pArgList);
     85        char szBuffer[4096];
     86        va_list va;
     87        va_start(va, pszFormat);
     88        RTStrPrintfV(szBuffer, RT_ELEMENTS(szBuffer), pszFormat, va);
     89        va_end(va);
    8890        pfnLog(VBOXDRVCFG_LOG_SEVERITY_REL, szBuffer, pvLog);
    8991    }
    9092}
    9193
    92 static void vboxDrvCfgLogRegular(LPCSTR szString, ...)
    93 {
    94     PFNVBOXDRVCFG_LOG pfnLog = g_pfnVBoxDrvCfgLog;
    95     void * pvLog = g_pvVBoxDrvCfgLog;
     94static void vboxDrvCfgLogRegular(const char *pszFormat, ...)
     95{
     96    PFNVBOXDRVCFGLOG pfnLog = g_pfnVBoxDrvCfgLog;
     97    void *pvLog = g_pvVBoxDrvCfgLog;
    9698    if (pfnLog)
    9799    {
    98         char szBuffer[4096] = {0};
    99         va_list pArgList;
    100         va_start(pArgList, szString);
    101         _vsnprintf(szBuffer, RT_ELEMENTS(szBuffer), szString, pArgList);
    102         va_end(pArgList);
     100        char szBuffer[4096];
     101        va_list va;
     102        va_start(va, pszFormat);
     103        RTStrPrintfV(szBuffer, RT_ELEMENTS(szBuffer), pszFormat, va);
     104        va_end(va);
    103105        pfnLog(VBOXDRVCFG_LOG_SEVERITY_REGULAR, szBuffer, pvLog);
    104106    }
    105107}
    106108
    107 static void vboxDrvCfgLogFlow(LPCSTR szString, ...)
    108 {
    109     PFNVBOXDRVCFG_LOG pfnLog = g_pfnVBoxDrvCfgLog;
    110     void * pvLog = g_pvVBoxDrvCfgLog;
     109static void vboxDrvCfgLogFlow(const char *pszFormat, ...)
     110{
     111    PFNVBOXDRVCFGLOG pfnLog = g_pfnVBoxDrvCfgLog;
     112    void *pvLog = g_pvVBoxDrvCfgLog;
    111113    if (pfnLog)
    112114    {
    113         char szBuffer[4096] = {0};
    114         va_list pArgList;
    115         va_start(pArgList, szString);
    116         _vsnprintf(szBuffer, RT_ELEMENTS(szBuffer), szString, pArgList);
    117         va_end(pArgList);
     115        char szBuffer[4096];
     116        va_list va;
     117        va_start(va, pszFormat);
     118        RTStrPrintfV(szBuffer, RT_ELEMENTS(szBuffer), pszFormat, va);
     119        va_end(va);
    118120        pfnLog(VBOXDRVCFG_LOG_SEVERITY_FLOW, szBuffer, pvLog);
    119121    }
    120122}
    121123
    122 static void vboxDrvCfgPanic()
    123 {
    124     PFNVBOXDRVCFG_PANIC pfnPanic = g_pfnVBoxDrvCfgPanic;
    125     void * pvPanic = g_pvVBoxDrvCfgPanic;
     124static void vboxDrvCfgPanic(void)
     125{
     126    PFNVBOXDRVCFGPANIC pfnPanic = g_pfnVBoxDrvCfgPanic;
     127    void *pvPanic = g_pvVBoxDrvCfgPanic;
    126128    if (pfnPanic)
    127     {
    128129        pfnPanic(pvPanic);
    129     }
    130130}
    131131
     
    141141
    142142
     143/**
     144 * This is a simple string vector class.
     145 *
     146 * @note Is is _NOT_ a list as the name could lead you to believe, but a vector.
     147 */
    143148class VBoxDrvCfgStringList
    144149{
    145150public:
    146     VBoxDrvCfgStringList(int aSize);
    147 
     151    VBoxDrvCfgStringList(size_t a_cElements);
    148152    ~VBoxDrvCfgStringList();
    149153
    150154    HRESULT add(LPWSTR pStr);
    151155
    152     int size() {return mSize;}
    153 
    154     LPWSTR get(int i) {return maList[i];}
     156    size_t size() { return m_cUsed; }
     157
     158    LPWSTR get(size_t i) { return i < m_cUsed ? m_paStrings[i] : NULL; }
    155159private:
    156     HRESULT resize(int newSize);
    157 
    158     LPWSTR *maList;
    159     int mBufSize;
    160     int mSize;
     160    HRESULT grow(size_t a_cNew);
     161
     162    /** Array of strings. */
     163    LPWSTR *m_paStrings;
     164    size_t  m_cAllocated;
     165    size_t  m_cUsed;
    161166};
    162167
    163 VBoxDrvCfgStringList::VBoxDrvCfgStringList(int aSize)
    164 {
    165     maList = (LPWSTR*)malloc( sizeof(maList[0]) * aSize);
    166     mBufSize = aSize;
    167     mSize = 0;
     168VBoxDrvCfgStringList::VBoxDrvCfgStringList(size_t a_cElements)
     169{
     170    m_paStrings  = (LPWSTR *)RTMemAllocZ(sizeof(m_paStrings[0]) * a_cElements);
     171    m_cAllocated = a_cElements;
     172    m_cUsed      = 0;
    168173}
    169174
    170175VBoxDrvCfgStringList::~VBoxDrvCfgStringList()
    171176{
    172     if (!mBufSize)
     177    if (!m_cAllocated)
    173178        return;
    174179
    175     for (int i = 0; i < mSize; ++i)
    176     {
    177         free(maList[i]);
    178     }
    179 
    180     free(maList);
     180    for (size_t i = 0; i < m_cUsed; ++i)
     181        RTMemFree(m_paStrings[i]);
     182    RTMemFree(m_paStrings);
     183    m_paStrings  = NULL;
     184    m_cAllocated = 0;
     185    m_cUsed      = 0;
    181186}
    182187
    183188HRESULT VBoxDrvCfgStringList::add(LPWSTR pStr)
    184189{
    185     if (mSize == mBufSize)
    186     {
    187         int hr = resize(mBufSize+10);
    188         if (SUCCEEDED(hr))
    189             return hr;
    190     }
    191     size_t cStr = wcslen(pStr) + 1;
    192     LPWSTR str = (LPWSTR)malloc( sizeof(maList[0][0]) * cStr);
    193     memcpy(str, pStr, sizeof(maList[0][0]) * cStr);
    194     maList[mSize] = str;
    195     ++mSize;
     190    if (m_cUsed == m_cAllocated)
     191    {
     192        int hrc = grow(m_cAllocated + 16);
     193        if (SUCCEEDED(hrc))
     194            return hrc;
     195    }
     196    LPWSTR str = (LPWSTR)RTMemDup(pStr, (RTUtf16Len(pStr) + 1) * sizeof(m_paStrings[0][0]));
     197    if (!str)
     198        return E_OUTOFMEMORY;
     199    m_paStrings[m_cUsed] = str;
     200    ++m_cUsed;
    196201    return S_OK;
    197202}
    198203
    199 HRESULT VBoxDrvCfgStringList::resize(int newSize)
    200 {
    201     NonStandardAssert(newSize >= mSize);
    202     if (newSize < mSize)
     204HRESULT VBoxDrvCfgStringList::grow(size_t a_cNew)
     205{
     206    NonStandardAssert(a_cNew >= m_cUsed);
     207    if (a_cNew < m_cUsed)
    203208        return E_FAIL;
    204     LPWSTR* pOld = maList;
    205     maList = (LPWSTR*)malloc( sizeof(maList[0]) * newSize);
    206     mBufSize = newSize;
    207     memcpy(maList, pOld, mSize*sizeof(maList[0]));
    208     free(pOld);
     209    void *pvNew = RTMemReallocZ(m_paStrings, m_cUsed * sizeof(m_paStrings[0]), a_cNew * sizeof(m_paStrings[0]));
     210    if (!pvNew)
     211        return E_OUTOFMEMORY;
     212    m_paStrings  = (LPWSTR *)pvNew;
     213    m_cAllocated = a_cNew;
    209214    return S_OK;
    210215}
     
    213218 * inf file manipulation API
    214219 */
    215 typedef bool (*PFNVBOXNETCFG_ENUMERATION_CALLBACK) (LPCWSTR lpszFileName, PVOID pContext);
    216 
    217 typedef struct _INF_INFO
    218 {
    219     LPCWSTR lpszClassName;
    220     LPCWSTR lpszPnPId;
    221 } INF_INFO, *PINF_INFO;
    222 
    223 typedef struct _INFENUM_CONTEXT
    224 {
    225     INF_INFO InfInfo;
    226     DWORD Flags;
    227     HRESULT hr;
    228 } INFENUM_CONTEXT, *PINFENUM_CONTEXT;
    229 
    230 static HRESULT vboxDrvCfgInfQueryContext(HINF hInf, LPCWSTR lpszSection, LPCWSTR lpszKey, PINFCONTEXT pCtx)
    231 {
    232     if (!SetupFindFirstLineW(hInf, lpszSection, lpszKey, pCtx))
     220typedef bool (*PFNVBOXNETCFG_ENUMERATION_CALLBACK_T)(LPCWSTR lpszFileName, PVOID pContext);
     221
     222typedef struct INF_INFO_T
     223{
     224    LPCWSTR pwszClassName;
     225    LPCWSTR pwszPnPId;
     226} INF_INFO_T, *PINF_INFO_T;
     227
     228typedef struct INFENUM_CONTEXT_T
     229{
     230    INF_INFO_T InfInfo;
     231    DWORD fFlags;
     232    HRESULT hrc;
     233} INFENUM_CONTEXT_T, *PINFENUM_CONTEXT_T;
     234
     235static HRESULT vboxDrvCfgInfQueryContext(HINF hInf, LPCWSTR pwszSection, LPCWSTR pwszKey, PINFCONTEXT pCtx)
     236{
     237    if (!SetupFindFirstLineW(hInf, pwszSection, pwszKey, pCtx))
    233238    {
    234239        DWORD dwErr = GetLastError();
    235         NonStandardLogRelCrap((__FUNCTION__ ": SetupFindFirstLine failed WinEr (%d) for Section(%S), Key(%S)\n", dwErr, lpszSection, lpszKey));
     240        NonStandardLogRelCrap((__FUNCTION__ ": SetupFindFirstLine failed WinEr (%Rwc) for Section(%ls), Key(%ls)\n",
     241                               dwErr, pwszSection, pwszKey));
    236242        return HRESULT_FROM_WIN32(dwErr);
    237243    }
     
    239245}
    240246
    241 static HRESULT vboxDrvCfgInfQueryKeyValue(PINFCONTEXT pCtx, DWORD iValue, LPWSTR *lppszValue, PDWORD pcValue)
    242 {
    243     DWORD dwErr;
    244     DWORD cValue;
    245 
    246     if (!SetupGetStringFieldW(pCtx, iValue, NULL, 0, &cValue))
    247     {
    248         dwErr = GetLastError();
     247static HRESULT vboxDrvCfgInfQueryKeyValue(PINFCONTEXT pCtx, DWORD iValue, LPWSTR *ppwszValue, PDWORD pcwcValue)
     248{
     249    *ppwszValue = NULL;
     250    if (pcwcValue)
     251        *pcwcValue = 0;
     252
     253    DWORD cwcValue;
     254    if (!SetupGetStringFieldW(pCtx, iValue, NULL, 0, &cwcValue))
     255    {
     256        DWORD dwErr = GetLastError();
    249257//        NonStandardAssert(dwErr == ERROR_INSUFFICIENT_BUFFER);
    250258        if (dwErr != ERROR_INSUFFICIENT_BUFFER)
    251259        {
    252             NonStandardLogFlowCrap((__FUNCTION__ ": SetupGetStringField failed WinEr (%d) for iValue(%d)\n", dwErr, iValue));
     260            NonStandardLogFlowCrap((__FUNCTION__ ": SetupGetStringField failed WinEr (%Rwc) for iValue(%d)\n", dwErr, iValue));
    253261            return HRESULT_FROM_WIN32(dwErr);
    254262        }
    255263    }
    256264
    257     LPWSTR lpszValue = (LPWSTR)malloc(cValue * sizeof (lpszValue[0]));
    258     NonStandardAssert(lpszValue);
    259     if (!lpszValue)
    260     {
    261         NonStandardLogRelCrap((__FUNCTION__ ": SetCoTaskMemAlloc failed to alloc mem of size (%d), for iValue(%d)\n", cValue * sizeof (lpszValue[0]), iValue));
     265    LPWSTR pwszValue = (LPWSTR)RTMemAlloc(cwcValue * sizeof(pwszValue[0]));
     266    NonStandardAssert(pwszValue);
     267    if (!pwszValue)
     268    {
     269        NonStandardLogRelCrap((__FUNCTION__ ": SetCoTaskMemAlloc failed to alloc mem of size (%d), for iValue(%d)\n",
     270                               cwcValue * sizeof(pwszValue[0]), iValue));
    262271        return E_FAIL;
    263272    }
    264273
    265     if (!SetupGetStringFieldW(pCtx, iValue, lpszValue, cValue, &cValue))
    266     {
    267         dwErr = GetLastError();
    268         NonStandardLogRelCrap((__FUNCTION__ ": SetupGetStringField failed WinEr (%d) for iValue(%d)\n", dwErr, iValue));
    269         NonStandardAssert(0);
    270         free(lpszValue);
     274    if (!SetupGetStringFieldW(pCtx, iValue, pwszValue, cwcValue, &cwcValue))
     275    {
     276        DWORD dwErr = GetLastError();
     277        NonStandardLogRelCrap((__FUNCTION__ ": SetupGetStringField failed WinEr (%Rwc) for iValue(%d)\n", dwErr, iValue));
     278        NonStandardAssertFailed();
     279        RTMemFree(pwszValue);
    271280        return HRESULT_FROM_WIN32(dwErr);
    272281    }
    273282
    274     *lppszValue = lpszValue;
    275     if (pcValue)
    276         *pcValue = cValue;
     283    *ppwszValue = pwszValue;
     284    if (pcwcValue)
     285        *pcwcValue = cwcValue;
    277286    return S_OK;
    278287}
     288
    279289#if defined(RT_ARCH_AMD64)
    280 # define VBOXDRVCFG_ARCHSTR L"amd64"
     290# define VBOXDRVCFG_ARCHSTR "amd64"
    281291#else
    282 # define VBOXDRVCFG_ARCHSTR L"x86"
     292# define VBOXDRVCFG_ARCHSTR "x86"
    283293#endif
    284294
    285 static HRESULT vboxDrvCfgInfQueryModelsSectionName(HINF hInf, LPWSTR *lppszValue, PDWORD pcValue)
    286 {
     295static HRESULT vboxDrvCfgInfQueryModelsSectionName(HINF hInf, LPWSTR *ppwszValue, PDWORD pcwcValue)
     296{
     297    *ppwszValue = NULL;
     298    if (pcwcValue)
     299        *pcwcValue = 0;
     300
    287301    INFCONTEXT InfCtx;
    288     LPWSTR lpszModels, lpszPlatform = NULL, lpszPlatformCur;
    289     LPWSTR lpszResult = NULL;
    290     DWORD cModels, cPlatform = 0, cPlatformCur, cResult = 0;
    291     bool bNt = false, bArch = false /*, bOs = false */;
    292 
    293     HRESULT hr = vboxDrvCfgInfQueryContext(hInf, L"Manufacturer", NULL, &InfCtx);
    294     if (hr != S_OK)
    295     {
    296         NonStandardLogCrap((__FUNCTION__ ": vboxDrvCfgInfQueryContext for Manufacturer failed, hr=0x%x\n", hr));
    297         return hr;
    298     }
    299 
    300     hr = vboxDrvCfgInfQueryKeyValue(&InfCtx, 1, &lpszModels, &cModels);
    301     if (hr != S_OK)
    302     {
    303         NonStandardLogRelCrap((__FUNCTION__ ": vboxDrvCfgRegQueryKeyValue 1 for Manufacturer failed, hr=0x%x\n", hr));
    304         return hr;
    305     }
    306 
    307     for (DWORD i = 2; (hr = vboxDrvCfgInfQueryKeyValue(&InfCtx, i, &lpszPlatformCur, &cPlatformCur)) == S_OK; ++i)
    308     {
    309         if (wcsicmp(lpszPlatformCur, L"NT" VBOXDRVCFG_ARCHSTR))
    310         {
    311             if (bNt)
     302    HRESULT hrc = vboxDrvCfgInfQueryContext(hInf, L"Manufacturer", NULL, &InfCtx);
     303    if (hrc != S_OK)
     304    {
     305        NonStandardLogCrap((__FUNCTION__ ": vboxDrvCfgInfQueryContext for Manufacturer failed, hrc=0x%x\n", hrc));
     306        return hrc;
     307    }
     308
     309    LPWSTR pwszModels;
     310    DWORD  cwcModels;
     311    hrc = vboxDrvCfgInfQueryKeyValue(&InfCtx, 1, &pwszModels, &cwcModels);
     312    if (hrc != S_OK)
     313    {
     314        NonStandardLogRelCrap((__FUNCTION__ ": vboxDrvCfgRegQueryKeyValue 1 for Manufacturer failed, hrc=0x%x\n", hrc));
     315        return hrc;
     316    }
     317
     318    LPWSTR pwszPlatform = NULL;
     319    DWORD  cwcPlatform  = 0;
     320    bool   fArch        = false;
     321    bool   fNt          = false;
     322
     323    LPWSTR pwszPlatformCur;
     324    DWORD  cwcPlatformCur;
     325    for (DWORD i = 2; (hrc = vboxDrvCfgInfQueryKeyValue(&InfCtx, i, &pwszPlatformCur, &cwcPlatformCur)) == S_OK; ++i)
     326    {
     327        if (RTUtf16ICmpAscii(pwszPlatformCur, "NT" VBOXDRVCFG_ARCHSTR) == 0)
     328            fArch = true;
     329        else
     330        {
     331            if (fNt || RTUtf16ICmpAscii(pwszPlatformCur, "NT") != 0)
    312332            {
    313                 free(lpszPlatformCur);
    314                 lpszPlatformCur = NULL;
     333                RTMemFree(pwszPlatformCur);
     334                pwszPlatformCur = NULL;
    315335                continue;
    316336            }
    317 
    318             if (wcsicmp(lpszPlatformCur, L"NT"))
     337            fNt = true;
     338        }
     339
     340        cwcPlatform = cwcPlatformCur;
     341        if (pwszPlatform)
     342            RTMemFree(pwszPlatform);
     343        pwszPlatform = pwszPlatformCur;
     344        pwszPlatformCur = NULL;
     345    }
     346
     347    hrc = S_OK;
     348
     349    LPWSTR pwszResult = NULL;
     350    DWORD  cwcResult = 0;
     351    if (pwszPlatform)
     352    {
     353        pwszResult = (LPWSTR)RTMemAlloc((cwcModels + cwcPlatform) * sizeof(pwszResult[0]));
     354        if (pwszResult)
     355        {
     356            memcpy(pwszResult, pwszModels, (cwcModels - 1) * sizeof(pwszResult[0]));
     357            pwszResult[cwcModels - 1] = L'.';
     358            memcpy(&pwszResult[cwcModels], pwszPlatform, cwcPlatform * sizeof(pwszResult[0]));
     359            cwcResult = cwcModels + cwcPlatform;
     360        }
     361        else
     362            hrc = E_OUTOFMEMORY;
     363    }
     364    else
     365    {
     366        pwszResult = pwszModels;
     367        cwcResult  = cwcModels;
     368        pwszModels = NULL;
     369    }
     370
     371    if (pwszModels)
     372        RTMemFree(pwszModels);
     373    if (pwszPlatform)
     374        RTMemFree(pwszPlatform);
     375
     376    if (hrc == S_OK)
     377    {
     378        *ppwszValue = pwszResult;
     379        if (pcwcValue)
     380            *pcwcValue = cwcResult;
     381    }
     382
     383    return hrc;
     384}
     385
     386static HRESULT vboxDrvCfgInfQueryFirstPnPId(HINF hInf, LPWSTR *ppwszPnPId)
     387{
     388    *ppwszPnPId = NULL;
     389
     390    LPWSTR pwszModels;
     391    HRESULT hrc = vboxDrvCfgInfQueryModelsSectionName(hInf, &pwszModels, NULL);
     392    NonStandardLogRelCrap((__FUNCTION__ ": vboxDrvCfgInfQueryModelsSectionName returned pwszModels = (%ls)", pwszModels));
     393    if (hrc != S_OK)
     394    {
     395        NonStandardLogCrap((__FUNCTION__ ": vboxDrvCfgRegQueryKeyValue for Manufacturer failed, hrc=0x%x\n", hrc));
     396        return hrc;
     397    }
     398
     399    LPWSTR     pwszPnPId = NULL;
     400    INFCONTEXT InfCtx;
     401    hrc = vboxDrvCfgInfQueryContext(hInf, pwszModels, NULL, &InfCtx);
     402    if (hrc == S_OK)
     403    {
     404        hrc = vboxDrvCfgInfQueryKeyValue(&InfCtx, 2, &pwszPnPId, NULL);
     405        if (hrc == S_OK)
     406        {
     407            NonStandardLogRelCrap((__FUNCTION__ ": vboxDrvCfgRegQueryKeyValue for models (%ls) returned pwszPnPId (%ls)\n", pwszModels, pwszPnPId));
     408            *ppwszPnPId = pwszPnPId;
     409        }
     410        else
     411            NonStandardLogRelCrap((__FUNCTION__ ": vboxDrvCfgRegQueryKeyValue for models (%ls) failed, hrc=0x%x\n", pwszModels, hrc));
     412    }
     413    else
     414        NonStandardLogRelCrap((__FUNCTION__ ": vboxDrvCfgInfQueryContext for models (%ls) failed, hrc=0x%x\n", pwszModels, hrc));
     415
     416    RTMemFree(pwszModels);
     417    return hrc;
     418}
     419
     420static bool vboxDrvCfgInfEnumerationCallback(LPCWSTR pwszFileName, PVOID pCtxt)
     421{
     422    PINFENUM_CONTEXT_T pContext = (PINFENUM_CONTEXT_T)pCtxt;
     423    NonStandardLogRelCrap((__FUNCTION__": pwszFileName (%ls)\n", pwszFileName));
     424    NonStandardLogRelCrap((__FUNCTION__ ": pContext->InfInfo.pwszClassName = (%ls)\n", pContext->InfInfo.pwszClassName));
     425    HINF hInf = SetupOpenInfFileW(pwszFileName, pContext->InfInfo.pwszClassName, INF_STYLE_WIN4, NULL /*__in PUINT ErrorLine */);
     426    if (hInf == INVALID_HANDLE_VALUE)
     427    {
     428        DWORD const dwErr = GetLastError();
     429//        NonStandardAssert(dwErr == ERROR_CLASS_MISMATCH);
     430        if (dwErr != ERROR_CLASS_MISMATCH)
     431            NonStandardLogCrap((__FUNCTION__ ": SetupOpenInfFileW err dwErr=%u\n", dwErr));
     432        else
     433            NonStandardLogCrap((__FUNCTION__ ": dwErr == ERROR_CLASS_MISMATCH\n"));
     434        return true;
     435    }
     436
     437    LPWSTR pwszPnPId;
     438    HRESULT hrc = vboxDrvCfgInfQueryFirstPnPId(hInf, &pwszPnPId);
     439    NonStandardLogRelCrap((__FUNCTION__ ": vboxDrvCfgInfQueryFirstPnPId returned pwszPnPId = (%ls)\n", pwszPnPId));
     440    NonStandardLogRelCrap((__FUNCTION__ ": pContext->InfInfo.pwszPnPId = (%ls)\n", pContext->InfInfo.pwszPnPId));
     441    if (hrc == S_OK)
     442    {
     443        if (!RTUtf16ICmp(pContext->InfInfo.pwszPnPId, pwszPnPId))
     444        {
     445            /** @todo bird/2020-09-01: See the following during uninstallation with
     446             * windbg attached (see DllMain trick):
     447             *
     448             *   ModLoad: 00007ffa`73c20000 00007ffa`73c4f000   C:\WINDOWS\SYSTEM32\drvsetup.dll
     449             *   (1b238.1b254): Access violation - code c0000005 (first chance)
     450             *   First chance exceptions are reported before any exception handling.
     451             *   This exception may be expected and handled.
     452             *   KERNELBASE!WaitForMultipleObjectsEx+0x9e:
     453             *   00007ffa`8247cb6e 458b74fd00      mov     r14d,dword ptr [r13+rdi*8] ds:00000000`00000010=????????
     454             *   0:006> k
     455             *    # Child-SP          RetAddr           Call Site
     456             *   00 00000099`6e4fe7a0 00007ffa`73c2df46 KERNELBASE!WaitForMultipleObjectsEx+0x9e
     457             *   01 00000099`6e4fea90 00007ffa`73c32ec2 drvsetup!pSetupStringTableEnum+0x3e
     458             *   02 00000099`6e4feae0 00007ffa`73c2ae9d drvsetup!DrvUtilsUpdateInfoEnumDriverInfs+0x8e
     459             *   03 00000099`6e4feb20 00007ffa`73c2b1cc drvsetup!DrvSetupUninstallDriverInternal+0x211
     460             *   04 00000099`6e4febe0 00007ffa`83eb09d7 drvsetup!pDrvSetupUninstallDriver+0xfc
     461             *   05 00000099`6e4fec30 00007ffa`83eb06a0 SETUPAPI!pSetupUninstallOEMInf+0x26b
     462             *   06 00000099`6e4fef00 00007ffa`57a39fb7 SETUPAPI!SetupUninstallOEMInfW+0x170
     463             *   07 00000099`6e4ff190 00007ffa`57a3ae0c MSID039!vboxDrvCfgInfEnumerationCallback+0xf7 [E:\vbox\svn\trunk\src\VBox\HostDrivers\win\cfg\VBoxDrvCfg.cpp @ 445]
     464             *   08 00000099`6e4ff1c0 00007ffa`57a321e6 MSID039!VBoxDrvCfgInfUninstallAllSetupDi+0xfc [E:\vbox\svn\trunk\src\VBox\HostDrivers\win\cfg\VBoxDrvCfg.cpp @ 653]
     465             *   09 (Inline Function) --------`-------- MSID039!_removeHostOnlyInterfaces+0x6c [E:\vbox\svn\trunk\src\VBox\Installer\win\InstallHelper\VBoxInstallHelper.cpp @ 1523]
     466             *   0a 00000099`6e4ff240 00007ffa`610f59d3 MSID039!RemoveHostOnlyInterfaces+0x76 [E:\vbox\svn\trunk\src\VBox\Installer\win\InstallHelper\VBoxInstallHelper.cpp @ 1545]
     467             *   0b 00000099`6e4ff270 00007ffa`610d80ac msi!CallCustomDllEntrypoint+0x2b
     468             *   0c 00000099`6e4ff2e0 00007ffa`84567034 msi!CMsiCustomAction::CustomActionThread+0x34c
     469             *   0d 00000099`6e4ff8d0 00007ffa`849a2651 KERNEL32!BaseThreadInitThunk+0x14
     470             *   0e 00000099`6e4ff900 00000000`00000000 ntdll!RtlUserThreadStart+0x21
     471             *   0:006> r
     472             *   rax=000000996e114000 rbx=0000000000000002 rcx=0000000000000002
     473             *   rdx=0000000000000000 rsi=0000000000000000 rdi=0000000000000000
     474             *   rip=00007ffa8247cb6e rsp=000000996e4fe7a0 rbp=0000000000000004
     475             *    r8=0000000000000000  r9=00000000ffffffff r10=0000000000000000
     476             *   r11=0000000000000246 r12=00000000ffffffff r13=0000000000000010
     477             *   r14=00007ffa73c32e00 r15=0000000000000001
     478             *   iopl=0         nv up ei ng nz ac pe cy
     479             *   cs=0033  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010293
     480             *   KERNELBASE!WaitForMultipleObjectsEx+0x9e:
     481             *   00007ffa`8247cb6e 458b74fd00      mov     r14d,dword ptr [r13+rdi*8] ds:00000000`00000010=????????
     482             *
     483             * Happens with the filter driver too:
     484             *
     485             *   (1b238.1b7e0): Access violation - code c0000005 (first chance)
     486             *   First chance exceptions are reported before any exception handling.
     487             *   This exception may be expected and handled.
     488             *   KERNELBASE!WaitForMultipleObjectsEx+0x9e:
     489             *   00007ffa`8247cb6e 458b74fd00      mov     r14d,dword ptr [r13+rdi*8] ds:00000000`00000010=????????
     490             *   0:006> k
     491             *    # Child-SP          RetAddr           Call Site
     492             *   00 00000099`6e4fe8c0 00007ffa`6558df46 KERNELBASE!WaitForMultipleObjectsEx+0x9e
     493             *   01 00000099`6e4febb0 00007ffa`65592ec2 drvsetup!pSetupStringTableEnum+0x3e
     494             *   02 00000099`6e4fec00 00007ffa`6558ae9d drvsetup!DrvUtilsUpdateInfoEnumDriverInfs+0x8e
     495             *   03 00000099`6e4fec40 00007ffa`6558b1cc drvsetup!DrvSetupUninstallDriverInternal+0x211
     496             *   04 00000099`6e4fed00 00007ffa`83eb09d7 drvsetup!pDrvSetupUninstallDriver+0xfc
     497             *   05 00000099`6e4fed50 00007ffa`83eb06a0 SETUPAPI!pSetupUninstallOEMInf+0x26b
     498             *   06 00000099`6e4ff020 00007ffa`57a39fb7 SETUPAPI!SetupUninstallOEMInfW+0x170
     499             *   07 00000099`6e4ff2b0 00007ffa`57a3abaf MSI398C!vboxDrvCfgInfEnumerationCallback+0xf7 [E:\vbox\svn\trunk\src\VBox\HostDrivers\win\cfg\VBoxDrvCfg.cpp @ 445]
     500             *   08 (Inline Function) --------`-------- MSI398C!vboxDrvCfgEnumFiles+0x4f [E:\vbox\svn\trunk\src\VBox\HostDrivers\win\cfg\VBoxDrvCfg.cpp @ 670]
     501             *   09 00000099`6e4ff2e0 00007ffa`57a3792e MSI398C!VBoxDrvCfgInfUninstallAllF+0xdf [E:\vbox\svn\trunk\src\VBox\HostDrivers\win\cfg\VBoxDrvCfg.cpp @ 723]
     502             *   0a 00000099`6e4ff7b0 00007ffa`57a33411 MSI398C!vboxNetCfgWinNetLwfUninstall+0x9e [E:\vbox\svn\trunk\src\VBox\HostDrivers\VBoxNetFlt\win\cfg\VBoxNetCfg.cpp @ 2249]
     503             *   0b 00000099`6e4ff7e0 00007ffa`57a3263d MSI398C!_uninstallNetLwf+0x71 [E:\vbox\svn\trunk\src\VBox\Installer\win\InstallHelper\VBoxInstallHelper.cpp @ 1206]
     504             *   0c 00000099`6e4ff810 00007ffa`610f59d3 MSI398C!UninstallNetFlt+0xd [E:\vbox\svn\trunk\src\VBox\Installer\win\InstallHelper\VBoxInstallHelper.cpp @ 1124]
     505             *   0d 00000099`6e4ff840 00007ffa`610d80ac msi!CallCustomDllEntrypoint+0x2b
     506             *   0e 00000099`6e4ff8b0 00007ffa`84567034 msi!CMsiCustomAction::CustomActionThread+0x34c
     507             *   0f 00000099`6e4ffea0 00007ffa`849a2651 KERNEL32!BaseThreadInitThunk+0x14
     508             *   10 00000099`6e4ffed0 00000000`00000000 ntdll!RtlUserThreadStart+0x21
     509             *   0:006> r
     510             *   rax=000000996e114000 rbx=0000000000000002 rcx=0000000000000002
     511             *   rdx=0000000000000000 rsi=0000000000000000 rdi=0000000000000000
     512             *   rip=00007ffa8247cb6e rsp=000000996e4fe8c0 rbp=0000000000000004
     513             *    r8=0000000000000000  r9=00000000ffffffff r10=0000000000000000
     514             *   r11=0000000000000246 r12=00000000ffffffff r13=0000000000000010
     515             *   r14=00007ffa65592e00 r15=0000000000000000
     516             *   iopl=0         nv up ei ng nz ac pe cy
     517             *   cs=0033  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010293
     518             *   KERNELBASE!WaitForMultipleObjectsEx+0x9e:
     519             *   00007ffa`8247cb6e 458b74fd00      mov     r14d,dword ptr [r13+rdi*8] ds:00000000`00000010=????????
     520             *
     521             * BUGBUG
     522             */
     523#if 0
     524            if (!SetupUninstallOEMInfW(pwszFileName, pContext->fFlags, /* could be SUOI_FORCEDELETE */ NULL /* Reserved */))
     525#else /* Just in case the API doesn't catch it itself (seems it does on w10/19044).  */
     526            BOOL  fRc = TRUE;
     527            __try
    319528            {
    320                 free(lpszPlatformCur);
    321                 lpszPlatformCur = NULL;
    322                 continue;
     529                fRc = SetupUninstallOEMInfW(pwszFileName, pContext->fFlags, /* could be SUOI_FORCEDELETE */ NULL /* Reserved */);
    323530            }
    324 
    325             bNt = true;
    326         }
    327         else
    328         {
    329             bArch = true;
    330         }
    331 
    332         cPlatform = cPlatformCur;
    333         if(lpszPlatform)
    334             free(lpszPlatform);
    335         lpszPlatform = lpszPlatformCur;
    336         lpszPlatformCur = NULL;
    337     }
    338 
    339     hr = S_OK;
    340 
    341     if (lpszPlatform)
    342     {
    343         lpszResult = (LPWSTR)malloc((cModels + cPlatform) * sizeof (lpszResult[0]));
    344         if (lpszResult)
    345         {
    346             memcpy(lpszResult, lpszModels, (cModels - 1) * sizeof (lpszResult[0]));
    347             *(lpszResult + cModels - 1) = L'.';
    348             memcpy(lpszResult + cModels, lpszPlatform, cPlatform * sizeof (lpszResult[0]));
    349             cResult = cModels + cPlatform;
    350         }
    351         else
    352         {
    353             hr = E_FAIL;
    354         }
     531            __except(hrc = GetExceptionCode(), EXCEPTION_EXECUTE_HANDLER)
     532            {
     533                NonStandardLogRelCrap((__FUNCTION__ ": SetupUninstallOEMInf raised an exception: %#x\n", hrc));
     534                hrc = E_ABORT;
     535            }
     536            if (!fRc)
     537#endif
     538            {
     539                DWORD const dwErr = GetLastError();
     540                NonStandardLogRelCrap((__FUNCTION__ ": SetupUninstallOEMInf failed for file (%ls), dwErr=%u\n", pwszFileName, dwErr));
     541                NonStandardAssertFailed();
     542                hrc = HRESULT_FROM_WIN32( dwErr );
     543            }
     544        }
     545
     546        RTMemFree(pwszPnPId);
    355547    }
    356548    else
    357     {
    358         lpszResult = lpszModels;
    359         cResult = cModels;
    360         lpszModels = NULL;
    361     }
    362 
    363     if (lpszModels)
    364         free(lpszModels);
    365     if (lpszPlatform)
    366         free(lpszPlatform);
    367 
    368     if (hr == S_OK)
    369     {
    370         *lppszValue = lpszResult;
    371         if (pcValue)
    372             *pcValue = cResult;
    373     }
    374 
    375     return hr;
    376 }
    377 
    378 static HRESULT vboxDrvCfgInfQueryFirstPnPId(HINF hInf, LPWSTR *lppszPnPId)
    379 {
    380     *lppszPnPId = NULL;
    381 
    382     LPWSTR lpszModels;
    383     HRESULT hr = vboxDrvCfgInfQueryModelsSectionName(hInf, &lpszModels, NULL);
    384     NonStandardLogRelCrap((__FUNCTION__ ": vboxDrvCfgInfQueryModelsSectionName returned lpszModels = (%S)", lpszModels));
    385     if (hr != S_OK)
    386     {
    387         NonStandardLogCrap((__FUNCTION__ ": vboxDrvCfgRegQueryKeyValue for Manufacturer failed, hr=0x%x\n", hr));
    388         return hr;
    389     }
    390 
    391     LPWSTR lpszPnPId = NULL;
    392     INFCONTEXT InfCtx;
    393     hr = vboxDrvCfgInfQueryContext(hInf, lpszModels, NULL, &InfCtx);
    394     if (hr != S_OK)
    395     {
    396         NonStandardLogRelCrap((__FUNCTION__ ": vboxDrvCfgInfQueryContext for models (%S) failed, hr=0x%x\n", lpszModels, hr));
    397     }
    398     else
    399     {
    400         hr = vboxDrvCfgInfQueryKeyValue(&InfCtx, 2, &lpszPnPId, NULL);
    401         NonStandardLogRelCrap((__FUNCTION__ ": vboxDrvCfgRegQueryKeyValue for models (%S) returned lpszPnPId (%S) \n", lpszModels, lpszPnPId));
    402 
    403         if (hr != S_OK)
    404             NonStandardLogRelCrap((__FUNCTION__ ": vboxDrvCfgRegQueryKeyValue for models (%S) failed, hr=0x%x\n", lpszModels, hr));
    405     }
    406     /* free models string right away */
    407     free(lpszModels);
    408     if (hr != S_OK)
    409         return hr;
    410 
    411     *lppszPnPId = lpszPnPId;
     549        NonStandardLogCrap((__FUNCTION__ ": vboxDrvCfgInfQueryFirstPnPId failed, hrc=0x%x\n", hrc));
     550
     551    SetupCloseInfFile(hInf);
     552    return true;
     553}
     554
     555
     556#define VBOXDRVCFG_S_INFEXISTS (HRESULT_FROM_WIN32(ERROR_FILE_EXISTS))
     557
     558static HRESULT vboxDrvCfgInfCopyEx(IN LPCWSTR pwszInfPath, IN DWORD fCopyStyle, OUT LPWSTR pwszDstName, IN DWORD cwcDstName,
     559                                   OUT PDWORD pcwcDstNameRet, OUT LPWSTR *pwszDstNameComponent)
     560{
     561    /* Extract the director from pwszInfPath */
     562    size_t cchPath = RTUtf16Len(pwszInfPath);
     563    while (cchPath > 0 && !RTPATH_IS_SEP(pwszInfPath[cchPath - 1]))
     564        cchPath--;
     565
     566    WCHAR *pwszMediaLocation = (WCHAR *)alloca(((cchPath) + 1) * sizeof(pwszMediaLocation[0]));
     567    memcpy(pwszMediaLocation, pwszInfPath, cchPath * sizeof(pwszMediaLocation[0]));
     568    pwszMediaLocation[cchPath] = '\0';
     569
     570
     571    if (!SetupCopyOEMInfW(pwszInfPath, pwszMediaLocation, SPOST_PATH, fCopyStyle,
     572                          pwszDstName, cwcDstName, pcwcDstNameRet, pwszDstNameComponent))
     573    {
     574        DWORD const dwErr = GetLastError();
     575        HRESULT hrc = HRESULT_FROM_WIN32(dwErr);
     576        if (fCopyStyle != SP_COPY_REPLACEONLY || hrc != VBOXDRVCFG_S_INFEXISTS)
     577            NonStandardLogRelCrap((__FUNCTION__ ": SetupCopyOEMInf fail dwErr=%u\n", dwErr));
     578        return hrc;
     579    }
     580
    412581    return S_OK;
    413582}
    414583
    415 static bool vboxDrvCfgInfEnumerationCallback(LPCWSTR lpszFileName, PVOID pCtxt);
    416 
    417 #define VBOXDRVCFG_S_INFEXISTS (HRESULT_FROM_WIN32(ERROR_FILE_EXISTS))
    418 
    419 static HRESULT vboxDrvCfgInfCopyEx(IN LPCWSTR lpszInfPath, IN DWORD fCopyStyle, OUT LPWSTR lpszDstName, IN DWORD cbDstName, OUT PDWORD pcbDstNameSize, OUT LPWSTR* lpszDstNameComponent)
    420 {
    421     WCHAR aMediaLocation[_MAX_DIR];
    422     WCHAR aDir[_MAX_DIR];
    423 
    424     _wsplitpath(lpszInfPath, aMediaLocation, aDir, NULL, NULL);
    425     wcscat(aMediaLocation, aDir);
    426 
    427     if (!SetupCopyOEMInfW(lpszInfPath, aMediaLocation, SPOST_PATH, fCopyStyle,
    428             lpszDstName, cbDstName, pcbDstNameSize,
    429             lpszDstNameComponent))
    430     {
    431         DWORD dwErr = GetLastError();
    432         HRESULT hr = HRESULT_FROM_WIN32(dwErr);
    433         if (fCopyStyle != SP_COPY_REPLACEONLY || hr != VBOXDRVCFG_S_INFEXISTS)
    434         {
    435             NonStandardLogRelCrap((__FUNCTION__ ": SetupCopyOEMInf fail dwErr=%ld\n", dwErr));
    436         }
    437         return hr;
    438     }
    439 
     584VBOXDRVCFG_DECL(HRESULT) VBoxDrvCfgInfInstall(IN LPCWSTR pwszInfPath)
     585{
     586    return vboxDrvCfgInfCopyEx(pwszInfPath, 0 /*fCopyStyle*/, NULL /*pwszDstName*/, 0 /*cwcDstName*/,
     587                               NULL /*pcwcDstNameRet*/, NULL /*pwszDstNameComponent*/);
     588}
     589
     590VBOXDRVCFG_DECL(HRESULT) VBoxDrvCfgInfUninstall(IN LPCWSTR pwszInfPath, DWORD fFlags)
     591{
     592    WCHAR   wszDstInfName[MAX_PATH];
     593    DWORD   cwcDword = RT_ELEMENTS(wszDstInfName);
     594    HRESULT hrc = vboxDrvCfgInfCopyEx(pwszInfPath, SP_COPY_REPLACEONLY, wszDstInfName, cwcDword, &cwcDword, NULL);
     595    if (hrc == VBOXDRVCFG_S_INFEXISTS)
     596    {
     597        if (!SetupUninstallOEMInfW(wszDstInfName, fFlags, NULL /*Reserved*/))
     598        {
     599            DWORD dwErr = GetLastError();
     600            NonStandardLogRelCrap((__FUNCTION__ ": SetupUninstallOEMInf failed for file (%ls), oem(%ls), dwErr=%u\n",
     601                                   pwszInfPath, wszDstInfName, dwErr));
     602            NonStandardAssertFailed();
     603            return HRESULT_FROM_WIN32(dwErr);
     604        }
     605    }
    440606    return S_OK;
    441607}
    442608
    443 static HRESULT vboxDrvCfgInfCopy(IN LPCWSTR lpszInfPath)
    444 {
    445     return vboxDrvCfgInfCopyEx(lpszInfPath, 0, NULL, 0, NULL, NULL);
    446 }
    447 
    448 VBOXDRVCFG_DECL(HRESULT) VBoxDrvCfgInfInstall(IN LPCWSTR lpszInfPath)
    449 {
    450     return vboxDrvCfgInfCopy(lpszInfPath);
    451 }
    452 
    453 VBOXDRVCFG_DECL(HRESULT) VBoxDrvCfgInfUninstall(IN LPCWSTR lpszInfPath, DWORD fFlags)
    454 {
    455     WCHAR DstInfName[MAX_PATH];
    456     DWORD cbDword = sizeof (DstInfName);
    457     HRESULT hr = vboxDrvCfgInfCopyEx(lpszInfPath, SP_COPY_REPLACEONLY, DstInfName, cbDword, &cbDword, NULL);
    458     if (hr == VBOXDRVCFG_S_INFEXISTS)
    459     {
    460         if (!SetupUninstallOEMInfW(DstInfName, fFlags, NULL /*__in PVOID Reserved == NULL */))
    461         {
    462             DWORD dwErr = GetLastError();
    463             NonStandardLogRelCrap((__FUNCTION__ ": SetupUninstallOEMInf failed for file (%S), oem(%S), dwErr=%ld\n", lpszInfPath, DstInfName, dwErr));
    464             NonStandardAssert(0);
    465             return HRESULT_FROM_WIN32(dwErr);
    466         }
    467     }
    468     return S_OK;
    469 }
    470 
    471 
    472 static HRESULT vboxDrvCfgCollectInfsSetupDi(const GUID * pGuid, LPCWSTR pPnPId, VBoxDrvCfgStringList & list)
    473 {
    474     DWORD dwErr = ERROR_SUCCESS;
    475     HDEVINFO hDevInfo = SetupDiCreateDeviceInfoList(
    476                             pGuid, /* IN LPGUID ClassGuid, OPTIONAL */
    477                             NULL /*IN HWND hwndParent OPTIONAL */
    478                             );
     609
     610static HRESULT vboxDrvCfgCollectInfsSetupDi(const GUID *pGuid, LPCWSTR pwszPnPId, VBoxDrvCfgStringList &a_rList)
     611{
     612    DWORD dwErrRet = ERROR_SUCCESS;
     613    HDEVINFO hDevInfo = SetupDiCreateDeviceInfoList(pGuid, /*ClassGuid*/ NULL /*hwndParent*/);
    479614    if (hDevInfo != INVALID_HANDLE_VALUE)
    480615    {
    481         if (SetupDiBuildDriverInfoList(hDevInfo,
    482                     NULL, /*IN OUT PSP_DEVINFO_DATA DeviceInfoData, OPTIONAL*/
    483                     SPDIT_CLASSDRIVER  /*IN DWORD DriverType*/
    484                     ))
     616        /** @todo bird/2020-09-01: seeing this during uninstall when windbg is
     617         * attached to msiexec.exe (see trick in DllMain):
     618         *
     619         *    (1b238.1b254): Access violation - code c0000005 (first chance)
     620         *    First chance exceptions are reported before any exception handling.
     621         *    This exception may be expected and handled.
     622         *    SETUPAPI!SpSignVerifyInfFile+0x246:
     623         *    00007ffa`83e3ee3e 663907          cmp     word ptr [rdi],ax ds:00000000`00000000=????
     624         *    0:006> k
     625         *     # Child-SP          RetAddr           Call Site
     626         *    00 00000099`6e4f8340 00007ffa`83e1e765 SETUPAPI!SpSignVerifyInfFile+0x246
     627         *    01 00000099`6e4f8420 00007ffa`83e9ebfd SETUPAPI!DrvSearchCallback+0x1155
     628         *    02 00000099`6e4f9380 00007ffa`83e9eed3 SETUPAPI!InfCacheSearchDirectory+0x469
     629         *    03 00000099`6e4f98b0 00007ffa`83e9f454 SETUPAPI!InfCacheSearchDirectoryRecursive+0xcf
     630         *    04 00000099`6e4f9fe0 00007ffa`83e9da10 SETUPAPI!InfCacheSearchPath+0x1a0
     631         *    05 00000099`6e4fa2b0 00007ffa`83e262a2 SETUPAPI!EnumDrvInfsInDirPathList+0x560
     632         *    06 00000099`6e4fa3f0 00007ffa`57a39a21 SETUPAPI!SetupDiBuildDriverInfoList+0x1242
     633         *    07 00000099`6e4fab10 00007ffa`57a3ad6e MSID039!vboxDrvCfgCollectInfsSetupDi+0x71 [E:\vbox\svn\trunk\src\VBox\HostDrivers\win\cfg\VBoxDrvCfg.cpp @ 526]
     634         *    08 00000099`6e4ff1c0 00007ffa`57a321e6 MSID039!VBoxDrvCfgInfUninstallAllSetupDi+0x5e [E:\vbox\svn\trunk\src\VBox\HostDrivers\win\cfg\VBoxDrvCfg.cpp @ 633]
     635         *    09 (Inline Function) --------`-------- MSID039!_removeHostOnlyInterfaces+0x6c [E:\vbox\svn\trunk\src\VBox\Installer\win\InstallHelper\VBoxInstallHelper.cpp @ 1523]
     636         *    0a 00000099`6e4ff240 00007ffa`610f59d3 MSID039!RemoveHostOnlyInterfaces+0x76 [E:\vbox\svn\trunk\src\VBox\Installer\win\InstallHelper\VBoxInstallHelper.cpp @ 1545]
     637         *    0b 00000099`6e4ff270 00007ffa`610d80ac msi!CallCustomDllEntrypoint+0x2b
     638         *    0c 00000099`6e4ff2e0 00007ffa`84567034 msi!CMsiCustomAction::CustomActionThread+0x34c
     639         *    0d 00000099`6e4ff8d0 00007ffa`849a2651 KERNEL32!BaseThreadInitThunk+0x14
     640         *    0e 00000099`6e4ff900 00000000`00000000 ntdll!RtlUserThreadStart+0x21
     641         *    0:006> r
     642         *    rax=0000000000000000 rbx=0000000000000490 rcx=aa222a2675da0000
     643         *    rdx=0000000000000000 rsi=0000000000000000 rdi=0000000000000000
     644         *    rip=00007ffa83e3ee3e rsp=000000996e4f8340 rbp=000000996e4f9480
     645         *     r8=0000000000050004  r9=00007ffa83ef5418 r10=0000000000008000
     646         *    r11=000000996e4f76f0 r12=000000996e4f84c8 r13=0000000000000000
     647         *    r14=000000996e4f88d0 r15=0000000000000000
     648         *    iopl=0         nv up ei pl nz ac pe cy
     649         *    cs=0033  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010213
     650         *    SETUPAPI!SpSignVerifyInfFile+0x246:
     651         *    00007ffa`83e3ee3e 663907          cmp     word ptr [rdi],ax ds:00000000`00000000=????
     652          */
     653#if 0
     654        if (SetupDiBuildDriverInfoList(hDevInfo, NULL /*DeviceInfoData*/, SPDIT_CLASSDRIVER))
     655#else   /* Just in case the API doesn't catch it itself (seems it does on w10/19044).  */
     656        BOOL fRc = FALSE;
     657        DWORD uXcpt = 0;
     658        __try
     659        {
     660            fRc = SetupDiBuildDriverInfoList(hDevInfo, NULL /*DeviceInfoData*/, SPDIT_CLASSDRIVER);
     661        }
     662        __except(uXcpt = GetExceptionCode(), EXCEPTION_EXECUTE_HANDLER)
     663        {
     664            NonStandardLogRelCrap((__FUNCTION__ ": SetupDiBuildDriverInfoList raised an exception: %#x\n", uXcpt));
     665        }
     666        if (fRc)
     667#endif
    485668        {
    486669            SP_DRVINFO_DATA DrvInfo;
    487670            DrvInfo.cbSize = sizeof(SP_DRVINFO_DATA);
    488             char DetailBuf[16384];
    489             PSP_DRVINFO_DETAIL_DATA pDrvDetail = (PSP_DRVINFO_DETAIL_DATA)DetailBuf;
    490 
    491             for (DWORD i = 0; ; i++)
     671
     672            union
    492673            {
    493                 if (SetupDiEnumDriverInfo(hDevInfo,
    494                         NULL, /* IN PSP_DEVINFO_DATA DeviceInfoData, OPTIONAL*/
    495                         SPDIT_CLASSDRIVER , /*IN DWORD DriverType,*/
    496                         i, /*IN DWORD MemberIndex,*/
    497                         &DrvInfo /*OUT PSP_DRVINFO_DATA DriverInfoData*/
    498                         ))
     674                SP_DRVINFO_DETAIL_DATA_W s;
     675                uint8_t ab[16384];
     676            } DrvDetail;
     677
     678            /* Ensure zero terminated buffer: */
     679            DrvDetail.ab[sizeof(DrvDetail) - 1] = '\0';
     680            DrvDetail.ab[sizeof(DrvDetail) - 2] = '\0';
     681
     682            for (DWORD i = 0; dwErrRet == ERROR_SUCCESS; i++)
     683            {
     684                if (SetupDiEnumDriverInfo(hDevInfo, NULL /*DeviceInfoData*/, SPDIT_CLASSDRIVER /*DriverType*/,
     685                                          i /*MemberIndex*/, &DrvInfo /*DriverInfoData*/))
    499686                {
    500                     DWORD dwReq;
    501                     pDrvDetail->cbSize = sizeof(SP_DRVINFO_DETAIL_DATA);
    502                     if (SetupDiGetDriverInfoDetail(
    503                             hDevInfo, /*IN HDEVINFO DeviceInfoSet,*/
    504                             NULL, /*IN PSP_DEVINFO_DATA DeviceInfoData, OPTIONAL*/
    505                             &DrvInfo, /*IN PSP_DRVINFO_DATA DriverInfoData,*/
    506                             pDrvDetail, /*OUT PSP_DRVINFO_DETAIL_DATA DriverInfoDetailData, OPTIONAL*/
    507                             sizeof(DetailBuf), /*IN DWORD DriverInfoDetailDataSize,*/
    508                             &dwReq /*OUT PDWORD RequiredSize OPTIONAL*/
    509                             ))
     687                    DWORD dwReq = 0;
     688                    DrvDetail.s.cbSize = sizeof(SP_DRVINFO_DETAIL_DATA);
     689                    if (SetupDiGetDriverInfoDetail(hDevInfo, NULL /*DeviceInfoData*/, &DrvInfo,
     690                                                   &DrvDetail.s, sizeof(DrvDetail) - 2 /*our terminator*/, &dwReq))
    510691                    {
    511                         for (WCHAR *pwszHwId = pDrvDetail->HardwareID;
    512                              pwszHwId && *pwszHwId && (uintptr_t)pwszHwId < (uintptr_t)DetailBuf + sizeof(DetailBuf);
    513                              pwszHwId += wcslen(pwszHwId) + 1)
     692                        for (WCHAR *pwszHwId = DrvDetail.s.HardwareID;
     693                             *pwszHwId != '\0' && (uintptr_t)pwszHwId < (uintptr_t)&DrvDetail.ab[sizeof(DrvDetail)];
     694                             pwszHwId += RTUtf16Len(pwszHwId) + 1)
    514695                        {
    515                             if (!wcsicmp(pwszHwId, pPnPId))
     696                            if (RTUtf16ICmp(pwszHwId, pwszPnPId) == 0)
    516697                            {
    517                                 NonStandardAssert(pDrvDetail->InfFileName[0]);
    518                                 if (pDrvDetail->InfFileName)
     698                                NonStandardAssert(DrvDetail.s.InfFileName[0]);
     699                                if (DrvDetail.s.InfFileName[0])
    519700                                {
    520                                     list.add(pDrvDetail->InfFileName);
    521                                     NonStandardLogRelCrap((__FUNCTION__": %S added to list", pDrvDetail->InfFileName));
     701                                    HRESULT hrc = a_rList.add(DrvDetail.s.InfFileName);
     702                                    NonStandardLogRelCrap((__FUNCTION__": %ls added to list (%#x)", DrvDetail.s.InfFileName, hrc));
     703                                    if (hrc != S_OK)
     704                                    {
     705                                        dwErrRet = ERROR_OUTOFMEMORY;
     706                                        break;
     707                                    }
    522708                                }
    523709                            }
     
    527713                    {
    528714                        DWORD dwErr2 = GetLastError();
    529                         NonStandardLogRelCrap((__FUNCTION__": SetupDiGetDriverInfoDetail fail dwErr=%ld, size(%d)", dwErr2, dwReq));
    530 //                        NonStandardAssert(0);
     715                        NonStandardLogRelCrap((__FUNCTION__": SetupDiGetDriverInfoDetail fail dwErr=%u, size(%d)", dwErr2, dwReq));
     716//                        NonStandardAssertFailed();
    531717                    }
    532 
    533718                }
    534719                else
     
    540725                        break;
    541726                    }
    542 
    543                     NonStandardAssert(0);
     727                    NonStandardAssertFailed();
    544728                }
    545729            }
    546730
    547             SetupDiDestroyDriverInfoList(hDevInfo,
    548                       NULL, /*IN PSP_DEVINFO_DATA DeviceInfoData, OPTIONAL*/
    549                       SPDIT_CLASSDRIVER/*IN DWORD DriverType*/
    550                       );
     731            SetupDiDestroyDriverInfoList(hDevInfo, NULL /*DeviceInfoData*/, SPDIT_CLASSDRIVER);
    551732        }
    552733        else
    553734        {
    554             dwErr = GetLastError();
    555             NonStandardAssert(0);
     735            dwErrRet = GetLastError();
     736            NonStandardAssertFailed();
    556737        }
    557738
     
    560741    else
    561742    {
    562         dwErr = GetLastError();
    563         NonStandardAssert(0);
    564     }
    565 
    566     return HRESULT_FROM_WIN32(dwErr);
     743        dwErrRet = GetLastError();
     744        NonStandardAssertFailed();
     745    }
     746
     747    return HRESULT_FROM_WIN32(dwErrRet);
    567748}
    568749
     
    586767#endif
    587768
    588 VBOXDRVCFG_DECL(HRESULT) VBoxDrvCfgInfUninstallAllSetupDi(IN const GUID * pGuidClass, IN LPCWSTR lpszClassName, IN LPCWSTR lpszPnPId, IN DWORD Flags)
     769VBOXDRVCFG_DECL(HRESULT) VBoxDrvCfgInfUninstallAllSetupDi(IN const GUID *pGuidClass, IN LPCWSTR pwszClassName,
     770                                                          IN LPCWSTR pwszPnPId, IN DWORD fFlags)
    589771{
    590772    VBoxDrvCfgStringList list(128);
    591     HRESULT hr = vboxDrvCfgCollectInfsSetupDi(pGuidClass, lpszPnPId, list);
    592     NonStandardLogRelCrap((__FUNCTION__": vboxDrvCfgCollectInfsSetupDi returned %d devices with PnPId %S and class name %S", list.size(), lpszPnPId, lpszClassName));
    593     if (hr == S_OK)
    594     {
    595         INFENUM_CONTEXT Context;
    596         Context.InfInfo.lpszClassName = lpszClassName;
    597         Context.InfInfo.lpszPnPId = lpszPnPId;
    598         Context.Flags = Flags;
    599         Context.hr = S_OK;
    600         int size = list.size();
    601         for (int i = 0; i < size; ++i)
    602         {
    603             LPCWSTR pInf = list.get(i);
    604             const WCHAR* pRel = wcsrchr(pInf, '\\');
    605             if (pRel)
    606                 ++pRel;
    607             else
    608                 pRel = pInf;
    609 
    610             vboxDrvCfgInfEnumerationCallback(pRel, &Context);
    611             NonStandardLogRelCrap((__FUNCTION__": inf = %S\n", list.get(i)));
    612         }
    613     }
    614     return hr;
    615 }
    616 
    617 static HRESULT vboxDrvCfgEnumFiles(LPCWSTR pPattern, PFNVBOXNETCFG_ENUMERATION_CALLBACK pfnCallback, PVOID pContext)
    618 {
    619     WIN32_FIND_DATA Data;
    620     memset(&Data, 0, sizeof(Data));
    621     HRESULT hr = S_OK;
    622 
    623     HANDLE hEnum = FindFirstFile(pPattern,&Data);
     773    HRESULT hrc = vboxDrvCfgCollectInfsSetupDi(pGuidClass, pwszPnPId, list);
     774    NonStandardLogRelCrap((__FUNCTION__": vboxDrvCfgCollectInfsSetupDi returned %d devices with PnPId %ls and class name %ls",
     775                           list.size(), pwszPnPId, pwszClassName));
     776    if (hrc == S_OK)
     777    {
     778        INFENUM_CONTEXT_T Context;
     779        Context.InfInfo.pwszClassName = pwszClassName;
     780        Context.InfInfo.pwszPnPId = pwszPnPId;
     781        Context.fFlags = fFlags;
     782        Context.hrc = S_OK;
     783        size_t const cItems = list.size();
     784        for (size_t i = 0; i < cItems; ++i)
     785        {
     786            LPCWSTR pwszInf = list.get(i);
     787
     788            /* Find the start of the filename: */
     789            size_t offFilename = RTUtf16Len(pwszInf);
     790            while (offFilename > 0 && !RTPATH_IS_SEP(pwszInf[offFilename - 1]))
     791                offFilename--;
     792
     793            vboxDrvCfgInfEnumerationCallback(&pwszInf[offFilename], &Context);
     794            NonStandardLogRelCrap((__FUNCTION__": inf = %ls\n", pwszInf));
     795        }
     796    }
     797    return hrc;
     798}
     799
     800static HRESULT vboxDrvCfgEnumFiles(LPCWSTR pwszDirAndPattern, PFNVBOXNETCFG_ENUMERATION_CALLBACK_T pfnCallback, PVOID pContext)
     801{
     802    HRESULT hrc = S_OK;
     803
     804    WIN32_FIND_DATAW Data;
     805    RT_ZERO(Data);
     806    HANDLE hEnum = FindFirstFileW(pwszDirAndPattern, &Data);
    624807    if (hEnum != INVALID_HANDLE_VALUE)
    625808    {
    626 
    627         do
     809        for (;;)
    628810        {
    629811            if (!pfnCallback(Data.cFileName, pContext))
    630             {
    631812                break;
    632             }
    633813
    634814            /* next iteration */
    635             memset(&Data, 0, sizeof(Data));
    636             BOOL bNext = FindNextFile(hEnum,&Data);
    637             if (!bNext)
     815            RT_ZERO(Data);
     816            BOOL fNext = FindNextFile(hEnum, &Data);
     817            if (!fNext)
    638818            {
    639819                DWORD dwErr = GetLastError();
    640820                if (dwErr != ERROR_NO_MORE_FILES)
    641821                {
    642                     NonStandardLogRelCrap((__FUNCTION__": FindNextFile fail dwErr=%ld\n", dwErr));
    643                     NonStandardAssert(0);
    644                     hr = HRESULT_FROM_WIN32(dwErr);
     822                    NonStandardLogRelCrap((__FUNCTION__": FindNextFile fail dwErr=%u\n", dwErr));
     823                    NonStandardAssertFailed();
     824                    hrc = HRESULT_FROM_WIN32(dwErr);
    645825                }
    646826                break;
    647827            }
    648         }while (true);
     828        }
     829
    649830        FindClose(hEnum);
    650831    }
     
    654835        if (dwErr != ERROR_NO_MORE_FILES)
    655836        {
    656             NonStandardLogRelCrap((__FUNCTION__": FindFirstFile fail dwErr=%ld\n", dwErr));
    657             NonStandardAssert(0);
    658             hr = HRESULT_FROM_WIN32(dwErr);
    659         }
    660     }
    661 
    662     return hr;
    663 }
    664 
    665 static bool vboxDrvCfgInfEnumerationCallback(LPCWSTR lpszFileName, PVOID pCtxt)
    666 {
    667     PINFENUM_CONTEXT pContext = (PINFENUM_CONTEXT)pCtxt;
    668     DWORD dwErr;
    669     NonStandardLogRelCrap((__FUNCTION__": lpszFileName (%S)\n", lpszFileName));
    670     NonStandardLogRelCrap((__FUNCTION__ ": pContext->InfInfo.lpszClassName = (%S)\n", pContext->InfInfo.lpszClassName));
    671     HINF hInf = SetupOpenInfFileW(lpszFileName, pContext->InfInfo.lpszClassName, INF_STYLE_WIN4, NULL /*__in PUINT ErrorLine */);
    672     if (hInf == INVALID_HANDLE_VALUE)
    673     {
    674         dwErr = GetLastError();
    675 //        NonStandardAssert(dwErr == ERROR_CLASS_MISMATCH);
    676         if (dwErr != ERROR_CLASS_MISMATCH)
    677         {
    678             NonStandardLogCrap((__FUNCTION__ ": SetupOpenInfFileW err dwErr=%ld\n", dwErr));
    679         }
     837            NonStandardLogRelCrap((__FUNCTION__": FindFirstFile fail dwErr=%u\n", dwErr));
     838            NonStandardAssertFailed();
     839            hrc = HRESULT_FROM_WIN32(dwErr);
     840        }
     841    }
     842
     843    return hrc;
     844}
     845
     846VBOXDRVCFG_DECL(HRESULT) VBoxDrvCfgInfUninstallAllF(LPCWSTR pwszClassName, LPCWSTR pwszPnPId, DWORD fFlags)
     847{
     848    static WCHAR const s_wszFilter[] = L"\\inf\\oem*.inf";
     849
     850    HRESULT hrc;
     851    WCHAR   wszInfDirPath[MAX_PATH];
     852    UINT    cwcInput = RT_ELEMENTS(wszInfDirPath) - RT_ELEMENTS(s_wszFilter);
     853    UINT    cwcWindows = GetSystemWindowsDirectoryW(wszInfDirPath, cwcInput);
     854    if (cwcWindows > 0 && cwcWindows < cwcInput)
     855    {
     856        RTUtf16Copy(&wszInfDirPath[cwcWindows], RT_ELEMENTS(wszInfDirPath) - cwcWindows, s_wszFilter);
     857
     858        INFENUM_CONTEXT_T Context;
     859        Context.InfInfo.pwszClassName = pwszClassName;
     860        Context.InfInfo.pwszPnPId = pwszPnPId;
     861        Context.fFlags = fFlags;
     862        Context.hrc = S_OK;
     863        NonStandardLogRelCrap((__FUNCTION__": Calling vboxDrvCfgEnumFiles(wszInfDirPath, vboxDrvCfgInfEnumerationCallback, &Context)"));
     864        hrc = vboxDrvCfgEnumFiles(wszInfDirPath, vboxDrvCfgInfEnumerationCallback, &Context);
     865        NonStandardAssert(hrc == S_OK);
     866        if (hrc == S_OK)
     867            hrc = Context.hrc;
    680868        else
    681         {
    682             NonStandardLogCrap((__FUNCTION__ ": dwErr == ERROR_CLASS_MISMATCH\n"));
    683         }
    684         return true;
    685     }
    686 
    687     LPWSTR lpszPnPId;
    688     HRESULT hr = vboxDrvCfgInfQueryFirstPnPId(hInf, &lpszPnPId);
    689     NonStandardLogRelCrap((__FUNCTION__ ": vboxDrvCfgInfQueryFirstPnPId returned lpszPnPId = (%S)\n", lpszPnPId));
    690     NonStandardLogRelCrap((__FUNCTION__ ": pContext->InfInfo.lpszPnPId = (%S)\n", pContext->InfInfo.lpszPnPId));
    691     if (hr == S_OK)
    692     {
    693         if (!wcsicmp(pContext->InfInfo.lpszPnPId, lpszPnPId))
    694         {
    695             if (!SetupUninstallOEMInfW(lpszFileName,
    696                         pContext->Flags, /*DWORD Flags could be SUOI_FORCEDELETE */
    697                         NULL /*__in PVOID Reserved == NULL */
    698                         ))
    699             {
    700                 dwErr = GetLastError();
    701                 NonStandardLogRelCrap((__FUNCTION__ ": SetupUninstallOEMInf failed for file (%S), dwErr=%ld\n", lpszFileName, dwErr));
    702                 NonStandardAssert(0);
    703                 hr = HRESULT_FROM_WIN32( dwErr );
    704             }
    705         }
    706 
    707         free(lpszPnPId);
    708     }
    709     else
    710     {
    711         NonStandardLogCrap((__FUNCTION__ ": vboxDrvCfgInfQueryFirstPnPId failed, hr=0x%x\n", hr));
    712     }
    713 
    714     SetupCloseInfFile(hInf);
    715 
    716     return true;
    717 }
    718 
    719 VBOXDRVCFG_DECL(HRESULT) VBoxDrvCfgInfUninstallAllF(LPCWSTR lpszClassName, LPCWSTR lpszPnPId, DWORD Flags)
    720 {
    721     static WCHAR const s_wszFilter[] = L"\\inf\\oem*.inf";
    722     HRESULT hr;
    723     WCHAR wszInfDirPath[MAX_PATH];
    724     UINT cwcInput = RT_ELEMENTS(wszInfDirPath) - RT_ELEMENTS(s_wszFilter);
    725     UINT cwcWindows = GetSystemWindowsDirectory(wszInfDirPath, cwcInput);
    726     if (cwcWindows > 0 && cwcWindows < cwcInput)
    727     {
    728         wcscpy(&wszInfDirPath[cwcWindows], s_wszFilter);
    729 
    730         INFENUM_CONTEXT Context;
    731         Context.InfInfo.lpszClassName = lpszClassName;
    732         Context.InfInfo.lpszPnPId = lpszPnPId;
    733         Context.Flags = Flags;
    734         Context.hr = S_OK;
    735         NonStandardLogRelCrap((__FUNCTION__": Calling vboxDrvCfgEnumFiles(wszInfDirPath, vboxDrvCfgInfEnumerationCallback, &Context)"));
    736         hr = vboxDrvCfgEnumFiles(wszInfDirPath, vboxDrvCfgInfEnumerationCallback, &Context);
    737         NonStandardAssert(hr == S_OK);
    738         if (hr == S_OK)
    739         {
    740             hr = Context.hr;
    741         }
    742         else
    743         {
    744             NonStandardLogRelCrap((__FUNCTION__": vboxDrvCfgEnumFiles failed, hr=0x%x\n", hr));
    745         }
     869            NonStandardLogRelCrap((__FUNCTION__": vboxDrvCfgEnumFiles failed, hrc=0x%x\n", hrc));
    746870    }
    747871    else
     
    749873        NonStandardLogRelCrap((__FUNCTION__": GetSystemWindowsDirectory failed, cwcWindows=%u lasterr=%u\n", cwcWindows, GetLastError()));
    750874        NonStandardAssertFailed();
    751         hr = E_FAIL;
    752     }
    753 
    754     return hr;
     875        hrc = E_FAIL;
     876    }
     877
     878    return hrc;
    755879
    756880}
     
    764888#define VBOXDRVCFG_SVC_WAITSTART_RETRIES (VBOXDRVCFG_SVC_WAITSTART_TIME/VBOXDRVCFG_SVC_WAITSTART_TIME_PERIOD)
    765889
    766 VBOXDRVCFG_DECL(HRESULT) VBoxDrvCfgSvcStart(LPCWSTR lpszSvcName)
    767 {
    768     SC_HANDLE hMgr = OpenSCManager(NULL, NULL, SERVICE_QUERY_STATUS | SERVICE_START);
     890VBOXDRVCFG_DECL(HRESULT) VBoxDrvCfgSvcStart(LPCWSTR pwszSvcName)
     891{
     892    SC_HANDLE hMgr = OpenSCManagerW(NULL, NULL, SERVICE_QUERY_STATUS | SERVICE_START);
    769893    if (hMgr == NULL)
    770894    {
    771895        DWORD dwErr = GetLastError();
    772         NonStandardLogRelCrap((__FUNCTION__": OpenSCManager failed, dwErr=%ld\n", dwErr));
     896        NonStandardLogRelCrap((__FUNCTION__": OpenSCManager failed, dwErr=%u\n", dwErr));
    773897        return HRESULT_FROM_WIN32(dwErr);
    774898    }
    775899
    776     HRESULT hr = S_OK;
    777     SC_HANDLE hSvc = OpenServiceW(hMgr, lpszSvcName, SERVICE_QUERY_STATUS | SERVICE_START);
     900    HRESULT hrc = S_OK;
     901    SC_HANDLE hSvc = OpenServiceW(hMgr, pwszSvcName, SERVICE_QUERY_STATUS | SERVICE_START);
    778902    if (hSvc)
    779903    {
    780         do
    781         {
    782             SERVICE_STATUS Status;
    783             BOOL fRc = QueryServiceStatus(hSvc, &Status);
    784             if (!fRc)
    785             {
    786                 DWORD dwErr = GetLastError();
    787                 NonStandardLogRelCrap((__FUNCTION__": QueryServiceStatus failed dwErr=%ld\n", dwErr));
    788                 hr = HRESULT_FROM_WIN32(dwErr);
    789                 break;
    790             }
    791 
     904        SERVICE_STATUS Status;
     905        BOOL fRc = QueryServiceStatus(hSvc, &Status);
     906        if (fRc)
     907        {
    792908            if (Status.dwCurrentState != SERVICE_RUNNING && Status.dwCurrentState != SERVICE_START_PENDING)
    793909            {
    794                 NonStandardLogRelCrap(("Starting service (%S)\n", lpszSvcName));
     910                NonStandardLogRelCrap(("Starting service (%ls)\n", pwszSvcName));
    795911
    796912                fRc = StartService(hSvc, 0, NULL);
     
    798914                {
    799915                    DWORD dwErr = GetLastError();
    800                     NonStandardLogRelCrap((__FUNCTION__": StartService failed dwErr=%ld\n", dwErr));
    801                     hr = HRESULT_FROM_WIN32(dwErr);
    802                     break;
     916                    NonStandardLogRelCrap((__FUNCTION__": StartService failed dwErr=%u\n", dwErr));
     917                    hrc = HRESULT_FROM_WIN32(dwErr);
    803918                }
    804919            }
    805920
    806             fRc = QueryServiceStatus(hSvc, &Status);
    807             if (!fRc)
     921            if (fRc)
    808922            {
    809                 DWORD dwErr = GetLastError();
    810                 NonStandardLogRelCrap((__FUNCTION__": QueryServiceStatus failed dwErr=%ld\n", dwErr));
    811                 hr = HRESULT_FROM_WIN32(dwErr);
    812                 break;
    813             }
    814 
    815             if (Status.dwCurrentState == SERVICE_START_PENDING)
    816             {
    817                 for (int i = 0; i < VBOXDRVCFG_SVC_WAITSTART_RETRIES; ++i)
     923                fRc = QueryServiceStatus(hSvc, &Status);
     924                if (fRc)
    818925                {
    819                     Sleep(VBOXDRVCFG_SVC_WAITSTART_TIME_PERIOD);
    820                     fRc = QueryServiceStatus(hSvc, &Status);
    821                     if (!fRc)
     926                    if (Status.dwCurrentState == SERVICE_START_PENDING)
     927                        for (size_t i = 0; i < VBOXDRVCFG_SVC_WAITSTART_RETRIES; ++i)
     928                        {
     929                            Sleep(VBOXDRVCFG_SVC_WAITSTART_TIME_PERIOD);
     930                            fRc = QueryServiceStatus(hSvc, &Status);
     931                            if (!fRc)
     932                            {
     933                                DWORD dwErr = GetLastError();
     934                                NonStandardLogRelCrap((__FUNCTION__": QueryServiceStatus failed dwErr=%u\n", dwErr));
     935                                hrc = HRESULT_FROM_WIN32(dwErr);
     936                                break;
     937                            }
     938                            if (Status.dwCurrentState != SERVICE_START_PENDING)
     939                                break;
     940                        }
     941
     942                    if (hrc != S_OK || Status.dwCurrentState != SERVICE_RUNNING)
    822943                    {
    823                         DWORD dwErr = GetLastError();
    824                         NonStandardLogRelCrap((__FUNCTION__": QueryServiceStatus failed dwErr=%ld\n", dwErr));
    825                         hr = HRESULT_FROM_WIN32(dwErr);
    826                         break;
     944                        NonStandardLogRelCrap((__FUNCTION__": Failed to start the service\n"));
     945                        hrc = E_FAIL;
    827946                    }
    828                     else if (Status.dwCurrentState != SERVICE_START_PENDING)
    829                         break;
     947                }
     948                else
     949                {
     950                    DWORD dwErr = GetLastError();
     951                    NonStandardLogRelCrap((__FUNCTION__": QueryServiceStatus failed dwErr=%u\n", dwErr));
     952                    hrc = HRESULT_FROM_WIN32(dwErr);
    830953                }
    831954            }
    832 
    833             if (hr != S_OK || Status.dwCurrentState != SERVICE_RUNNING)
    834             {
    835                 NonStandardLogRelCrap((__FUNCTION__": Failed to start the service\n"));
    836                 hr = E_FAIL;
    837                 break;
    838             }
    839 
    840         } while (0);
     955        }
     956        else
     957        {
     958            DWORD dwErr = GetLastError();
     959            NonStandardLogRelCrap((__FUNCTION__": QueryServiceStatus failed dwErr=%u\n", dwErr));
     960            hrc = HRESULT_FROM_WIN32(dwErr);
     961        }
    841962
    842963        CloseServiceHandle(hSvc);
     
    845966    {
    846967        DWORD dwErr = GetLastError();
    847         NonStandardLogRelCrap((__FUNCTION__": OpenServiceW failed, dwErr=%ld\n", dwErr));
    848         hr = HRESULT_FROM_WIN32(dwErr);
     968        NonStandardLogRelCrap((__FUNCTION__": OpenServiceW failed, dwErr=%u\n", dwErr));
     969        hrc = HRESULT_FROM_WIN32(dwErr);
    849970    }
    850971
    851972    CloseServiceHandle(hMgr);
    852 
    853     return hr;
    854 }
    855 
    856 
    857 HRESULT VBoxDrvCfgDrvUpdate(LPCWSTR pcszwHwId, LPCWSTR pcsxwInf, BOOL *pbRebootRequired)
    858 {
    859     if (pbRebootRequired)
    860         *pbRebootRequired = FALSE;
    861     BOOL bRebootRequired = FALSE;
    862     WCHAR InfFullPath[MAX_PATH];
    863     DWORD dwChars = GetFullPathNameW(pcsxwInf,
    864             sizeof (InfFullPath) / sizeof (InfFullPath[0]),
    865             InfFullPath,
    866             NULL /* LPTSTR *lpFilePart */
    867             );
     973    return hrc;
     974}
     975
     976
     977HRESULT VBoxDrvCfgDrvUpdate(LPCWSTR pszwHwId, LPCWSTR psxwInf, BOOL *pfRebootRequired)
     978{
     979    if (pfRebootRequired)
     980        *pfRebootRequired = FALSE;
     981
     982    WCHAR wszInfFullPath[MAX_PATH];
     983    DWORD dwChars = GetFullPathNameW(psxwInf, MAX_PATH, wszInfFullPath, NULL /*lpFilePart*/);
    868984    if (!dwChars || dwChars >= MAX_PATH)
    869985    {
    870         NonStandardLogCrap(("GetFullPathNameW failed, dwErr=%ld, dwChars=%ld\n",
    871                             GetLastError(), dwChars));
     986        NonStandardLogCrap(("GetFullPathNameW failed, dwErr=%u, dwChars=%ld\n", GetLastError(), dwChars));
    872987        return E_INVALIDARG;
    873988    }
    874989
    875 
    876     if (!UpdateDriverForPlugAndPlayDevicesW(NULL, /* HWND hwndParent */
    877             pcszwHwId,
    878             InfFullPath,
    879             INSTALLFLAG_FORCE,
    880             &bRebootRequired))
     990    BOOL fRebootRequired = FALSE;
     991    if (!UpdateDriverForPlugAndPlayDevicesW(NULL /*hwndParent*/, pszwHwId, wszInfFullPath, INSTALLFLAG_FORCE, &fRebootRequired))
    881992    {
    882993        DWORD dwErr = GetLastError();
    883         NonStandardLogCrap(("UpdateDriverForPlugAndPlayDevicesW failed, dwErr=%ld\n",
    884                             dwErr));
     994        NonStandardLogCrap(("UpdateDriverForPlugAndPlayDevicesW failed, dwErr=%u\n", dwErr));
    885995        return HRESULT_FROM_WIN32(dwErr);
    886996    }
    887997
    888 
    889     if (bRebootRequired)
    890         NonStandardLogCrap(("!!Driver Update: REBOOT REQUIRED!!\n", GetLastError(), dwChars));
    891 
    892     if (pbRebootRequired)
    893         *pbRebootRequired = bRebootRequired;
     998    if (fRebootRequired)
     999        NonStandardLogCrap(("!!Driver Update: REBOOT REQUIRED!!\n"));
     1000
     1001    if (pfRebootRequired)
     1002        *pfRebootRequired = fRebootRequired;
    8941003
    8951004    return S_OK;
    8961005}
     1006
  • trunk/src/VBox/Installer/win/InstallHelper/Makefile.kmk

    r96407 r96572  
    5252ifdef VBOX_WITH_NETFLT
    5353 VBoxInstallHelper_LIBS   += \
    54         $(PATH_STAGE_LIB)/WinNetConfig.lib \
    55         $(PATH_STAGE_LIB)/VBoxDrvCfg.lib \
     54        $(PATH_STAGE_LIB)/WinNetConfigSharedStatic.lib \
     55        $(PATH_STAGE_LIB)/VBoxDrvCfgSharedStatic.lib \
    5656        $(PATH_TOOL_$(VBOX_VCC_TOOL)_LIB)/comsupp.lib \
    5757        $(PATH_SDK_$(VBOX_WINPSDK)_LIB)/WbemUuid.Lib
  • trunk/src/VBox/Installer/win/InstallHelper/VBoxCommon.cpp

    r96428 r96572  
    3333*********************************************************************************************************************************/
    3434#include <iprt/win/windows.h>
    35 
    36 #include <tchar.h>
    37 #include <stdio.h>
    38 
    3935#include <msi.h>
    4036#include <msiquery.h>
    4137
     38#include <iprt/string.h>
    4239#include <iprt/utf16.h>
    4340
    4441
    45 #if (_MSC_VER < 1400) /* Provide swprintf_s to VC < 8.0. */
    46 int swprintf_s(WCHAR *buffer, size_t cbBuffer, const WCHAR *format, ...)
     42UINT VBoxGetMsiProp(MSIHANDLE hMsi, const WCHAR *pwszName, WCHAR *pwszValueBuf, DWORD cwcValueBuf)
    4743{
    48     int ret;
    49     va_list va;
    50     va_start(va, format);
    51     ret = _vsnwprintf(buffer, cbBuffer, format, va);
    52     va_end(va);
    53     return ret;
    54 }
    55 #endif
     44    RT_BZERO(pwszValueBuf, cwcValueBuf * sizeof(pwszValueBuf[0]));
    5645
    57 UINT VBoxGetMsiProp(MSIHANDLE hMsi, const WCHAR *pwszName, WCHAR *pwszValue, DWORD dwSize)
    58 {
    59     DWORD dwBuffer = 0;
    60     UINT uiRet = MsiGetPropertyW(hMsi, pwszName, L"", &dwBuffer);
     46    /** @todo r=bird: why do we need to query the size first and then the data.
     47     *        The API should be perfectly capable of doing that without our help. */
     48    DWORD cwcNeeded = 0;
     49    UINT  uiRet = MsiGetPropertyW(hMsi, pwszName, L"", &cwcNeeded);
    6150    if (uiRet == ERROR_MORE_DATA)
    6251    {
    63         ++dwBuffer;     /* On output does not include terminating null, so add 1. */
     52        ++cwcNeeded;     /* On output does not include terminating null, so add 1. */
    6453
    65         if (dwBuffer > dwSize)
     54        if (cwcNeeded > cwcValueBuf)
    6655            return ERROR_MORE_DATA;
    67 
    68         ZeroMemory(pwszValue, dwSize);
    69         uiRet = MsiGetPropertyW(hMsi, pwszName, pwszValue, &dwBuffer);
     56        uiRet = MsiGetPropertyW(hMsi, pwszName, pwszValueBuf, &cwcNeeded);
    7057    }
    7158    return uiRet;
     
    9279        WCHAR wszValue[1024]; /* 1024 should be enough for everybody (tm). */
    9380        if (VBoxGetMsiProp(hMsi, pwszName, wszValue, sizeof(wszValue)) == ERROR_SUCCESS)
    94         {
    9581            rc = RTUtf16ToUtf8(wszValue, ppszValue);
    96         }
    9782        else
    9883            rc = VERR_NOT_FOUND;
     
    11398{
    11499    wchar_t wszTemp[32];
    115     swprintf(wszTemp, sizeof(wszTemp) / sizeof(wchar_t), L"%ld", dwVal);
     100    RTUtf16Printf(wszTemp, RT_ELEMENTS(wszTemp), "%u", dwVal);
    116101    return VBoxSetMsiProp(hMsi, pwszName, wszTemp);
    117102}
  • trunk/src/VBox/Installer/win/InstallHelper/VBoxCommon.h

    r96428 r96572  
    3636#endif
    3737
    38 UINT VBoxGetMsiProp(MSIHANDLE hMsi, const WCHAR *pwszName, WCHAR *pwszValue, DWORD dwSize);
     38UINT VBoxGetMsiProp(MSIHANDLE hMsi, const WCHAR *pwszName, WCHAR *pwszValueBuf, DWORD cwcValueBuf);
    3939int  VBoxGetMsiPropUtf8(MSIHANDLE hMsi, const char *pcszName, char **ppszValue);
    4040UINT VBoxSetMsiProp(MSIHANDLE hMsi, const WCHAR *pwszName, const WCHAR *pwszValue);
  • trunk/src/VBox/Installer/win/InstallHelper/VBoxInstallHelper.cpp

    r96428 r96572  
    3535#endif
    3636
    37 #include <VBox/version.h>
    38 
    39 #include <wchar.h>
    40 #include <stdio.h>
    41 
    4237#include <msi.h>
    4338#include <msiquery.h>
     
    4641#include <iprt/win/windows.h>
    4742
    48 #include <assert.h>
    4943#include <shellapi.h>
    5044#define INITGUID
     
    5347#include <devguid.h>
    5448
    55 #include <iprt/alloca.h>
    56 #include <iprt/string.h> /* RT_ZERO */
    57 #include <iprt/path.h>   /* RTPATH_MAX, RTPATH_IS_SLASH */
    58 
    5949#include <iprt/win/objbase.h>
    6050#include <iprt/win/setupapi.h>
    6151#include <iprt/win/shlobj.h>
    6252
     53#include <VBox/version.h>
     54
     55#include <iprt/assert.h>
     56#include <iprt/alloca.h>
     57#include <iprt/mem.h>
     58#include <iprt/path.h>   /* RTPATH_MAX, RTPATH_IS_SLASH */
     59#include <iprt/string.h> /* RT_ZERO */
     60#include <iprt/utf16.h>
     61
    6362#include "VBoxCommon.h"
    64 
    6563#ifndef VBOX_OSE
    6664# include "internal/VBoxSerial.h"
     
    7270*********************************************************************************************************************************/
    7371#ifdef DEBUG
    74 # define NonStandardAssert(_expr) assert(_expr)
     72# define NonStandardAssert(_expr) Assert(_expr)
    7573#else
    7674# define NonStandardAssert(_expr) do{ }while(0)
     
    8886{
    8987    RT_NOREF(hInst, uReason, pReserved);
     88
     89#if 0
     90    /*
     91     * This is a trick for allowing the debugger to be attached, don't know if
     92     * there is an official way to do that, but this is a pretty efficient.
     93     *
     94     * Monitor the debug output in DbgView and be ready to start windbg when
     95     * the message below appear.  This will happen 3-4 times during install,
     96     * and 2-3 times during uninstall.
     97     *
     98     * Note! The DIFxApp.DLL will automatically trigger breakpoints when a
     99     *       debugger is attached.  Just continue on these.
     100     */
     101    if (uReason == DLL_PROCESS_ATTACH)
     102    {
     103        WCHAR wszMsg[128];
     104        RTUtf16Printf(wszMsg, RT_ELEMENTS(wszMsg), "Waiting for debugger to attach: windbg -g -G -p %u\n", GetCurrentProcessId());
     105        for (unsigned i = 0; i < 128 && !IsDebuggerPresent(); i++)
     106        {
     107            OutputDebugStringW(wszMsg);
     108            Sleep(1001);
     109        }
     110        Sleep(1002);
     111        __debugbreak();
     112    }
     113#endif
     114
    90115    return TRUE;
    91116}
     
    94119 * Format and add message to the MSI log.
    95120 *
    96  * UTF-16 strings are formatted using '%s' (lowercase).
    97  * ANSI strings are formatted using '%S' (uppercase).
     121 * UTF-16 strings are formatted using '%ls' (lowercase).
     122 * ANSI strings are formatted using '%s' (uppercase).
    98123 */
    99 static UINT logStringF(MSIHANDLE hInstall, const wchar_t *pwszFmt, ...)
     124static UINT logStringF(MSIHANDLE hInstall, const char *pszFmt, ...)
    100125{
    101126    PMSIHANDLE hMSI = MsiCreateRecord(2 /* cParms */);
     
    104129        wchar_t wszBuf[RTPATH_MAX + 256];
    105130        va_list va;
    106         va_start(va, pwszFmt);
    107         ssize_t cwc = _vsnwprintf(wszBuf, RT_ELEMENTS(wszBuf), pwszFmt, va);
     131        va_start(va, pszFmt);
     132        ssize_t cwc = RTUtf16PrintfV(wszBuf, RT_ELEMENTS(wszBuf), pszFmt, va);
    108133        va_end(va);
    109         wszBuf[RT_ELEMENTS(wszBuf) - 1] = '\0';
    110134
    111135        MsiRecordSetStringW(hMSI, 0, wszBuf);
     
    151175     * Construct a full command line.
    152176     */
    153     size_t const cwcImage = wcslen(pwszImage);
    154     size_t const cwcArgs  = wcslen(pwszArgs);
     177    size_t const cwcImage = RTUtf16Len(pwszImage);
     178    size_t const cwcArgs  = RTUtf16Len(pwszArgs);
    155179
    156180    wchar_t *pwszCmdLine = (wchar_t *)alloca((1 + cwcImage + 1 + 1 + cwcArgs + 1) * sizeof(wchar_t));
     
    184208                       0 /*fFlags*/, NULL /*pwszEnv*/, NULL /*pwszCwd*/, &StartupInfo, &ChildInfo))
    185209    {
    186         logStringF(hModule, L"procRun: Info: Started process %u: %s", ChildInfo.dwProcessId, pwszCmdLine);
     210        logStringF(hModule, "procRun: Info: Started process %u: %ls", ChildInfo.dwProcessId, pwszCmdLine);
    187211        CloseHandle(ChildInfo.hThread);
    188212        DWORD const dwWait = WaitForSingleObject(ChildInfo.hProcess, RT_MS_30SEC);
     
    192216            if (dwExitCode == 0)
    193217            {
    194                 logStringF(hModule, L"procRun: Info: Process '%s' terminated exit code zero", pwszCmdLine);
     218                logStringF(hModule, "procRun: Info: Process '%ls' terminated exit code zero", pwszCmdLine);
    195219                rcWin = ERROR_SUCCESS;
    196220            }
    197221            else
    198222            {
    199                 logStringF(hModule, L"procRun: Process '%s' terminated with non-zero exit code: %u (%#x)",
     223                logStringF(hModule, "procRun: Process '%ls' terminated with non-zero exit code: %u (%#x)",
    200224                           pwszCmdLine, dwExitCode, dwExitCode);
    201225                rcWin = ERROR_GEN_FAILURE;
     
    205229        {
    206230            rcWin = GetLastError();
    207             logStringF(hModule, L"procRun: Process '%s' is probably still running: rcWin=%u dwWait=%u (%#x)",
     231            logStringF(hModule, "procRun: Process '%ls' is probably still running: rcWin=%u dwWait=%u (%#x)",
    208232                       pwszCmdLine, rcWin, dwWait, dwWait);
    209233        }
     
    212236    {
    213237        rcWin = GetLastError();
    214         logStringF(hModule, L"procRun: Creating process '%s' failed: rcWin=%u\n", pwszCmdLine, rcWin);
     238        logStringF(hModule, "procRun: Creating process '%ls' failed: rcWin=%u\n", pwszCmdLine, rcWin);
    215239    }
    216240    return rcWin;
     
    308332                            cwc += RT_ELEMENTS(s_wszPythonExe) - 1;
    309333                        wszBuf[cwc] = '\0';
    310                         logStringF(hModule, L"getPythonPath: Found: \"%s\"", wszBuf);
     334                        logStringF(hModule, "getPythonPath: Found: \"%ls\"", wszBuf);
    311335
    312336                        NonStandardAssert(cwcPythonPath > cwc);
     
    316340                    }
    317341                    else
    318                         logStringF(hModule, L"getPythonPath: Warning: Skipping \"%s\": is a directory (%#x)", wszBuf, fAttribs);
     342                        logStringF(hModule, "getPythonPath: Warning: Skipping \"%ls\": is a directory (%#x)", wszBuf, fAttribs);
    319343                }
    320344                else
    321                     logStringF(hModule, L"getPythonPath: Warning: Skipping \"%s\": Does not exist (%u)", wszBuf, GetLastError());
     345                    logStringF(hModule, "getPythonPath: Warning: Skipping \"%ls\": Does not exist (%u)", wszBuf, GetLastError());
    322346            }
    323347        }
     
    326350    RegCloseKey(hKeyPythonCore);
    327351    if (rcWinRet != ERROR_SUCCESS)
    328         logStringF(hModule, L"getPythonPath: Unable to find python");
     352        logStringF(hModule, "getPythonPath: Unable to find python");
    329353    return rcWinRet;
    330354}
     
    374398     * This is a prerequisite for setting up the VBox API.
    375399     */
    376     logStringF(hModule, L"checkPythonDependencies: Checking for win32api extensions ...");
     400    logStringF(hModule, "checkPythonDependencies: Checking for win32api extensions ...");
    377401
    378402    UINT rcWin = procRun(hModule, pwszPythonExe, L"-c \"import win32api\"");
    379403    if (rcWin == ERROR_SUCCESS)
    380         logStringF(hModule, L"checkPythonDependencies: win32api found\n");
     404        logStringF(hModule, "checkPythonDependencies: win32api found\n");
    381405    else
    382         logStringF(hModule, L"checkPythonDependencies: Importing win32api failed with %u (%#x)\n", rcWin, rcWin);
     406        logStringF(hModule, "checkPythonDependencies: Importing win32api failed with %u (%#x)\n", rcWin, rcWin);
    383407
    384408    return rcWin;
     
    402426    if (rcWin == ERROR_SUCCESS)
    403427    {
    404         logStringF(hModule, L"IsPythonInstalled: Python installation found at \"%s\"", wszPythonPath);
     428        logStringF(hModule, "IsPythonInstalled: Python installation found at \"%ls\"", wszPythonPath);
    405429        VBoxSetMsiProp(hModule, L"VBOX_PYTHON_PATH", wszPythonPath);
    406430        VBoxSetMsiProp(hModule, L"VBOX_PYTHON_INSTALLED", L"1");
     
    408432    else
    409433    {
    410         logStringF(hModule, L"IsPythonInstalled: Error: No suitable Python installation found (%u), skipping installation.", rcWin);
    411         logStringF(hModule, L"IsPythonInstalled: Python seems not to be installed; please download + install the Python Core package.");
     434        logStringF(hModule, "IsPythonInstalled: Error: No suitable Python installation found (%u), skipping installation.", rcWin);
     435        logStringF(hModule, "IsPythonInstalled: Python seems not to be installed; please download + install the Python Core package.");
    412436        VBoxSetMsiProp(hModule, L"VBOX_PYTHON_INSTALLED", L"0");
    413437    }
     
    434458        dwErr = checkPythonDependencies(hModule, wszPythonExe);
    435459        if (dwErr == ERROR_SUCCESS)
    436             logStringF(hModule, L"ArePythonAPIDepsInstalled: Dependencies look good.");
     460            logStringF(hModule, "ArePythonAPIDepsInstalled: Dependencies look good.");
    437461    }
    438462
    439463    if (dwErr != ERROR_SUCCESS)
    440         logStringF(hModule, L"ArePythonAPIDepsInstalled: Failed with dwErr=%u", dwErr);
     464        logStringF(hModule, "ArePythonAPIDepsInstalled: Failed with dwErr=%u", dwErr);
    441465
    442466    VBoxSetMsiProp(hModule, L"VBOX_PYTHON_DEPS_INSTALLED", dwErr == ERROR_SUCCESS ? L"1" : L"0");
     
    462486{
    463487    HKEY hKeyVS = NULL;
    464     LSTATUS dwErr = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
    465                                   L"SOFTWARE\\Microsoft\\VisualStudio\\14.0\\VC\\Runtimes\\X64",
    466                                   0, KEY_READ, &hKeyVS);
    467     if (dwErr == ERROR_SUCCESS)
     488    LSTATUS lrc = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
     489                                L"SOFTWARE\\Microsoft\\VisualStudio\\14.0\\VC\\Runtimes\\X64",
     490                                0, KEY_READ, &hKeyVS);
     491    if (lrc == ERROR_SUCCESS)
    468492    {
    469493        DWORD dwVal = 0;
    470494        DWORD cbVal = sizeof(dwVal);
    471         DWORD dwValueType = REG_DWORD;
    472 
    473         dwErr = RegQueryValueExW(hKeyVS, L"Installed", NULL, &dwValueType, (LPBYTE)&dwVal, &cbVal);
    474         if (dwErr == ERROR_SUCCESS)
     495        DWORD dwValueType = REG_DWORD; /** @todo r=bird: output only parameter, optional, so pointless. */
     496        lrc = RegQueryValueExW(hKeyVS, L"Installed", NULL, &dwValueType, (LPBYTE)&dwVal, &cbVal);
     497        if (lrc == ERROR_SUCCESS)
    475498        {
    476499            if (dwVal >= 1)
    477500            {
    478                 DWORD dwMin, dwMaj;
    479                 dwErr = RegQueryValueExW(hKeyVS, L"Major", NULL, &dwValueType, (LPBYTE)&dwMaj, &cbVal);
    480                 if (dwErr == ERROR_SUCCESS)
     501                DWORD dwMaj = 0; /** @todo r=bird: It's purdent to initialize values if you don't bother to check the type and size! */
     502                lrc = RegQueryValueExW(hKeyVS, L"Major", NULL, &dwValueType, (LPBYTE)&dwMaj, &cbVal);
     503                if (lrc == ERROR_SUCCESS)
    481504                {
    482505                    VBoxSetMsiPropDWORD(hModule, L"VBOX_MSCRT_VER_MAJ", dwMaj);
    483506
    484                     dwErr = RegQueryValueExW(hKeyVS, L"Minor", NULL, &dwValueType, (LPBYTE)&dwMin, &cbVal);
    485                     if (dwErr == ERROR_SUCCESS)
     507                    DWORD dwMin = 0;
     508                    lrc = RegQueryValueExW(hKeyVS, L"Minor", NULL, &dwValueType, (LPBYTE)&dwMin, &cbVal);
     509                    if (lrc == ERROR_SUCCESS)
    486510                    {
    487511                        VBoxSetMsiPropDWORD(hModule, L"VBOX_MSCRT_VER_MIN", dwMin);
    488512
    489                         logStringF(hModule, L"IsMSCRTInstalled: Found v%ld.%ld\n", dwMaj, dwMin);
     513                        logStringF(hModule, "IsMSCRTInstalled: Found v%u.%u\n", dwMaj, dwMin);
    490514
    491515                        /* Check for at least 2019. */
     
    494518                    }
    495519                    else
    496                         logStringF(hModule, L"IsMSCRTInstalled: Found, but 'Minor' key not present");
     520                        logStringF(hModule, "IsMSCRTInstalled: Found, but 'Minor' key not present (lrc=%d)", lrc);
    497521                }
    498522                else
    499                     logStringF(hModule, L"IsMSCRTInstalled: Found, but 'Major' key not present");
     523                    logStringF(hModule, "IsMSCRTInstalled: Found, but 'Major' key not present (lrc=%d)", lrc);
    500524            }
    501525            else
    502526            {
    503                 logStringF(hModule, L"IsMSCRTInstalled: Found, but not marked as installed");
    504                 dwErr = ERROR_NOT_INSTALLED;
     527                logStringF(hModule, "IsMSCRTInstalled: Found, but not marked as installed");
     528                lrc = ERROR_NOT_INSTALLED;
    505529            }
    506530        }
    507531        else
    508             logStringF(hModule, L"IsMSCRTInstalled: Found, but 'Installed' key not present");
    509     }
    510 
    511     if (dwErr != ERROR_SUCCESS)
    512         logStringF(hModule, L"IsMSCRTInstalled: Failed with dwErr=%ld", dwErr);
     532            logStringF(hModule, "IsMSCRTInstalled: Found, but 'Installed' key not present (lrc=%d)", lrc);
     533    }
     534
     535    if (lrc != ERROR_SUCCESS)
     536        logStringF(hModule, "IsMSCRTInstalled: Failed with lrc=%ld", lrc);
    513537
    514538    return ERROR_SUCCESS; /* Never return failure. */
     
    533557     */
    534558    HKEY hKeyCurVer = NULL;
    535     LSTATUS dwErr = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", 0, KEY_READ, &hKeyCurVer);
    536     if (dwErr == ERROR_SUCCESS)
     559    LSTATUS lrc = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", 0, KEY_READ, &hKeyCurVer);
     560    if (lrc == ERROR_SUCCESS)
    537561    {
    538562        DWORD dwVal = 0;
    539563        DWORD cbVal = sizeof(dwVal);
    540         DWORD dwValueType = REG_DWORD;
    541         dwErr = RegQueryValueExW(hKeyCurVer, L"CurrentMajorVersionNumber", NULL, &dwValueType, (LPBYTE)&dwVal, &cbVal);
    542         if (dwErr == ERROR_SUCCESS)
    543         {
    544             logStringF(hModule, L"IsWindows10/CurrentMajorVersionNumber: %ld", dwVal);
     564        DWORD dwValueType = REG_DWORD; /** @todo r=bird: Again, the type is an optional output parameter. pointless to init or pass it unless you check.  */
     565        lrc = RegQueryValueExW(hKeyCurVer, L"CurrentMajorVersionNumber", NULL, &dwValueType, (LPBYTE)&dwVal, &cbVal);
     566        if (lrc == ERROR_SUCCESS)
     567        {
     568            logStringF(hModule, "IsWindows10/CurrentMajorVersionNumber: %u", dwVal);
    545569
    546570            VBoxSetMsiProp(hModule, L"VBOX_IS_WINDOWS_10", dwVal >= 10 ? L"1" : L"");
    547571        }
    548572        else
    549             logStringF(hModule, L"IsWindows10/RegOpenKeyExW: Error reading CurrentMajorVersionNumber (%ld)", dwErr);
     573            logStringF(hModule, "IsWindows10/RegOpenKeyExW: Error reading CurrentMajorVersionNumber (%ld)", lrc);
    550574
    551575        RegCloseKey(hKeyCurVer);
    552576    }
    553577    else
    554         logStringF(hModule, L"IsWindows10/RegOpenKeyExW: Error opening CurrentVersion key (%ld)", dwErr);
     578        logStringF(hModule, "IsWindows10/RegOpenKeyExW: Error opening CurrentVersion key (%ld)", lrc);
    555579
    556580    return ERROR_SUCCESS; /* Never return failure. */
     
    569593UINT __stdcall InstallPythonAPI(MSIHANDLE hModule)
    570594{
    571     logStringF(hModule, L"InstallPythonAPI: Checking for installed Python environment(s) ...");
     595    logStringF(hModule, "InstallPythonAPI: Checking for installed Python environment(s) ...");
    572596
    573597    /** @todo r=bird: Can't we get the VBOX_PYTHON_PATH property here? */
     
    585609    /* Get the VBox API setup string. */
    586610    WCHAR wszVBoxSDKPath[RTPATH_MAX];
    587     rcWin = VBoxGetMsiProp(hModule, L"CustomActionData", wszVBoxSDKPath, sizeof(wszVBoxSDKPath));
     611    rcWin = VBoxGetMsiProp(hModule, L"CustomActionData", wszVBoxSDKPath, RT_ELEMENTS(wszVBoxSDKPath));
    588612    if (rcWin == ERROR_SUCCESS)
    589613    {
     
    594618            if (SetEnvironmentVariableW(L"VBOX_INSTALL_PATH", wszVBoxSDKPath))
    595619            {
    596                 logStringF(hModule, L"InstallPythonAPI: Invoking vboxapisetup.py in \"%s\" ...", wszVBoxSDKPath);
     620                logStringF(hModule, "InstallPythonAPI: Invoking vboxapisetup.py in \"%ls\" ...", wszVBoxSDKPath);
    597621
    598622                rcWin = procRun(hModule, wszPythonExe, L"vboxapisetup.py install");
    599623                if (rcWin == ERROR_SUCCESS)
    600624                {
    601                     logStringF(hModule, L"InstallPythonAPI: Installation of vboxapisetup.py successful");
     625                    logStringF(hModule, "InstallPythonAPI: Installation of vboxapisetup.py successful");
    602626
    603627                    /*
    604628                     * Do some sanity checking if the VBox API works.
    605629                     */
    606                     logStringF(hModule, L"InstallPythonAPI: Validating VBox API ...");
     630                    logStringF(hModule, "InstallPythonAPI: Validating VBox API ...");
    607631
    608632                    rcWin = procRun(hModule, wszPythonExe, L"-c \"from vboxapi import VirtualBoxManager\"");
    609633                    if (rcWin == ERROR_SUCCESS)
    610634                    {
    611                         logStringF(hModule, L"InstallPythonAPI: VBox API looks good.");
     635                        logStringF(hModule, "InstallPythonAPI: VBox API looks good.");
    612636                        VBoxSetMsiProp(hModule, L"VBOX_API_INSTALLED", L"1");
    613637                        return ERROR_SUCCESS;
     
    615639
    616640                    /* failed */
    617                     logStringF(hModule, L"InstallPythonAPI: Validating VBox API failed with %u (%#x)", rcWin, rcWin);
     641                    logStringF(hModule, "InstallPythonAPI: Validating VBox API failed with %u (%#x)", rcWin, rcWin);
    618642                }
    619643                else
    620                     logStringF(hModule, L"InstallPythonAPI: Calling vboxapisetup.py failed with %u (%#x)", rcWin, rcWin);
     644                    logStringF(hModule, "InstallPythonAPI: Calling vboxapisetup.py failed with %u (%#x)", rcWin, rcWin);
    621645            }
    622646            else
    623                 logStringF(hModule, L"InstallPythonAPI: Could set environment variable VBOX_INSTALL_PATH: LastError=%u",
     647                logStringF(hModule, "InstallPythonAPI: Could set environment variable VBOX_INSTALL_PATH: LastError=%u",
    624648                           GetLastError());
    625649        }
    626650        else
    627             logStringF(hModule, L"InstallPythonAPI: Could set working directory to \"%s\": LastError=%u",
     651            logStringF(hModule, "InstallPythonAPI: Could set working directory to \"%ls\": LastError=%u",
    628652                       wszVBoxSDKPath, GetLastError());
    629653    }
    630654    else
    631         logStringF(hModule, L"InstallPythonAPI: Unable to retrieve VBox installation directory: rcWin=%u (%#x)", rcWin, rcWin);
     655        logStringF(hModule, "InstallPythonAPI: Unable to retrieve VBox installation directory: rcWin=%u (%#x)", rcWin, rcWin);
    632656
    633657    VBoxSetMsiProp(hModule, L"VBOX_API_INSTALLED", L"0");
    634     logStringF(hModule, L"InstallPythonAPI: Installation failed");
     658    logStringF(hModule, "InstallPythonAPI: Installation failed");
    635659    return ERROR_SUCCESS; /* Do not fail here. */
    636660}
     
    642666{
    643667    LONG rc;
    644     WCHAR wszValue[_MAX_PATH];
     668    WCHAR wszValue[MAX_PATH];
    645669    if (GetPrivateProfileStringW(pwszSection, pwszValue, NULL, wszValue, sizeof(wszValue), pwszFileName) > 0)
    646670    {
    647         WCHAR wszKey[_MAX_PATH + 64];
    648         if (wcsicmp(L"General", pwszSection) != 0)
    649             swprintf_s(wszKey, RT_ELEMENTS(wszKey), L"SOFTWARE\\%S\\VirtualBox\\Branding\\%s", VBOX_VENDOR_SHORT, pwszSection);
     671        WCHAR wszKey[MAX_PATH + 64];
     672        if (RTUtf16ICmpAscii(pwszSection, "General") != 0)
     673            RTUtf16Printf(wszKey, RT_ELEMENTS(wszKey), "SOFTWARE\\%s\\VirtualBox\\Branding\\%ls", VBOX_VENDOR_SHORT, pwszSection);
    650674        else
    651             swprintf_s(wszKey, RT_ELEMENTS(wszKey), L"SOFTWARE\\%S\\VirtualBox\\Branding", VBOX_VENDOR_SHORT);
     675            RTUtf16Printf(wszKey, RT_ELEMENTS(wszKey), "SOFTWARE\\%s\\VirtualBox\\Branding", VBOX_VENDOR_SHORT);
    652676
    653677        HKEY hkBranding = NULL;
     
    660684                                REG_SZ,
    661685                                (BYTE *)wszValue,
    662                                 (DWORD)wcslen(wszValue));
     686                                (DWORD)RTUtf16Len(wszValue));
    663687            if (rc != ERROR_SUCCESS)
    664                 logStringF(hModule, L"InstallBranding: Could not write value %s! Error %d", pwszValue, rc);
     688                logStringF(hModule, "InstallBranding: Could not write value %s! Error %d", pwszValue, rc);
    665689            RegCloseKey(hkBranding);
    666690        }
     
    676700static UINT CopyDir(MSIHANDLE hModule, const WCHAR *pwszzDstDir, const WCHAR *pwszzSrcDir)
    677701{
    678     NonStandardAssert(pwszzDstDir[wcslen(pwszzDstDir) + 1] == '\0');
    679     NonStandardAssert(pwszzSrcDir[wcslen(pwszzSrcDir) + 1] == '\0');
     702    NonStandardAssert(pwszzDstDir[RTUtf16Len(pwszzDstDir) + 1] == '\0');
     703    NonStandardAssert(pwszzSrcDir[RTUtf16Len(pwszzSrcDir) + 1] == '\0');
    680704
    681705    SHFILEOPSTRUCTW s = {0};
     
    689713             | FOF_NOERRORUI;
    690714
    691     logStringF(hModule, L"CopyDir: pwszzDstDir=%s, pwszzSrcDir=%s", pwszzDstDir, pwszzSrcDir);
     715    logStringF(hModule, "CopyDir: pwszzDstDir=%ls, pwszzSrcDir=%ls", pwszzDstDir, pwszzSrcDir);
    692716    int r = SHFileOperationW(&s);
    693717    if (r == 0)
    694718        return ERROR_SUCCESS;
    695     logStringF(hModule, L"CopyDir: Copy operation returned status %#x", r);
     719    logStringF(hModule, "CopyDir: Copy operation returned status %#x", r);
    696720    return ERROR_GEN_FAILURE;
    697721}
     
    702726static UINT RemoveDir(MSIHANDLE hModule, const WCHAR *pwszzDstDir)
    703727{
    704     NonStandardAssert(pwszzDstDir[wcslen(pwszzDstDir) + 1] == '\0');
     728    NonStandardAssert(pwszzDstDir[RTUtf16Len(pwszzDstDir) + 1] == '\0');
    705729
    706730    SHFILEOPSTRUCTW s = {0};
     
    713737             | FOF_NOERRORUI;
    714738
    715     logStringF(hModule, L"RemoveDir: pwszzDstDir=%s", pwszzDstDir);
     739    logStringF(hModule, "RemoveDir: pwszzDstDir=%ls", pwszzDstDir);
    716740    int r = SHFileOperationW(&s);
    717741    if (r == 0)
    718742        return ERROR_SUCCESS;
    719     logStringF(hModule, L"RemoveDir: Remove operation returned status %#x", r);
     743    logStringF(hModule, "RemoveDir: Remove operation returned status %#x", r);
    720744    return ERROR_GEN_FAILURE;
    721745}
     
    726750static UINT RenameDir(MSIHANDLE hModule, const WCHAR *pwszzDstDir, const WCHAR *pwszzSrcDir)
    727751{
    728     NonStandardAssert(pwszzDstDir[wcslen(pwszzDstDir) + 1] == '\0');
    729     NonStandardAssert(pwszzSrcDir[wcslen(pwszzSrcDir) + 1] == '\0');
     752    NonStandardAssert(pwszzDstDir[RTUtf16Len(pwszzDstDir) + 1] == '\0');
     753    NonStandardAssert(pwszzSrcDir[RTUtf16Len(pwszzSrcDir) + 1] == '\0');
    730754
    731755    SHFILEOPSTRUCTW s = {0};
     
    739763             | FOF_NOERRORUI;
    740764
    741     logStringF(hModule, L"RenameDir: pwszzDstDir=%s, pwszzSrcDir=%s", pwszzDstDir, pwszzSrcDir);
     765    logStringF(hModule, "RenameDir: pwszzDstDir=%ls, pwszzSrcDir=%ls", pwszzDstDir, pwszzSrcDir);
    742766    int r = SHFileOperationW(&s);
    743767    if (r == 0)
    744768        return ERROR_SUCCESS;
    745     logStringF(hModule, L"RenameDir: Rename operation returned status %#x", r);
     769    logStringF(hModule, "RenameDir: Rename operation returned status %#x", r);
    746770    return ERROR_GEN_FAILURE;
    747771}
     
    750774static UINT AppendToPath(wchar_t *pwszPath, size_t cwcPath, wchar_t *pwszAppend, bool fDoubleTerm = false)
    751775{
    752     size_t cwcCurPath = wcslen(pwszPath);
     776    size_t cwcCurPath = RTUtf16Len(pwszPath);
    753777    size_t cwcSlash   = cwcCurPath > 1 && RTPATH_IS_SLASH(pwszPath[cwcCurPath - 1]) ? 0 : 1;
    754778    while (RTPATH_IS_SLASH(*pwszAppend))
    755779        pwszAppend++;
    756     size_t cwcAppend  = wcslen(pwszAppend);
     780    size_t cwcAppend  = RTUtf16Len(pwszAppend);
    757781    if (cwcCurPath + cwcCurPath + cwcAppend + fDoubleTerm < cwcPath)
    758782    {
     
    770794static UINT JoinPaths(wchar_t *pwszPath, size_t cwcPath, wchar_t *pwszPath1, wchar_t *pwszAppend, bool fDoubleTerm = false)
    771795{
    772     size_t cwcCurPath = wcslen(pwszPath1);
     796    size_t cwcCurPath = RTUtf16Len(pwszPath1);
    773797    if (cwcCurPath < cwcPath)
    774798    {
     
    781805UINT __stdcall UninstallBranding(MSIHANDLE hModule)
    782806{
    783     logStringF(hModule, L"UninstallBranding: Handling branding file ...");
     807    logStringF(hModule, "UninstallBranding: Handling branding file ...");
    784808
    785809    WCHAR wszPath[RTPATH_MAX];
    786     UINT rc = VBoxGetMsiProp(hModule, L"CustomActionData", wszPath, sizeof(wszPath));
     810    UINT rc = VBoxGetMsiProp(hModule, L"CustomActionData", wszPath, RT_ELEMENTS(wszPath));
    787811    if (rc == ERROR_SUCCESS)
    788812    {
    789         size_t const cwcPath = wcslen(wszPath);
     813        size_t const cwcPath = RTUtf16Len(wszPath);
    790814        rc = AppendToPath(wszPath, RTPATH_MAX, L"custom", true /*fDoubleTerm*/);
    791815        if (rc == ERROR_SUCCESS)
     
    799823    }
    800824
    801     logStringF(hModule, L"UninstallBranding: Handling done. (rc=%u (ignored))", rc);
     825    logStringF(hModule, "UninstallBranding: Handling done. (rc=%u (ignored))", rc);
    802826    return ERROR_SUCCESS; /* Do not fail here. */
    803827}
     
    805829UINT __stdcall InstallBranding(MSIHANDLE hModule)
    806830{
    807     logStringF(hModule, L"InstallBranding: Handling branding file ...");
     831    logStringF(hModule, "InstallBranding: Handling branding file ...");
    808832
    809833    /*
     
    842866    }
    843867
    844     logStringF(hModule, L"InstallBranding: Handling done. (rc=%u (ignored))", rc);
     868    logStringF(hModule, "InstallBranding: Handling done. (rc=%u (ignored))", rc);
    845869    return ERROR_SUCCESS; /* Do not fail here. */
    846870}
     
    863887static UINT _uninstallNetLwf(MSIHANDLE hModule);
    864888
    865 static VOID vboxDrvLoggerCallback(VBOXDRVCFG_LOG_SEVERITY enmSeverity, char *pszMsg, void *pvContext)
     889static VOID vboxDrvLoggerCallback(VBOXDRVCFG_LOG_SEVERITY_T enmSeverity, char *pszMsg, void *pvContext)
    866890{
    867891    RT_NOREF1(pvContext);
     
    873897        case VBOXDRVCFG_LOG_SEVERITY_REL:
    874898            if (g_hCurrentModule)
    875                 logStringF(g_hCurrentModule, L"%S", pszMsg);
     899                logStringF(g_hCurrentModule, "%s", pszMsg);
    876900            break;
    877901        default:
     
    883907{
    884908    if (g_hCurrentModule)
    885         logStringF(g_hCurrentModule, L"%S", pszString);
     909        logStringF(g_hCurrentModule, "%s", pszString);
    886910}
    887911
     
    920944        case NETCFG_S_REBOOT:
    921945        {
    922             logStringF(hModule, L"Reboot required, setting REBOOT property to \"force\"");
     946            logStringF(hModule, "Reboot required, setting REBOOT property to \"force\"");
    923947            HRESULT hr2 = MsiSetPropertyW(hModule, L"REBOOT", L"Force");
    924948            if (hr2 != ERROR_SUCCESS)
    925                 logStringF(hModule, L"Failed to set REBOOT property, error = %#x", hr2);
     949                logStringF(hModule, "Failed to set REBOOT property, error = %#x", hr2);
    926950            uRet = ERROR_SUCCESS; /* Never fail here. */
    927951            break;
     
    929953
    930954        default:
    931             logStringF(hModule, L"Converting unhandled HRESULT (%#x) to ERROR_GEN_FAILURE", hr);
     955            logStringF(hModule, "Converting unhandled HRESULT (%#x) to ERROR_GEN_FAILURE", hr);
    932956            uRet = ERROR_GEN_FAILURE;
    933957    }
     
    943967        if (uErr != ERROR_SUCCESS)
    944968        {
    945             logStringF(hModule, L"createNetCfgLockedMsgRecord: MsiRecordSetInteger failed, error = %#x", uErr);
     969            logStringF(hModule, "createNetCfgLockedMsgRecord: MsiRecordSetInteger failed, error = %#x", uErr);
    946970            MsiCloseHandle(hRecord);
    947971            hRecord = NULL;
     
    949973    }
    950974    else
    951         logStringF(hModule, L"createNetCfgLockedMsgRecord: Failed to create a record");
     975        logStringF(hModule, "createNetCfgLockedMsgRecord: Failed to create a record");
    952976
    953977    return hRecord;
     
    968992        {
    969993            if (FAILED(hr))
    970                 logStringF(hModule, L"doNetCfgInit: VBoxNetCfgWinQueryINetCfg failed, error = %#x", hr);
     994                logStringF(hModule, "doNetCfgInit: VBoxNetCfgWinQueryINetCfg failed, error = %#x", hr);
    971995            uErr = errorConvertFromHResult(hModule, hr);
    972996            break;
     
    9771001        if (!lpszLockedBy)
    9781002        {
    979             logStringF(hModule, L"doNetCfgInit: lpszLockedBy == NULL, breaking");
     1003            logStringF(hModule, "doNetCfgInit: lpszLockedBy == NULL, breaking");
    9801004            break;
    9811005        }
     
    9881012         * rather than waiting for a longer period of time before displaying it */
    9891013        if (   cRetries < VBOX_NETCFG_MAX_RETRIES
    990             && !wcscmp(lpszLockedBy, L"6to4svc.dll"))
     1014            && RTUtf16ICmpAscii(lpszLockedBy, "6to4svc.dll") == 0)
    9911015        {
    9921016            cRetries++;
    993             logStringF(hModule, L"doNetCfgInit: lpszLockedBy is 6to4svc.dll, retrying %d out of %d", cRetries, VBOX_NETCFG_MAX_RETRIES);
     1017            logStringF(hModule, "doNetCfgInit: lpszLockedBy is 6to4svc.dll, retrying %d out of %d", cRetries, VBOX_NETCFG_MAX_RETRIES);
    9941018            MsgResult = IDRETRY;
    9951019        }
     
    10011025                if (!hMsg)
    10021026                {
    1003                     logStringF(hModule, L"doNetCfgInit: Failed to create a message record, breaking");
     1027                    logStringF(hModule, "doNetCfgInit: Failed to create a message record, breaking");
    10041028                    CoTaskMemFree(lpszLockedBy);
    10051029                    break;
     
    10111035            if (rTmp != ERROR_SUCCESS)
    10121036            {
    1013                 logStringF(hModule, L"doNetCfgInit: MsiRecordSetStringW failed, error = #%x", rTmp);
     1037                logStringF(hModule, "doNetCfgInit: MsiRecordSetStringW failed, error = #%x", rTmp);
    10141038                CoTaskMemFree(lpszLockedBy);
    10151039                break;
     
    10181042            MsgResult = MsiProcessMessage(hModule, (INSTALLMESSAGE)(INSTALLMESSAGE_USER | MB_RETRYCANCEL), hMsg);
    10191043            NonStandardAssert(MsgResult == IDRETRY || MsgResult == IDCANCEL);
    1020             logStringF(hModule, L"doNetCfgInit: MsiProcessMessage returned (%#x)", MsgResult);
     1044            logStringF(hModule, "doNetCfgInit: MsiProcessMessage returned (%#x)", MsgResult);
    10211045        }
    10221046        CoTaskMemFree(lpszLockedBy);
     
    10291053}
    10301054
    1031 static UINT vboxNetFltQueryInfArray(MSIHANDLE hModule, OUT LPWSTR pwszPtInf, OUT LPWSTR pwszMpInf, DWORD dwSize)
    1032 {
    1033     DWORD dwBuf = dwSize - RT_MAX(sizeof(NETFLT_PT_INF_REL_PATH), sizeof(NETFLT_MP_INF_REL_PATH));
    1034     UINT uErr = MsiGetPropertyW(hModule, L"CustomActionData", pwszPtInf, &dwBuf);
     1055static UINT vboxNetFltQueryInfArray(MSIHANDLE hModule, OUT LPWSTR pwszPtInf, DWORD cwcPtInf,
     1056                                    OUT LPWSTR pwszMpInf, DWORD cwcMpInf)
     1057{
     1058    DWORD cwcEffBuf = cwcPtInf - RT_MAX(sizeof(NETFLT_PT_INF_REL_PATH), sizeof(NETFLT_MP_INF_REL_PATH)) / sizeof(WCHAR);
     1059    UINT uErr = MsiGetPropertyW(hModule, L"CustomActionData", pwszPtInf, &cwcEffBuf);
    10351060    if (   uErr == ERROR_SUCCESS
    1036         && dwBuf)
    1037     {
    1038         wcscpy(pwszMpInf, pwszPtInf);
    1039 
    1040         wcsncat(pwszPtInf, NETFLT_PT_INF_REL_PATH, sizeof(NETFLT_PT_INF_REL_PATH));
    1041         logStringF(hModule, L"vboxNetFltQueryInfArray: INF 1: %s", pwszPtInf);
    1042 
    1043         wcsncat(pwszMpInf, NETFLT_MP_INF_REL_PATH, sizeof(NETFLT_MP_INF_REL_PATH));
    1044         logStringF(hModule, L"vboxNetFltQueryInfArray: INF 2: %s", pwszMpInf);
     1061        && cwcEffBuf > 0)
     1062    {
     1063        int vrc = RTUtf16Copy(pwszMpInf, cwcMpInf, pwszPtInf);
     1064        AssertRCReturn(vrc, ERROR_BUFFER_OVERFLOW);
     1065
     1066        vrc = RTUtf16Cat(pwszPtInf, cwcPtInf, NETFLT_PT_INF_REL_PATH);
     1067        AssertRCReturn(vrc, ERROR_BUFFER_OVERFLOW);
     1068        logStringF(hModule, "vboxNetFltQueryInfArray: INF 1: %ls", pwszPtInf);
     1069
     1070        vrc = RTUtf16Cat(pwszMpInf, cwcMpInf, NETFLT_MP_INF_REL_PATH);
     1071        AssertRCReturn(vrc, ERROR_BUFFER_OVERFLOW);
     1072        logStringF(hModule, "vboxNetFltQueryInfArray: INF 2: %ls", pwszMpInf);
    10451073    }
    10461074    else if (uErr != ERROR_SUCCESS)
    1047         logStringF(hModule, L"vboxNetFltQueryInfArray: MsiGetPropertyW failed, error = %#x", uErr);
     1075        logStringF(hModule, "vboxNetFltQueryInfArray: MsiGetPropertyW failed, error = %#x", uErr);
    10481076    else
    10491077    {
    1050         logStringF(hModule, L"vboxNetFltQueryInfArray: Empty installation directory");
     1078        logStringF(hModule, "vboxNetFltQueryInfArray: Empty installation directory");
    10511079        uErr = ERROR_GEN_FAILURE;
    10521080    }
     
    10691097    __try
    10701098    {
    1071         logStringF(hModule, L"Uninstalling NetFlt");
     1099        logStringF(hModule, "Uninstalling NetFlt");
    10721100
    10731101        uErr = doNetCfgInit(hModule, &pNetCfg, TRUE);
     
    10761104            HRESULT hr = VBoxNetCfgWinNetFltUninstall(pNetCfg);
    10771105            if (hr != S_OK)
    1078                 logStringF(hModule, L"UninstallNetFlt: VBoxNetCfgWinUninstallComponent failed, error = %#x", hr);
     1106                logStringF(hModule, "UninstallNetFlt: VBoxNetCfgWinUninstallComponent failed, error = %#x", hr);
    10791107
    10801108            uErr = errorConvertFromHResult(hModule, hr);
     
    10821110            VBoxNetCfgWinReleaseINetCfg(pNetCfg, TRUE);
    10831111
    1084             logStringF(hModule, L"Uninstalling NetFlt done, error = %#x", uErr);
     1112            logStringF(hModule, "Uninstalling NetFlt done, error = %#x", uErr);
    10851113        }
    10861114        else
    1087             logStringF(hModule, L"UninstallNetFlt: doNetCfgInit failed, error = %#x", uErr);
     1115            logStringF(hModule, "UninstallNetFlt: doNetCfgInit failed, error = %#x", uErr);
    10881116    }
    10891117    __finally
     
    11211149    {
    11221150
    1123         logStringF(hModule, L"InstallNetFlt: Installing NetFlt");
     1151        logStringF(hModule, "InstallNetFlt: Installing NetFlt");
    11241152
    11251153        uErr = doNetCfgInit(hModule, &pNetCfg, TRUE);
     
    11281156            WCHAR wszPtInf[MAX_PATH];
    11291157            WCHAR wszMpInf[MAX_PATH];
    1130             uErr = vboxNetFltQueryInfArray(hModule, wszPtInf, wszMpInf, sizeof(wszMpInf));
     1158            uErr = vboxNetFltQueryInfArray(hModule, wszPtInf, RT_ELEMENTS(wszPtInf), wszMpInf, RT_ELEMENTS(wszMpInf));
    11311159            if (uErr == ERROR_SUCCESS)
    11321160            {
     
    11341162                HRESULT hr = VBoxNetCfgWinNetFltInstall(pNetCfg, &apwszInfs[0], RT_ELEMENTS(apwszInfs));
    11351163                if (FAILED(hr))
    1136                     logStringF(hModule, L"InstallNetFlt: VBoxNetCfgWinNetFltInstall failed, error = %#x", hr);
     1164                    logStringF(hModule, "InstallNetFlt: VBoxNetCfgWinNetFltInstall failed, error = %#x", hr);
    11371165
    11381166                uErr = errorConvertFromHResult(hModule, hr);
    11391167            }
    11401168            else
    1141                 logStringF(hModule, L"InstallNetFlt: vboxNetFltQueryInfArray failed, error = %#x", uErr);
     1169                logStringF(hModule, "InstallNetFlt: vboxNetFltQueryInfArray failed, error = %#x", uErr);
    11421170
    11431171            VBoxNetCfgWinReleaseINetCfg(pNetCfg, TRUE);
    11441172
    1145             logStringF(hModule, L"InstallNetFlt: Done");
     1173            logStringF(hModule, "InstallNetFlt: Done");
    11461174        }
    11471175        else
    1148             logStringF(hModule, L"InstallNetFlt: doNetCfgInit failed, error = %#x", uErr);
     1176            logStringF(hModule, "InstallNetFlt: doNetCfgInit failed, error = %#x", uErr);
    11491177    }
    11501178    __finally
     
    11821210    __try
    11831211    {
    1184         logStringF(hModule, L"Uninstalling NetLwf");
     1212        logStringF(hModule, "Uninstalling NetLwf");
    11851213
    11861214        uErr = doNetCfgInit(hModule, &pNetCfg, TRUE);
     
    11891217            HRESULT hr = VBoxNetCfgWinNetLwfUninstall(pNetCfg);
    11901218            if (hr != S_OK)
    1191                 logStringF(hModule, L"UninstallNetLwf: VBoxNetCfgWinUninstallComponent failed, error = %#x", hr);
     1219                logStringF(hModule, "UninstallNetLwf: VBoxNetCfgWinUninstallComponent failed, error = %#x", hr);
    11921220
    11931221            uErr = errorConvertFromHResult(hModule, hr);
     
    11951223            VBoxNetCfgWinReleaseINetCfg(pNetCfg, TRUE);
    11961224
    1197             logStringF(hModule, L"Uninstalling NetLwf done, error = %#x", uErr);
     1225            logStringF(hModule, "Uninstalling NetLwf done, error = %#x", uErr);
    11981226        }
    11991227        else
    1200             logStringF(hModule, L"UninstallNetLwf: doNetCfgInit failed, error = %#x", uErr);
     1228            logStringF(hModule, "UninstallNetLwf: doNetCfgInit failed, error = %#x", uErr);
    12011229    }
    12021230    __finally
     
    12341262    {
    12351263
    1236         logStringF(hModule, L"InstallNetLwf: Installing NetLwf");
     1264        logStringF(hModule, "InstallNetLwf: Installing NetLwf");
    12371265
    12381266        uErr = doNetCfgInit(hModule, &pNetCfg, TRUE);
     
    12521280                    }
    12531281
    1254                     wcscat(wszInf, NETLWF_INF_NAME);
     1282                    int vrc = RTUtf16Cat(wszInf, RT_ELEMENTS(wszInf), NETLWF_INF_NAME);
     1283                    AssertRC(vrc);
    12551284
    12561285                    HRESULT hr = VBoxNetCfgWinNetLwfInstall(pNetCfg, wszInf);
    12571286                    if (FAILED(hr))
    1258                         logStringF(hModule, L"InstallNetLwf: VBoxNetCfgWinNetLwfInstall failed, error = %#x", hr);
     1287                        logStringF(hModule, "InstallNetLwf: VBoxNetCfgWinNetLwfInstall failed, error = %#x", hr);
    12591288
    12601289                    uErr = errorConvertFromHResult(hModule, hr);
     
    12621291                else
    12631292                {
    1264                     logStringF(hModule, L"vboxNetFltQueryInfArray: Empty installation directory");
     1293                    logStringF(hModule, "vboxNetFltQueryInfArray: Empty installation directory");
    12651294                    uErr = ERROR_GEN_FAILURE;
    12661295                }
    12671296            }
    12681297            else
    1269                 logStringF(hModule, L"vboxNetFltQueryInfArray: MsiGetPropertyW failed, error = %#x", uErr);
     1298                logStringF(hModule, "vboxNetFltQueryInfArray: MsiGetPropertyW failed, error = %#x", uErr);
    12701299
    12711300            VBoxNetCfgWinReleaseINetCfg(pNetCfg, TRUE);
    12721301
    1273             logStringF(hModule, L"InstallNetLwf: Done");
     1302            logStringF(hModule, "InstallNetLwf: Done");
    12741303        }
    12751304        else
    1276             logStringF(hModule, L"InstallNetLwf: doNetCfgInit failed, error = %#x", uErr);
     1305            logStringF(hModule, "InstallNetLwf: doNetCfgInit failed, error = %#x", uErr);
    12771306    }
    12781307    __finally
     
    13361365                ULONG cbName = sizeof(ConnectoinName);
    13371366
    1338                 HRESULT hr = VBoxNetCfgWinGenHostonlyConnectionName (DevName, ConnectoinName, &cbName);
     1367                HRESULT hr = VBoxNetCfgWinGenHostonlyConnectionName(DevName, ConnectoinName, &cbName);
    13391368                NonStandardAssert(hr == S_OK);
    13401369                if (SUCCEEDED(hr))
     
    13631392    BOOL fSetupModeInteractive = SetupSetNonInteractiveMode(FALSE);
    13641393
    1365     logStringF(hModule, L"CreateHostOnlyInterface: Creating host-only interface");
     1394    logStringF(hModule, "CreateHostOnlyInterface: Creating host-only interface");
    13661395
    13671396    HRESULT hr = E_FAIL;
    13681397    GUID guid;
    13691398    WCHAR wszMpInf[MAX_PATH];
    1370     DWORD cchMpInf = RT_ELEMENTS(wszMpInf) - (DWORD)wcslen(pwszInfName) - 1 - 1;
     1399    DWORD cwcMpInf = RT_ELEMENTS(wszMpInf) - (DWORD)RTUtf16Len(pwszInfName) - 1 - 1;
    13711400    LPCWSTR pwszInfPath = NULL;
    13721401    bool fIsFile = false;
    1373     UINT uErr = MsiGetPropertyW(hModule, L"CustomActionData", wszMpInf, &cchMpInf);
     1402    UINT uErr = MsiGetPropertyW(hModule, L"CustomActionData", wszMpInf, &cwcMpInf);
    13741403    if (uErr == ERROR_SUCCESS)
    13751404    {
    1376         if (cchMpInf)
    1377         {
    1378             logStringF(hModule, L"CreateHostOnlyInterface: NetAdpDir property = %s", wszMpInf);
    1379             if (wszMpInf[cchMpInf - 1] != L'\\')
    1380             {
    1381                 wszMpInf[cchMpInf++] = L'\\';
    1382                 wszMpInf[cchMpInf]   = L'\0';
    1383             }
    1384 
    1385             wcscat(wszMpInf, pwszInfName);
     1405        if (cwcMpInf)
     1406        {
     1407            logStringF(hModule, "CreateHostOnlyInterface: NetAdpDir property = %ls", wszMpInf);
     1408            if (wszMpInf[cwcMpInf - 1] != L'\\')
     1409            {
     1410                wszMpInf[cwcMpInf++] = L'\\';
     1411                wszMpInf[cwcMpInf]   = L'\0';
     1412            }
     1413
     1414            int vrc = RTUtf16Cat(wszMpInf, RT_ELEMENTS(wszMpInf), pwszInfName);
     1415            AssertRC(vrc);
     1416
    13861417            pwszInfPath = wszMpInf;
    13871418            fIsFile = true;
    13881419
    1389             logStringF(hModule, L"CreateHostOnlyInterface: Resulting INF path = %s", pwszInfPath);
     1420            logStringF(hModule, "CreateHostOnlyInterface: Resulting INF path = %ls", pwszInfPath);
    13901421        }
    13911422        else
    1392             logStringF(hModule, L"CreateHostOnlyInterface: VBox installation path is empty");
     1423            logStringF(hModule, "CreateHostOnlyInterface: VBox installation path is empty");
    13931424    }
    13941425    else
    1395         logStringF(hModule, L"CreateHostOnlyInterface: Unable to retrieve VBox installation path, error = %#x", uErr);
     1426        logStringF(hModule, "CreateHostOnlyInterface: Unable to retrieve VBox installation path, error = %#x", uErr);
    13961427
    13971428    /* Make sure the inf file is installed. */
    13981429    if (pwszInfPath != NULL && fIsFile)
    13991430    {
    1400         logStringF(hModule, L"CreateHostOnlyInterface: Calling VBoxDrvCfgInfInstall(%s)", pwszInfPath);
     1431        logStringF(hModule, "CreateHostOnlyInterface: Calling VBoxDrvCfgInfInstall(%ls)", pwszInfPath);
    14011432        hr = VBoxDrvCfgInfInstall(pwszInfPath);
    1402         logStringF(hModule, L"CreateHostOnlyInterface: VBoxDrvCfgInfInstall returns %#x", hr);
     1433        logStringF(hModule, "CreateHostOnlyInterface: VBoxDrvCfgInfInstall returns %#x", hr);
    14031434        if (FAILED(hr))
    1404             logStringF(hModule, L"CreateHostOnlyInterface: Failed to install INF file, error = %#x", hr);
     1435            logStringF(hModule, "CreateHostOnlyInterface: Failed to install INF file, error = %#x", hr);
    14051436    }
    14061437
     
    14141445            if (fRebootRequired)
    14151446            {
    1416                 logStringF(hModule, L"CreateHostOnlyInterface: Reboot required for update, setting REBOOT property to force");
     1447                logStringF(hModule, "CreateHostOnlyInterface: Reboot required for update, setting REBOOT property to force");
    14171448                HRESULT hr2 = MsiSetPropertyW(hModule, L"REBOOT", L"Force");
    14181449                if (hr2 != ERROR_SUCCESS)
    1419                     logStringF(hModule, L"CreateHostOnlyInterface: Failed to set REBOOT property for update, error = %#x", hr2);
     1450                    logStringF(hModule, "CreateHostOnlyInterface: Failed to set REBOOT property for update, error = %#x", hr2);
    14201451            }
    14211452        }
     
    14231454        {
    14241455            //in fail case call CreateHostOnlyInterface
    1425             logStringF(hModule, L"CreateHostOnlyInterface: VBoxNetCfgWinUpdateHostOnlyNetworkInterface failed, hr = %#x", hr);
    1426             logStringF(hModule, L"CreateHostOnlyInterface: calling VBoxNetCfgWinCreateHostOnlyNetworkInterface");
     1456            logStringF(hModule, "CreateHostOnlyInterface: VBoxNetCfgWinUpdateHostOnlyNetworkInterface failed, hr = %#x", hr);
     1457            logStringF(hModule, "CreateHostOnlyInterface: calling VBoxNetCfgWinCreateHostOnlyNetworkInterface");
    14271458#ifdef VBOXNETCFG_DELAYEDRENAME
    14281459            BSTR devId;
     
    14311462            hr = VBoxNetCfgWinCreateHostOnlyNetworkInterface(pwszInfPath, fIsFile, NULL, &guid, NULL, NULL);
    14321463#endif /* !VBOXNETCFG_DELAYEDRENAME */
    1433             logStringF(hModule, L"CreateHostOnlyInterface: VBoxNetCfgWinCreateHostOnlyNetworkInterface returns %#x", hr);
     1464            logStringF(hModule, "CreateHostOnlyInterface: VBoxNetCfgWinCreateHostOnlyNetworkInterface returns %#x", hr);
    14341465            if (SUCCEEDED(hr))
    14351466            {
    14361467                ULONG ip = inet_addr("192.168.56.1");
    14371468                ULONG mask = inet_addr("255.255.255.0");
    1438                 logStringF(hModule, L"CreateHostOnlyInterface: calling VBoxNetCfgWinEnableStaticIpConfig");
     1469                logStringF(hModule, "CreateHostOnlyInterface: calling VBoxNetCfgWinEnableStaticIpConfig");
    14391470                hr = VBoxNetCfgWinEnableStaticIpConfig(&guid, ip, mask);
    1440                 logStringF(hModule, L"CreateHostOnlyInterface: VBoxNetCfgWinEnableStaticIpConfig returns %#x", hr);
     1471                logStringF(hModule, "CreateHostOnlyInterface: VBoxNetCfgWinEnableStaticIpConfig returns %#x", hr);
    14411472                if (FAILED(hr))
    1442                     logStringF(hModule, L"CreateHostOnlyInterface: VBoxNetCfgWinEnableStaticIpConfig failed, error = %#x", hr);
     1473                    logStringF(hModule, "CreateHostOnlyInterface: VBoxNetCfgWinEnableStaticIpConfig failed, error = %#x", hr);
    14431474#ifdef VBOXNETCFG_DELAYEDRENAME
    14441475                hr = VBoxNetCfgWinRenameHostOnlyConnection(&guid, devId, NULL);
    14451476                if (FAILED(hr))
    1446                     logStringF(hModule, L"CreateHostOnlyInterface: VBoxNetCfgWinRenameHostOnlyConnection failed, error = %#x", hr);
     1477                    logStringF(hModule, "CreateHostOnlyInterface: VBoxNetCfgWinRenameHostOnlyConnection failed, error = %#x", hr);
    14471478                SysFreeString(devId);
    14481479#endif /* VBOXNETCFG_DELAYEDRENAME */
    14491480            }
    14501481            else
    1451                 logStringF(hModule, L"CreateHostOnlyInterface: VBoxNetCfgWinCreateHostOnlyNetworkInterface failed, error = %#x", hr);
     1482                logStringF(hModule, "CreateHostOnlyInterface: VBoxNetCfgWinCreateHostOnlyNetworkInterface failed, error = %#x", hr);
    14521483        }
    14531484    }
    14541485
    14551486    if (SUCCEEDED(hr))
    1456         logStringF(hModule, L"CreateHostOnlyInterface: Creating host-only interface done");
     1487        logStringF(hModule, "CreateHostOnlyInterface: Creating host-only interface done");
    14571488
    14581489    /* Restore original setup mode. */
    1459     logStringF(hModule, L"CreateHostOnlyInterface: Almost done...");
     1490    logStringF(hModule, "CreateHostOnlyInterface: Almost done...");
    14601491    if (fSetupModeInteractive)
    14611492        SetupSetNonInteractiveMode(fSetupModeInteractive);
     
    14651496#endif /* VBOX_WITH_NETFLT */
    14661497
    1467     logStringF(hModule, L"CreateHostOnlyInterface: Returns success (ignoring all failures)");
     1498    logStringF(hModule, "CreateHostOnlyInterface: Returns success (ignoring all failures)");
    14681499    /* Never fail the install even if we did not succeed. */
    14691500    return ERROR_SUCCESS;
     
    14771508UINT __stdcall Ndis6CreateHostOnlyInterface(MSIHANDLE hModule)
    14781509{
     1510#if 0 /* Trick for allowing the debugger to be attached. */
     1511    for (unsigned i = 0; i < 128 && !IsDebuggerPresent(); i++)
     1512    {
     1513        logStringF(hModule, "Waiting for debugger to attach: windbg -p %u", GetCurrentProcessId());
     1514        Sleep(1001);
     1515    }
     1516    Sleep(1002);
     1517    __debugbreak();
     1518#endif
    14791519    return _createHostOnlyInterface(hModule, NETADP_ID, L"VBoxNetAdp6.inf");
    14801520}
     
    14851525    netCfgLoggerEnable(hModule);
    14861526
    1487     logStringF(hModule, L"RemoveHostOnlyInterfaces: Removing all host-only interfaces");
     1527    logStringF(hModule, "RemoveHostOnlyInterfaces: Removing all host-only interfaces");
    14881528
    14891529    BOOL fSetupModeInteractive = SetupSetNonInteractiveMode(FALSE);
     
    14941534        hr = VBoxDrvCfgInfUninstallAllSetupDi(&GUID_DEVCLASS_NET, L"Net", pwszId, SUOI_FORCEDELETE/* could be SUOI_FORCEDELETE */);
    14951535        if (FAILED(hr))
    1496             logStringF(hModule, L"RemoveHostOnlyInterfaces: NetAdp uninstalled successfully, but failed to remove INF files");
     1536            logStringF(hModule, "RemoveHostOnlyInterfaces: NetAdp uninstalled successfully, but failed to remove INF files");
    14971537        else
    1498             logStringF(hModule, L"RemoveHostOnlyInterfaces: NetAdp uninstalled successfully");
     1538            logStringF(hModule, "RemoveHostOnlyInterfaces: NetAdp uninstalled successfully");
    14991539    }
    15001540    else
    1501         logStringF(hModule, L"RemoveHostOnlyInterfaces: NetAdp uninstall failed, hr = %#x", hr);
     1541        logStringF(hModule, "RemoveHostOnlyInterfaces: NetAdp uninstall failed, hr = %#x", hr);
    15021542
    15031543    /* Restore original setup mode. */
     
    15221562    netCfgLoggerEnable(hModule);
    15231563
    1524     logStringF(hModule, L"StopHostOnlyInterfaces: Stopping all host-only interfaces");
     1564    logStringF(hModule, "StopHostOnlyInterfaces: Stopping all host-only interfaces");
    15251565
    15261566    BOOL fSetupModeInteractive = SetupSetNonInteractiveMode(FALSE);
     
    15281568    HRESULT hr = VBoxNetCfgWinPropChangeAllNetDevicesOfId(pwszId, VBOXNECTFGWINPROPCHANGE_TYPE_DISABLE);
    15291569    if (SUCCEEDED(hr))
    1530         logStringF(hModule, L"StopHostOnlyInterfaces: Disabling host interfaces was successful, hr = %#x", hr);
     1570        logStringF(hModule, "StopHostOnlyInterfaces: Disabling host interfaces was successful, hr = %#x", hr);
    15311571    else
    1532         logStringF(hModule, L"StopHostOnlyInterfaces: Disabling host interfaces failed, hr = %#x", hr);
     1572        logStringF(hModule, "StopHostOnlyInterfaces: Disabling host interfaces failed, hr = %#x", hr);
    15331573
    15341574    /* Restore original setup mode. */
     
    15531593    netCfgLoggerEnable(hModule);
    15541594
    1555     logStringF(hModule, L"UpdateHostOnlyInterfaces: Updating all host-only interfaces");
     1595    logStringF(hModule, "UpdateHostOnlyInterfaces: Updating all host-only interfaces");
    15561596
    15571597    BOOL fSetupModeInteractive = SetupSetNonInteractiveMode(FALSE);
    15581598
    15591599    WCHAR wszMpInf[MAX_PATH];
    1560     DWORD cchMpInf = RT_ELEMENTS(wszMpInf) - (DWORD)wcslen(pwszInfName) - 1 - 1;
     1600    DWORD cwcMpInf = RT_ELEMENTS(wszMpInf) - (DWORD)RTUtf16Len(pwszInfName) - 1 - 1;
    15611601    LPCWSTR pwszInfPath = NULL;
    15621602    bool fIsFile = false;
    1563     UINT uErr = MsiGetPropertyW(hModule, L"CustomActionData", wszMpInf, &cchMpInf);
     1603    UINT uErr = MsiGetPropertyW(hModule, L"CustomActionData", wszMpInf, &cwcMpInf);
    15641604    if (uErr == ERROR_SUCCESS)
    15651605    {
    1566         if (cchMpInf)
    1567         {
    1568             logStringF(hModule, L"UpdateHostOnlyInterfaces: NetAdpDir property = %s", wszMpInf);
    1569             if (wszMpInf[cchMpInf - 1] != L'\\')
    1570             {
    1571                 wszMpInf[cchMpInf++] = L'\\';
    1572                 wszMpInf[cchMpInf]   = L'\0';
    1573             }
    1574 
    1575             wcscat(wszMpInf, pwszInfName);
     1606        if (cwcMpInf)
     1607        {
     1608            logStringF(hModule, "UpdateHostOnlyInterfaces: NetAdpDir property = %ls", wszMpInf);
     1609            if (wszMpInf[cwcMpInf - 1] != L'\\')
     1610            {
     1611                wszMpInf[cwcMpInf++] = L'\\';
     1612                wszMpInf[cwcMpInf]   = L'\0';
     1613            }
     1614
     1615            int vrc = RTUtf16Cat(wszMpInf, RT_ELEMENTS(wszMpInf), pwszInfName);
     1616             AssertRC(vrc);
    15761617            pwszInfPath = wszMpInf;
    15771618            fIsFile = true;
    15781619
    1579             logStringF(hModule, L"UpdateHostOnlyInterfaces: Resulting INF path = %s", pwszInfPath);
     1620            logStringF(hModule, "UpdateHostOnlyInterfaces: Resulting INF path = %ls", pwszInfPath);
    15801621
    15811622            DWORD attrFile = GetFileAttributesW(pwszInfPath);
     
    15831624            {
    15841625                DWORD dwErr = GetLastError();
    1585                 logStringF(hModule, L"UpdateHostOnlyInterfaces: File \"%s\" not found, dwErr=%ld", pwszInfPath, dwErr);
     1626                logStringF(hModule, "UpdateHostOnlyInterfaces: File \"%ls\" not found, dwErr=%ld", pwszInfPath, dwErr);
    15861627            }
    15871628            else
    15881629            {
    1589                 logStringF(hModule, L"UpdateHostOnlyInterfaces: File \"%s\" exists", pwszInfPath);
     1630                logStringF(hModule, "UpdateHostOnlyInterfaces: File \"%ls\" exists", pwszInfPath);
    15901631
    15911632                BOOL fRebootRequired = FALSE;
     
    15951636                    if (fRebootRequired)
    15961637                    {
    1597                         logStringF(hModule, L"UpdateHostOnlyInterfaces: Reboot required, setting REBOOT property to force");
     1638                        logStringF(hModule, "UpdateHostOnlyInterfaces: Reboot required, setting REBOOT property to force");
    15981639                        HRESULT hr2 = MsiSetPropertyW(hModule, L"REBOOT", L"Force");
    15991640                        if (hr2 != ERROR_SUCCESS)
    1600                             logStringF(hModule, L"UpdateHostOnlyInterfaces: Failed to set REBOOT property, error = %#x", hr2);
     1641                            logStringF(hModule, "UpdateHostOnlyInterfaces: Failed to set REBOOT property, error = %#x", hr2);
    16011642                    }
    16021643                }
    16031644                else
    1604                     logStringF(hModule, L"UpdateHostOnlyInterfaces: VBoxNetCfgWinUpdateHostOnlyNetworkInterface failed, hr = %#x", hr);
     1645                    logStringF(hModule, "UpdateHostOnlyInterfaces: VBoxNetCfgWinUpdateHostOnlyNetworkInterface failed, hr = %#x", hr);
    16051646            }
    16061647        }
    16071648        else
    1608             logStringF(hModule, L"UpdateHostOnlyInterfaces: VBox installation path is empty");
     1649            logStringF(hModule, "UpdateHostOnlyInterfaces: VBox installation path is empty");
    16091650    }
    16101651    else
    1611         logStringF(hModule, L"UpdateHostOnlyInterfaces: Unable to retrieve VBox installation path, error = %#x", uErr);
     1652        logStringF(hModule, "UpdateHostOnlyInterfaces: Unable to retrieve VBox installation path, error = %#x", uErr);
    16121653
    16131654    /* Restore original setup mode. */
     
    16441685    __try
    16451686    {
    1646         logStringF(hModule, L"Uninstalling NetAdp");
     1687        logStringF(hModule, "Uninstalling NetAdp");
    16471688
    16481689        uErr = doNetCfgInit(hModule, &pNetCfg, TRUE);
     
    16511692            HRESULT hr = VBoxNetCfgWinNetAdpUninstall(pNetCfg, pwszId);
    16521693            if (hr != S_OK)
    1653                 logStringF(hModule, L"UninstallNetAdp: VBoxNetCfgWinUninstallComponent failed, error = %#x", hr);
     1694                logStringF(hModule, "UninstallNetAdp: VBoxNetCfgWinUninstallComponent failed, error = %#x", hr);
    16541695
    16551696            uErr = errorConvertFromHResult(hModule, hr);
     
    16571698            VBoxNetCfgWinReleaseINetCfg(pNetCfg, TRUE);
    16581699
    1659             logStringF(hModule, L"Uninstalling NetAdp done, error = %#x", uErr);
     1700            logStringF(hModule, "Uninstalling NetAdp done, error = %#x", uErr);
    16601701        }
    16611702        else
    1662             logStringF(hModule, L"UninstallNetAdp: doNetCfgInit failed, error = %#x", uErr);
     1703            logStringF(hModule, "UninstallNetAdp: doNetCfgInit failed, error = %#x", uErr);
    16631704    }
    16641705    __finally
     
    17241765                lStatus = RegQueryValueExW(hNetCardGUID, L"ProviderName", NULL, &dwKeyType, (LPBYTE)wszNetProviderName, &dwLen);
    17251766
    1726                 if (   !wcscmp(wszNetCfgInstanceId, pwszGUID)
    1727                     && !wcscmp(wszNetProductName, L"VirtualBox TAP Adapter")
    1728                     && (   (!wcscmp(wszNetProviderName, L"innotek GmbH")) /* Legacy stuff. */
    1729                         || (!wcscmp(wszNetProviderName, L"Sun Microsystems, Inc.")) /* Legacy stuff. */
    1730                         || (!wcscmp(wszNetProviderName, MY_WTEXT(VBOX_VENDOR))) /* Reflects current vendor string. */
     1767                if (   !RTUtf16Cmp(wszNetCfgInstanceId, pwszGUID)
     1768                    && !RTUtf16Cmp(wszNetProductName, L"VirtualBox TAP Adapter")
     1769                    && (   (!RTUtf16Cmp(wszNetProviderName, L"innotek GmbH")) /* Legacy stuff. */
     1770                        || (!RTUtf16Cmp(wszNetProviderName, L"Sun Microsystems, Inc.")) /* Legacy stuff. */
     1771                        || (!RTUtf16Cmp(wszNetProviderName, MY_WTEXT(VBOX_VENDOR))) /* Reflects current vendor string. */
    17311772                       )
    17321773                   )
     
    17461787}
    17471788
    1748 /** @todo r=andy BUGBUG WTF! Why do we a) set the rc to 0 (success), and b) need this macro at all!? */
     1789/** @todo r=andy BUGBUG WTF! Why do we a) set the rc to 0 (success), and b) need this macro at all!?
     1790 *
     1791 * @todo r=bird: Because it's returning a bool, not int? The return code is
     1792 * ignored anyway, both internally in removeNetworkInterface and in it's caller.
     1793 * There is similar code in VBoxNetCfg.cpp, which is probably where it was copied from. */
    17491794#define SetErrBreak(args) \
    17501795    if (1) { \
     
    17691814        {
    17701815            WCHAR wszRegLocation[256];
    1771             swprintf_s(wszRegLocation, RT_ELEMENTS(wszRegLocation),
    1772                        L"SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\%s", pwszGUID);
    1773             LONG lStatus = RegOpenKeyExW(HKEY_LOCAL_MACHINE, wszRegLocation, 0, KEY_READ, &hkeyNetwork);
    1774             if (lStatus != ERROR_SUCCESS || !hkeyNetwork)
    1775                 SetErrBreak((hModule, L"VBox HostInterfaces: Host interface network was not found in registry (%s)! [1]",
    1776                              wszRegLocation));
    1777 
    1778             lStatus = RegOpenKeyExW(hkeyNetwork, L"Connection", 0, KEY_READ, &hkeyConnection);
    1779             if (lStatus != ERROR_SUCCESS || !hkeyConnection)
    1780                 SetErrBreak((hModule, L"VBox HostInterfaces: Host interface network was not found in registry (%s)! [2]",
    1781                              wszRegLocation));
     1816            RTUtf16Printf(wszRegLocation, RT_ELEMENTS(wszRegLocation),
     1817                          "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\%ls", pwszGUID);
     1818            LONG lrc = RegOpenKeyExW(HKEY_LOCAL_MACHINE, wszRegLocation, 0, KEY_READ, &hkeyNetwork);
     1819            if (lrc != ERROR_SUCCESS || !hkeyNetwork)
     1820                SetErrBreak((hModule, "VBox HostInterfaces: Host interface network was not found in registry (%ls)! (lrc=%d) [1]",
     1821                             wszRegLocation, lrc));
     1822
     1823            lrc = RegOpenKeyExW(hkeyNetwork, L"Connection", 0, KEY_READ, &hkeyConnection);
     1824            if (lrc != ERROR_SUCCESS || !hkeyConnection)
     1825                SetErrBreak((hModule, "VBox HostInterfaces: Host interface network was not found in registry (%ls)! (lrc=%d) [2]",
     1826                             wszRegLocation, lrc));
    17821827
    17831828            DWORD len = sizeof(wszPnPInstanceId);
    17841829            DWORD dwKeyType;
    1785             lStatus = RegQueryValueExW(hkeyConnection, L"PnPInstanceID", NULL, &dwKeyType, (LPBYTE)&wszPnPInstanceId[0], &len);
    1786             if (lStatus != ERROR_SUCCESS || (dwKeyType != REG_SZ))
    1787                 SetErrBreak((hModule, L"VBox HostInterfaces: Host interface network was not found in registry (%s)! [3]",
    1788                              wszRegLocation));
     1830            lrc = RegQueryValueExW(hkeyConnection, L"PnPInstanceID", NULL, &dwKeyType, (LPBYTE)&wszPnPInstanceId[0], &len);
     1831            if (lrc != ERROR_SUCCESS || dwKeyType != REG_SZ)
     1832                SetErrBreak((hModule, "VBox HostInterfaces: Host interface network was not found in registry (%ls)! (lrc=%d) [3]",
     1833                             wszRegLocation, lrc));
    17891834        }
    17901835        while (0);
     
    18051850        do /* break-loop */
    18061851        {
     1852            /* initialize the structure size */
     1853            SP_DEVINFO_DATA DeviceInfoData = { sizeof(DeviceInfoData) };
     1854
     1855            /* copy the net class GUID */
    18071856            GUID netGuid;
    1808             SP_DEVINFO_DATA DeviceInfoData;
    1809             DWORD index = 0;
    1810             DWORD size = 0;
    1811 
    1812             /* initialize the structure size */
    1813             DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
    1814 
    1815             /* copy the net class GUID */
    18161857            memcpy(&netGuid, &GUID_DEVCLASS_NET, sizeof (GUID_DEVCLASS_NET));
    18171858
     
    18201861            if (hDeviceInfo == INVALID_HANDLE_VALUE)
    18211862            {
    1822                 logStringF(hModule, L"VBox HostInterfaces: SetupDiGetClassDevs failed (0x%08X)!", GetLastError());
    1823                 SetErrBreak((hModule, L"VBox HostInterfaces: Uninstallation failed!"));
    1824             }
    1825 
     1863                logStringF(hModule, "VBox HostInterfaces: SetupDiGetClassDevs failed (0x%08X)!", GetLastError());
     1864                SetErrBreak((hModule, "VBox HostInterfaces: Uninstallation failed!"));
     1865            }
     1866
     1867            /* enumerate the driver info list */
    18261868            BOOL fFoundDevice = FALSE;
    1827 
    1828             /* enumerate the driver info list */
    1829             while (TRUE)
    1830             {
    1831                 WCHAR *pwszDeviceHwid;
    1832 
     1869            for (DWORD index = 0;; index++)
     1870            {
    18331871                fResult = SetupDiEnumDeviceInfo(hDeviceInfo, index, &DeviceInfoData);
    18341872                if (!fResult)
     
    18361874                    if (GetLastError() == ERROR_NO_MORE_ITEMS)
    18371875                        break;
    1838                     else
    1839                     {
    1840                         index++;
    1841                         continue;
    1842                     }
     1876                    continue;
    18431877                }
    18441878
    18451879                /* try to get the hardware ID registry property */
     1880                WCHAR *pwszDeviceHwid;
     1881                DWORD size = 0;
    18461882                fResult = SetupDiGetDeviceRegistryProperty(hDeviceInfo,
    18471883                                                           &DeviceInfoData,
     
    18541890                {
    18551891                    if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
     1892                        continue;
     1893
     1894                    pwszDeviceHwid = (WCHAR *)RTMemAllocZ(size);
     1895                    if (!pwszDeviceHwid)
     1896                        continue;
     1897
     1898                    fResult = SetupDiGetDeviceRegistryProperty(hDeviceInfo,
     1899                                                               &DeviceInfoData,
     1900                                                               SPDRP_HARDWAREID,
     1901                                                               NULL,
     1902                                                               (PBYTE)pwszDeviceHwid,
     1903                                                               size,
     1904                                                               &size);
     1905                    if (!fResult)
    18561906                    {
    1857                         index++;
     1907                        RTMemFree(pwszDeviceHwid);
    18581908                        continue;
    1859                     }
    1860 
    1861                     pwszDeviceHwid = (WCHAR *)malloc(size);
    1862                     if (pwszDeviceHwid)
    1863                     {
    1864                         fResult = SetupDiGetDeviceRegistryProperty(hDeviceInfo,
    1865                                                                    &DeviceInfoData,
    1866                                                                    SPDRP_HARDWAREID,
    1867                                                                    NULL,
    1868                                                                    (PBYTE)pwszDeviceHwid,
    1869                                                                    size,
    1870                                                                    NULL);
    1871                         if (!fResult)
    1872                         {
    1873                             free(pwszDeviceHwid);
    1874                             pwszDeviceHwid = NULL;
    1875                             index++;
    1876                             continue;
    1877                         }
    18781909                    }
    18791910                }
     
    18811912                {
    18821913                    /* something is wrong.  This shouldn't have worked with a NULL buffer */
    1883                     index++;
    18841914                    continue;
    18851915                }
    18861916
    18871917                for (WCHAR *t = pwszDeviceHwid;
    1888                      t && *t && t < &pwszDeviceHwid[size / sizeof(WCHAR)];
    1889                      t += wcslen(t) + 1)
     1918                     *t && t < &pwszDeviceHwid[size / sizeof(WCHAR)];
     1919                     t += RTUtf16Len(t) + 1)
    18901920                {
    1891                     if (!_wcsicmp(L"vboxtap", t))
     1921                    if (RTUtf16ICmpAscii(t, "vboxtap") == 0)
    18921922                    {
    1893                           /* get the device instance ID */
    1894                           WCHAR wszDevID[MAX_DEVICE_ID_LEN];
    1895                           if (CM_Get_Device_IDW(DeviceInfoData.DevInst,
    1896                                                 wszDevID, MAX_DEVICE_ID_LEN, 0) == CR_SUCCESS)
    1897                           {
    1898                               /* compare to what we determined before */
    1899                               if (!wcscmp(wszDevID, wszPnPInstanceId))
    1900                               {
    1901                                   fFoundDevice = TRUE;
    1902                                   break;
    1903                               }
    1904                           }
     1923                        /* get the device instance ID */
     1924                        WCHAR wszDevID[MAX_DEVICE_ID_LEN];
     1925                        if (CM_Get_Device_IDW(DeviceInfoData.DevInst, wszDevID, MAX_DEVICE_ID_LEN, 0) == CR_SUCCESS)
     1926                        {
     1927                            /* compare to what we determined before */
     1928                            if (RTUtf16Cmp(wszDevID, wszPnPInstanceId) == 0)
     1929                            {
     1930                                fFoundDevice = TRUE;
     1931                                break;
     1932                            }
     1933                        }
    19051934                    }
    19061935                }
    19071936
    1908                 if (pwszDeviceHwid)
    1909                 {
    1910                     free(pwszDeviceHwid);
    1911                     pwszDeviceHwid = NULL;
    1912                 }
     1937                RTMemFree(pwszDeviceHwid);
    19131938
    19141939                if (fFoundDevice)
    19151940                    break;
    1916 
    1917                 index++;
    19181941            }
    19191942
     
    19231946                if (!fResult)
    19241947                {
    1925                     logStringF(hModule, L"VBox HostInterfaces: SetupDiSetSelectedDevice failed (0x%08X)!", GetLastError());
    1926                     SetErrBreak((hModule, L"VBox HostInterfaces: Uninstallation failed!"));
     1948                    logStringF(hModule, "VBox HostInterfaces: SetupDiSetSelectedDevice failed (0x%08X)!", GetLastError());
     1949                    SetErrBreak((hModule, "VBox HostInterfaces: Uninstallation failed!"));
    19271950                }
    19281951
     
    19301953                if (!fResult)
    19311954                {
    1932                     logStringF(hModule, L"VBox HostInterfaces: SetupDiCallClassInstaller (DIF_REMOVE) failed (0x%08X)!", GetLastError());
    1933                     SetErrBreak((hModule, L"VBox HostInterfaces: Uninstallation failed!"));
     1955                    logStringF(hModule, "VBox HostInterfaces: SetupDiCallClassInstaller (DIF_REMOVE) failed (0x%08X)!", GetLastError());
     1956                    SetErrBreak((hModule, "VBox HostInterfaces: Uninstallation failed!"));
    19341957                }
    19351958            }
    19361959            else
    1937                 SetErrBreak((hModule, L"VBox HostInterfaces: Host interface network device not found!"));
     1960                SetErrBreak((hModule, "VBox HostInterfaces: Host interface network device not found!"));
    19381961        } while (0);
    19391962
     
    19501973    HKEY hCtrlNet;
    19511974
    1952     LONG lStatus = RegOpenKeyExW(HKEY_LOCAL_MACHINE, s_wszNetworkKey, 0, KEY_READ, &hCtrlNet);
    1953     if (lStatus == ERROR_SUCCESS)
    1954     {
    1955         logStringF(hModule, L"VBox HostInterfaces: Enumerating interfaces ...");
     1975    LSTATUS lrc = RegOpenKeyExW(HKEY_LOCAL_MACHINE, s_wszNetworkKey, 0, KEY_READ, &hCtrlNet);
     1976    if (lrc == ERROR_SUCCESS)
     1977    {
     1978        logStringF(hModule, "VBox HostInterfaces: Enumerating interfaces ...");
    19561979        for (int i = 0; ; ++i)
    19571980        {
    19581981            WCHAR wszNetworkGUID[256] = { 0 };
    19591982            DWORD dwLen = (DWORD)sizeof(wszNetworkGUID);
    1960             lStatus = RegEnumKeyExW(hCtrlNet, i, wszNetworkGUID, &dwLen, NULL, NULL, NULL, NULL);
    1961             if (lStatus != ERROR_SUCCESS)
    1962             {
    1963                 switch (lStatus)
     1983            lrc = RegEnumKeyExW(hCtrlNet, i, wszNetworkGUID, &dwLen, NULL, NULL, NULL, NULL);
     1984            if (lrc != ERROR_SUCCESS)
     1985            {
     1986                switch (lrc)
    19641987                {
    19651988                    case ERROR_NO_MORE_ITEMS:
    1966                         logStringF(hModule, L"VBox HostInterfaces: No interfaces found.");
     1989                        logStringF(hModule, "VBox HostInterfaces: No interfaces found.");
    19671990                        break;
    19681991                    default:
    1969                         logStringF(hModule, L"VBox HostInterfaces: Enumeration failed: %ld", lStatus);
     1992                        logStringF(hModule, "VBox HostInterfaces: Enumeration failed: %ld", lrc);
    19701993                        break;
    19711994                }
     
    19751998            if (isTAPDevice(wszNetworkGUID))
    19761999            {
    1977                 logStringF(hModule, L"VBox HostInterfaces: Removing interface \"%s\" ...", wszNetworkGUID);
     2000                logStringF(hModule, "VBox HostInterfaces: Removing interface \"%ls\" ...", wszNetworkGUID);
    19782001                removeNetworkInterface(hModule, wszNetworkGUID);
    1979                 lStatus = RegDeleteKeyW(hCtrlNet, wszNetworkGUID);
     2002                lrc = RegDeleteKeyW(hCtrlNet, wszNetworkGUID);
    19802003            }
    19812004        }
    19822005        RegCloseKey(hCtrlNet);
    1983         logStringF(hModule, L"VBox HostInterfaces: Removing interfaces done.");
     2006        logStringF(hModule, "VBox HostInterfaces: Removing interfaces done.");
    19842007    }
    19852008    return ERROR_SUCCESS;
     
    20162039            QueryServiceStatus(hService, &Status);
    20172040            if (Status.dwCurrentState == SERVICE_STOPPED)
    2018                 logStringF(hModule, L"VBoxDrv: The service old service was already stopped");
     2041                logStringF(hModule, "VBoxDrv: The service old service was already stopped");
    20192042            else
    20202043            {
    2021                 logStringF(hModule, L"VBoxDrv: Stopping the service (state %u)", Status.dwCurrentState);
     2044                logStringF(hModule, "VBoxDrv: Stopping the service (state %u)", Status.dwCurrentState);
    20222045                if (ControlService(hService, SERVICE_CONTROL_STOP, &Status))
    20232046                {
     
    20312054
    20322055                    if (Status.dwCurrentState == SERVICE_STOPPED)
    2033                         logStringF(hModule, L"VBoxDrv: Stopped service");
     2056                        logStringF(hModule, "VBoxDrv: Stopped service");
    20342057                    else
    2035                         logStringF(hModule, L"VBoxDrv: Failed to stop the service, status: %u", Status.dwCurrentState);
     2058                        logStringF(hModule, "VBoxDrv: Failed to stop the service, status: %u", Status.dwCurrentState);
    20362059                }
    20372060                else
     
    20402063                    if (   Status.dwCurrentState == SERVICE_STOP_PENDING
    20412064                        && dwErr == ERROR_SERVICE_CANNOT_ACCEPT_CTRL)
    2042                         logStringF(hModule, L"VBoxDrv: Failed to stop the service: stop pending, not accepting control messages");
     2065                        logStringF(hModule, "VBoxDrv: Failed to stop the service: stop pending, not accepting control messages");
    20432066                    else
    2044                         logStringF(hModule, L"VBoxDrv: Failed to stop the service: dwErr=%u status=%u", dwErr, Status.dwCurrentState);
     2067                        logStringF(hModule, "VBoxDrv: Failed to stop the service: dwErr=%u status=%u", dwErr, Status.dwCurrentState);
    20452068                }
    20462069            }
     
    20502073             */
    20512074            if (DeleteService(hService))
    2052                 logStringF(hModule, L"VBoxDrv: Successfully delete service");
     2075                logStringF(hModule, "VBoxDrv: Successfully delete service");
    20532076            else
    2054                 logStringF(hModule, L"VBoxDrv: Failed to delete the service: %u", GetLastError());
     2077                logStringF(hModule, "VBoxDrv: Failed to delete the service: %u", GetLastError());
    20552078
    20562079            CloseServiceHandle(hService);
     
    20602083            DWORD const dwErr = GetLastError();
    20612084            if (dwErr == ERROR_SERVICE_DOES_NOT_EXIST)
    2062                 logStringF(hModule, L"VBoxDrv: Nothing to do, the old service does not exist");
     2085                logStringF(hModule, "VBoxDrv: Nothing to do, the old service does not exist");
    20632086            else
    2064                 logStringF(hModule, L"VBoxDrv: Failed to open the service: %u", dwErr);
     2087                logStringF(hModule, "VBoxDrv: Failed to open the service: %u", dwErr);
    20652088        }
    20662089
     
    20682091    }
    20692092    else
    2070         logStringF(hModule, L"VBoxDrv: Failed to open service manager (%u).", GetLastError());
     2093        logStringF(hModule, "VBoxDrv: Failed to open service manager (%u).", GetLastError());
    20712094
    20722095    return ERROR_SUCCESS;
  • trunk/src/VBox/Installer/win/Makefile.kmk

    r96428 r96572  
    103103endif
    104104
     105# Aliases for VBOX_SIGN_FILE_FN that allows better control of the MSI and MSM signing.
     106VBOX_SIGN_MSI_FN ?= $(VBOX_SIGN_FILE_FN)
     107VBOX_SIGN_MSM_FN ?= $(VBOX_SIGN_FILE_FN)
     108VBOX_SIGN_CAB_FN ?= $(VBOX_SIGN_FILE_FN)
    105109
    106110#
     
    569573                $(VBOX_PATH_WIX)/difxapp_$(if-expr "$(KBUILD_TARGET_ARCH)" == "x86",x86,x64).wixlib
    570574        $(RM) -f $(VBOX_WIN_INST_OUT_DIR)/NLS/$(lang).mst
    571         $(call VBOX_SIGN_FILE_FN,$$@,$(VBOX_PRODUCT) $(VBOX_VERSION_STRING)r$(VBOX_SVN_REV) ($(KBUILD_TARGET_ARCH)),,,disable-dual-signing)
     575        $(call VBOX_SIGN_MSM_FN,$$@,$(VBOX_PRODUCT) $(VBOX_VERSION_STRING)r$(VBOX_SVN_REV) ($(KBUILD_TARGET_ARCH)),,,disable-dual-signing)
    572576# Create repack script for this step.
    573577        $(APPEND) -tn "$$(VBOX_WIN_INST_REPACK_DIR)/2-link-VBoxMerge$(module)_$(lang).cmd" \
     
    11271131        $(REDIRECT) -C $(@D) -- cscript.exe /nologo $(VBOX_PATH_WISUBSTG) $(@F)
    11281132        $(REDIRECT) -C $(@D) -- cscript.exe /nologo $(VBOX_PATH_WISUMINFO) $@ $(VBOX_INS_PROD_LANG)
    1129         $(call VBOX_SIGN_FILE_FN,$@,$(VBOX_PRODUCT) $(VBOX_VERSION_STRING)r$(VBOX_SVN_REV) ($(KBUILD_TARGET_ARCH)),,,disable-dual-signing)
     1133        $(call VBOX_SIGN_MSI_FN,$@,$(VBOX_PRODUCT) $(VBOX_VERSION_STRING)r$(VBOX_SVN_REV) ($(KBUILD_TARGET_ARCH)),,,disable-dual-signing)
    11301134
    11311135# Create repack script for this step.
     
    11681172                $@ \
    11691173                $(VBOX_WIN_INST_REPACK_DIR)/4-multiarch-$(PACKAGE_NAME_MULTIARCH_FINAL).cmd ) )
    1170         $(if-expr defined(VBOX_WITH_MSM_INSTALL),,$(call VBOX_SIGN_FILE_FN,$(PACKAGE_NAME_MULTIARCH_COMMONCAB)))
     1174        $(if-expr defined(VBOX_WITH_MSM_INSTALL),,$(call VBOX_SIGN_CAB_FN,$(PACKAGE_NAME_MULTIARCH_COMMONCAB)))
    11711175        $(REDIRECT) -C $(@D) -- \
    11721176                $(VBoxStubBld_1_TARGET) -out $@ \
  • trunk/src/VBox/Main/Makefile.kmk

    r96407 r96572  
    772772 VBoxSVC_SDKS.win += VBOX_WIN_NEWDEV
    773773 VBoxSVC_LIBS.win += \
    774         $(PATH_STAGE_LIB)/WinNetConfigNonStatic$(VBOX_SUFF_LIB) \
    775         $(PATH_STAGE_LIB)/VBoxDrvCfg$(VBOX_SUFF_LIB) \
     774        $(PATH_STAGE_LIB)/WinNetConfigDll$(VBOX_SUFF_LIB) \
     775        $(PATH_STAGE_LIB)/VBoxDrvCfgDll$(VBOX_SUFF_LIB) \
    776776        $(PATH_TOOL_$(VBOX_VCC_TOOL)_LIB)/comsupp.lib \
    777777        $(PATH_SDK_$(VBOX_WINPSDK)_LIB)/WbemUuid.Lib
     
    10831083 VBoxC_SDKS.win += VBOX_WIN_NEWDEV
    10841084 VBoxC_LIBS.win += \
    1085         $(PATH_STAGE_LIB)/VBoxDrvCfg$(VBOX_SUFF_LIB) \
    1086         $(PATH_STAGE_LIB)/WinNetConfigNonStatic$(VBOX_SUFF_LIB) \
     1085        $(PATH_STAGE_LIB)/WinNetConfigDll$(VBOX_SUFF_LIB) \
     1086        $(PATH_STAGE_LIB)/VBoxDrvCfgDll$(VBOX_SUFF_LIB) \
    10871087        $(PATH_TOOL_$(VBOX_VCC_TOOL)_LIB)/comsupp.lib \
    10881088        $(PATH_SDK_$(VBOX_WINPSDK)_LIB)/WbemUuid.Lib
Note: See TracChangeset for help on using the changeset viewer.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette