Replace legacy dynamically-loaded functions with statically linked ones

We don't need the dynamic load complexity for these now with baseline
Windows version being Windows 7 SP1. Stuff used only for compatibility
with older versions was dumped.

Change-Id: I810f271796cfd875cfa18a3081c9ad444fe57b3e
Reviewed-on: https://gerrit.libreoffice.org/70321
Tested-by: Jenkins
Reviewed-by: Mike Kaganski <mike.kaganski@collabora.com>
diff --git a/canvas/source/directx/dx_9rm.cxx b/canvas/source/directx/dx_9rm.cxx
index 988f4a0..f1557af 100644
--- a/canvas/source/directx/dx_9rm.cxx
+++ b/canvas/source/directx/dx_9rm.cxx
@@ -65,50 +65,6 @@ namespace dxcanvas
{
    namespace
    {

        // monitorSupport


        class monitorSupport
        {
        public:

            monitorSupport() :
                mhLibrary(LoadLibraryW(L"user32.dll")),
                mpMonitorFromWindow(nullptr)
            {
                if(mhLibrary)
                    mpMonitorFromWindow = reinterpret_cast<fMonitorFromWindow>(
                        GetProcAddress(
                            mhLibrary,"MonitorFromWindow"));
            }

            ~monitorSupport()
            {
                if(mhLibrary)
                    FreeLibrary(mhLibrary);
                mhLibrary=nullptr;
            }

            HMONITOR MonitorFromWindow( HWND hwnd )
            {
                // return adapter_default in case something went wrong...
                if(!mpMonitorFromWindow)
                    return HMONITOR(nullptr);
                // MONITOR_DEFAULTTONEAREST
                const DWORD dwFlags(0x00000002);
                return mpMonitorFromWindow(hwnd,dwFlags);
            }
        private:

            HINSTANCE mhLibrary;
            typedef HMONITOR (WINAPI *fMonitorFromWindow )( HWND hwnd, DWORD dwFlags );
            fMonitorFromWindow mpMonitorFromWindow;
        };

        monitorSupport aMonitorSupport;


        class DXRenderModule;


@@ -1100,7 +1056,7 @@ namespace dxcanvas

        UINT DXRenderModule::getAdapterFromWindow()
        {
            HMONITOR hMonitor(aMonitorSupport.MonitorFromWindow(mhWnd));
            HMONITOR hMonitor(MonitorFromWindow(mhWnd, MONITOR_DEFAULTTONEAREST));
            UINT aAdapterCount(mpDirect3D9->GetAdapterCount());
            for(UINT i=0; i<aAdapterCount; ++i)
                if(hMonitor == mpDirect3D9->GetAdapterMonitor(i))
diff --git a/dbaccess/Executable_odbcconfig.mk b/dbaccess/Executable_odbcconfig.mk
index fdfcbf2..de40bdd 100644
--- a/dbaccess/Executable_odbcconfig.mk
+++ b/dbaccess/Executable_odbcconfig.mk
@@ -15,6 +15,11 @@ $(eval $(call gb_Executable_use_libraries,odbcconfig,\
    comphelper \
))

$(eval $(call gb_Executable_use_system_win32_libs,odbcconfig,\
	legacy_stdio_definitions \
	odbccp32 \
))

$(eval $(call gb_Library_use_sdk_api,odbcconfig))

$(eval $(call gb_Executable_add_exception_objects,odbcconfig,\
diff --git a/dbaccess/win32/source/odbcconfig/odbcconfig.cxx b/dbaccess/win32/source/odbcconfig/odbcconfig.cxx
index 71cb828..e9c4091 100644
--- a/dbaccess/win32/source/odbcconfig/odbcconfig.cxx
+++ b/dbaccess/win32/source/odbcconfig/odbcconfig.cxx
@@ -22,14 +22,7 @@
# define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <sqlext.h>
#include <comphelper/scopeguard.hxx>

// the name of the library which contains the SQLManageDataSources function
#define ODBC_UI_LIB_NAME    L"ODBCCP32.DLL"

// the signature of the SQLManageDataSources function
typedef SQLRETURN (SQL_API* TSQLManageDataSource) (SQLHWND hwndParent);
#include <odbcinst.h>

// displays the error text for the last error (GetLastError), and returns this error value
static int displayLastError()
@@ -109,19 +102,7 @@ extern "C" int APIENTRY wWinMain( HINSTANCE _hAppInstance, HINSTANCE, LPWSTR, in
    if ( !IsWindow( hAppWindow ) )
        return displayLastError();

    HMODULE hModule = LoadLibraryW( ODBC_UI_LIB_NAME );
    if ( hModule == nullptr )
        hModule = LoadLibraryExW( ODBC_UI_LIB_NAME, nullptr, LOAD_WITH_ALTERED_SEARCH_PATH );
    if ( hModule == nullptr )
        return displayLastError();
    comphelper::ScopeGuard hModuleReleaser([hModule]() { FreeLibrary(hModule); });

    FARPROC pManageDSProc = GetProcAddress( hModule, "SQLManageDataSources" );
    if ( pManageDSProc == nullptr )
        return displayLastError();

    TSQLManageDataSource pManageDS = reinterpret_cast<TSQLManageDataSource>(pManageDSProc);
    if ( !( (*pManageDS)( hAppWindow ) ) )
    if (!SQLManageDataSources(hAppWindow))
        return displayLastError();

    return 0;
diff --git a/sal/Library_sal.mk b/sal/Library_sal.mk
index 47f02c8..ff42255 100644
--- a/sal/Library_sal.mk
+++ b/sal/Library_sal.mk
@@ -50,6 +50,8 @@ $(eval $(call gb_Library_use_system_win32_libs,sal,\
	ole32 \
	shell32 \
	user32 \
	userenv \
	wer \
	ws2_32 \
))

diff --git a/sal/osl/w32/module.cxx b/sal/osl/w32/module.cxx
index 8de791a..104a828 100644
--- a/sal/osl/w32/module.cxx
+++ b/sal/osl/w32/module.cxx
@@ -18,7 +18,7 @@
 */

#include "system.h"
#include <tlhelp32.h>
#include <psapi.h>

#include "file_url.hxx"
#include "path_helper.hxx"
@@ -180,206 +180,57 @@ osl_getAsciiFunctionSymbol( oslModule Module, const sal_Char *pSymbol )
    return fncAddr;
}

/*****************************************************************************/
/* Implementation for Windows 95, 98 and Me */
/*****************************************************************************/

/* Undefine because there is no explicit "A" definition */

#ifdef MODULEENTRY32
#undef MODULEENTRY32
#endif

#ifdef LPMODULEENTRY32
#undef LPMODULEENTRY32
#endif

/***************************************************************************************/
/* Implementation for Windows NT, 2K and XP (2K and XP could use the above method too) */
/***************************************************************************************/

#include <imagehlp.h>

typedef BOOL (WINAPI *SymInitialize_PROC)(
    HANDLE   hProcess,
    LPWSTR   UserSearchPath,
    BOOL     fInvadeProcess
    );

typedef BOOL (WINAPI *SymCleanup_PROC)(
    HANDLE hProcess
    );

typedef BOOL (WINAPI *SymGetModuleInfo_PROC)(
    HANDLE              hProcess,
    DWORD               dwAddr,
    PIMAGEHLP_MODULEW   ModuleInfo
    );

/* Seems that IMAGEHLP.DLL is always available on NT 4. But MSDN from Platform SDK says Win 2K is required. MSDN from VS 6.0a says
    it's O.K on NT 4 ???!!!
    BTW: We are using ANSI function because not all version of IMAGEHLP.DLL contain Unicode support
*/

static bool osl_addressGetModuleURL_NT4_( void *pv, rtl_uString **pustrURL )
{
    bool    bSuccess    = false;    /* Assume failure */

    /*  IMAGEHELP.DLL has a bug that it recursively scans subdirectories of
        the root when calling SymInitialize(), so we prefer DBGHELP.DLL
        which exports the same symbols and is shipped with OOo */

    HMODULE     hModImageHelp = LoadLibraryW( L"DBGHELP.DLL" );

    if ( !hModImageHelp )
        hModImageHelp = LoadLibraryW( L"IMAGEHLP.DLL" );

    if ( hModImageHelp )
    {
        SymGetModuleInfo_PROC   lpfnSymGetModuleInfo;
        SymInitialize_PROC      lpfnSymInitialize;
        SymCleanup_PROC         lpfnSymCleanup;

        lpfnSymInitialize = reinterpret_cast<SymInitialize_PROC>(GetProcAddress( hModImageHelp, "SymInitializeW" ));
        lpfnSymCleanup = reinterpret_cast<SymCleanup_PROC>(GetProcAddress( hModImageHelp, "SymCleanup" ));
        lpfnSymGetModuleInfo = reinterpret_cast<SymGetModuleInfo_PROC>(GetProcAddress( hModImageHelp, "SymGetModuleInfoW" ));

        if ( lpfnSymInitialize && lpfnSymCleanup && lpfnSymGetModuleInfo )
        {
            IMAGEHLP_MODULEW ModuleInfo;
            ::osl::LongPathBuffer< sal_Unicode > aModuleFileName( MAX_LONG_PATH );
            LPWSTR lpSearchPath = nullptr;

            if ( GetModuleFileNameW( nullptr, o3tl::toW(aModuleFileName), aModuleFileName.getBufSizeInSymbols() ) )
            {
                wchar_t *pLastBkSlash = wcsrchr( o3tl::toW(aModuleFileName), L'\\' );

                if (
                    pLastBkSlash &&
                    pLastBkSlash > o3tl::toW(aModuleFileName)
                    && *(pLastBkSlash - 1) != L':'
                    && *(pLastBkSlash - 1) != L'\\'
                    )
                {
                    *pLastBkSlash = 0;
                    lpSearchPath = o3tl::toW(aModuleFileName);
                }
            }

            lpfnSymInitialize( GetCurrentProcess(), lpSearchPath, TRUE );

            ZeroMemory( &ModuleInfo, sizeof(ModuleInfo) );
            ModuleInfo.SizeOfStruct = sizeof(ModuleInfo);

            bSuccess = !!lpfnSymGetModuleInfo( GetCurrentProcess(), reinterpret_cast<DWORD_PTR>(pv), &ModuleInfo );

            if ( bSuccess )
            {
                /*  #99182 On localized (non-english) NT4 and XP (!!!) for some libraries the LoadedImageName member of ModuleInfo isn't filled. Because
                    other members ModuleName and ImageName do not contain the full path we can cast the Member
                    BaseOfImage to a HMODULE (on NT it's the same) and use GetModuleFileName to retrieve the full
                    path of the loaded image */

                if ( ModuleInfo.LoadedImageName[0] || GetModuleFileNameW( reinterpret_cast<HMODULE>(ModuleInfo.BaseOfImage), ModuleInfo.LoadedImageName, SAL_N_ELEMENTS(ModuleInfo.LoadedImageName) ) )
                {
                    rtl_uString *ustrSysPath = nullptr;

                    rtl_uString_newFromStr( &ustrSysPath, o3tl::toU(ModuleInfo.LoadedImageName) );
                    OSL_ASSERT(ustrSysPath != nullptr);
                    osl_getFileURLFromSystemPath( ustrSysPath, pustrURL );
                    rtl_uString_release( ustrSysPath );
                }
                else
                    bSuccess = false;
            }

            lpfnSymCleanup( GetCurrentProcess() );
        }

        FreeLibrary( hModImageHelp );
    }

    return bSuccess;
}

typedef struct MODULEINFO {
    LPVOID lpBaseOfDll;
    DWORD SizeOfImage;
    LPVOID EntryPoint;
} *LPMODULEINFO;

typedef BOOL (WINAPI *EnumProcessModules_PROC)(
  HANDLE hProcess,      // handle to the process
  HMODULE * lphModule,  // array to receive the module handles
  DWORD cb,             // size of the array
  LPDWORD lpcbNeeded    // receives the number of bytes returned
);

typedef BOOL (WINAPI *GetModuleInformation_PROC)(
  HANDLE hProcess,         // handle to the process
  HMODULE hModule,         // handle to the module
  LPMODULEINFO lpmodinfo,  // structure that receives information
  DWORD cb                 // size of the structure
);

/* This version can fail because PSAPI.DLL is not always part of NT 4 despite MSDN Library 6.0a say so */

static bool osl_addressGetModuleURL_NT_( void *pv, rtl_uString **pustrURL )
sal_Bool SAL_CALL osl_getModuleURLFromAddress( void *pv, rtl_uString **pustrURL )
{
    bool    bSuccess    = false;    /* Assume failure */
    static HMODULE hModPsapi = LoadLibraryW( L"PSAPI.DLL" );
    static auto lpfnEnumProcessModules = reinterpret_cast<decltype(EnumProcessModules)*>(
        hModPsapi ? GetProcAddress(hModPsapi, "EnumProcessModules") : nullptr);
    static auto lpfnGetModuleInformation = reinterpret_cast<decltype(GetModuleInformation)*>(
        hModPsapi ? GetProcAddress(hModPsapi, "GetModuleInformation") : nullptr);

    if ( hModPsapi )
    if (lpfnEnumProcessModules && lpfnGetModuleInformation)
    {
        EnumProcessModules_PROC     lpfnEnumProcessModules      = reinterpret_cast<EnumProcessModules_PROC>(GetProcAddress( hModPsapi, "EnumProcessModules" ));
        GetModuleInformation_PROC   lpfnGetModuleInformation    = reinterpret_cast<GetModuleInformation_PROC>(GetProcAddress( hModPsapi, "GetModuleInformation" ));
        DWORD cbNeeded = 0;
        HMODULE* lpModules = nullptr;
        DWORD nModules = 0;
        UINT iModule = 0;
        MODULEINFO modinfo;

        if ( lpfnEnumProcessModules && lpfnGetModuleInformation )
        lpfnEnumProcessModules(GetCurrentProcess(), nullptr, 0, &cbNeeded);

        lpModules = static_cast<HMODULE*>(_alloca(cbNeeded));
        lpfnEnumProcessModules(GetCurrentProcess(), lpModules, cbNeeded, &cbNeeded);

        nModules = cbNeeded / sizeof(HMODULE);

        for (iModule = 0; !bSuccess && iModule < nModules; iModule++)
        {
            DWORD       cbNeeded = 0;
            HMODULE     *lpModules = nullptr;
            DWORD       nModules = 0;
            UINT        iModule = 0;
            MODULEINFO  modinfo;
            lpfnGetModuleInformation(GetCurrentProcess(), lpModules[iModule], &modinfo,
                                     sizeof(modinfo));

            lpfnEnumProcessModules( GetCurrentProcess(), nullptr, 0, &cbNeeded );

            lpModules = static_cast<HMODULE *>(_alloca( cbNeeded ));
            lpfnEnumProcessModules( GetCurrentProcess(), lpModules, cbNeeded, &cbNeeded );

            nModules = cbNeeded / sizeof(HMODULE);

            for ( iModule = 0; !bSuccess && iModule < nModules; iModule++ )
            if (static_cast<BYTE*>(pv) >= static_cast<BYTE*>(modinfo.lpBaseOfDll)
                && static_cast<BYTE*>(pv)
                       < static_cast<BYTE*>(modinfo.lpBaseOfDll) + modinfo.SizeOfImage)
            {
                lpfnGetModuleInformation( GetCurrentProcess(), lpModules[iModule], &modinfo, sizeof(modinfo) );
                ::osl::LongPathBuffer<sal_Unicode> aBuffer(MAX_LONG_PATH);
                rtl_uString* ustrSysPath = nullptr;

                if ( static_cast<BYTE *>(pv) >= static_cast<BYTE *>(modinfo.lpBaseOfDll) && static_cast<BYTE *>(pv) < static_cast<BYTE *>(modinfo.lpBaseOfDll) + modinfo.SizeOfImage )
                {
                    ::osl::LongPathBuffer< sal_Unicode > aBuffer( MAX_LONG_PATH );
                    rtl_uString *ustrSysPath = nullptr;
                GetModuleFileNameW(lpModules[iModule], o3tl::toW(aBuffer),
                                   aBuffer.getBufSizeInSymbols());

                    GetModuleFileNameW( lpModules[iModule], o3tl::toW(aBuffer), aBuffer.getBufSizeInSymbols() );
                rtl_uString_newFromStr(&ustrSysPath, aBuffer);
                osl_getFileURLFromSystemPath(ustrSysPath, pustrURL);
                rtl_uString_release(ustrSysPath);

                    rtl_uString_newFromStr( &ustrSysPath, aBuffer );
                    osl_getFileURLFromSystemPath( ustrSysPath, pustrURL );
                    rtl_uString_release( ustrSysPath );

                    bSuccess = true;
                }
                bSuccess = true;
            }
        }

    }

    return bSuccess;
}

sal_Bool SAL_CALL osl_getModuleURLFromAddress( void *pv, rtl_uString **pustrURL )
{
    /* Use ..._NT first because ..._NT4 is much slower */
    return osl_addressGetModuleURL_NT_( pv, pustrURL ) || osl_addressGetModuleURL_NT4_( pv, pustrURL );
}

sal_Bool SAL_CALL osl_getModuleURLFromFunctionAddress( oslGenericFunction addr, rtl_uString ** ppLibraryUrl )
{
    /* casting a function pointer to a data pointer (void*) is
diff --git a/sal/osl/w32/salinit.cxx b/sal/osl/w32/salinit.cxx
index 71c14e6..77cb5da 100644
--- a/sal/osl/w32/salinit.cxx
+++ b/sal/osl/w32/salinit.cxx
@@ -33,24 +33,11 @@ extern "C" {
void sal_detail_initialize(int argc, char ** argv)
{
    sal_initGlobalTimer();
    HMODULE h = GetModuleHandleW(L"kernel32.dll");
    if (h != nullptr) {
        FARPROC p;
#ifndef _WIN64
        p = GetProcAddress(h, "SetProcessDEPPolicy");
        if (p != 0) {
            reinterpret_cast< BOOL (WINAPI *)(DWORD) >(p)(0x00000001);
        }
    SetProcessDEPPolicy(PROCESS_DEP_ENABLE);
#endif
        p = GetProcAddress(h, "SetDllDirectoryW");
        if (p != nullptr) {
            reinterpret_cast< BOOL (WINAPI *)(LPCWSTR) >(p)(L"");
        }
        p = GetProcAddress(h, "SetSearchPathMode");
        if (p != nullptr) {
            reinterpret_cast< BOOL (WINAPI *)(DWORD) >(p)(0x8001);
        }
    }
    SetDllDirectoryW(L""); // remove the current directory from the default DLL search order
    SetSearchPathMode(BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE | BASE_SEARCH_PATH_PERMANENT);

    WSADATA wsaData;
    int     error;
diff --git a/sal/osl/w32/security.cxx b/sal/osl/w32/security.cxx
index f7e14e7..d0872ef 100644
--- a/sal/osl/w32/security.cxx
+++ b/sal/osl/w32/security.cxx
@@ -18,6 +18,7 @@
 */

#include "system.h"
#include <userenv.h>

#include <cassert>
#include <osl/security.h>
@@ -31,45 +32,13 @@
#include <o3tl/char16_t2wchar_t.hxx>
#include "secimpl.hxx"

/* Data for use in (un)LoadProfile Functions */
/* Declarations based on USERENV.H for Windows 2000 Beta 2 */
#define PI_NOUI         0x00000001   // Prevents displaying of messages

typedef struct {
  DWORD    dwSize;          // Must be set to sizeof(PROFILEINFO)
  DWORD    dwFlags;         // See flags above
  LPWSTR   lpUserName;      // User name (required)
  LPWSTR   lpProfilePath;   // Roaming profile path
  LPWSTR   lpDefaultPath;   // Default user profile path
  LPWSTR   lpServerName;    // Validating DC name in netbios format
  LPWSTR   lpPolicyPath;    // Path to the NT4 style policy file
  HANDLE   hProfile;        // Registry key handle - filled by function
} PROFILEINFOW, FAR * LPPROFILEINFOW;

/* Typedefs for function pointers in USERENV.DLL */
typedef BOOL (STDMETHODCALLTYPE FAR * LPFNLOADUSERPROFILE) (
  HANDLE hToken,
  LPPROFILEINFOW lpProfileInfo
);

typedef BOOL (STDMETHODCALLTYPE FAR * LPFNUNLOADUSERPROFILE) (
  HANDLE hToken,
  HANDLE hProfile
);

typedef BOOL (STDMETHODCALLTYPE FAR * LPFNGETUSERPROFILEDIR) (
  HANDLE hToken,
  LPWSTR lpProfileDir,
  LPDWORD lpcchSize
);

/* To get an impersonation token we need to create an impersonation
   duplicate so every access token has to be created with duplicate
   access rights */

#define TOKEN_DUP_QUERY (TOKEN_QUERY|TOKEN_DUPLICATE)

static bool GetSpecialFolder(rtl_uString **strPath,int nFolder);
static bool GetSpecialFolder(rtl_uString **strPath, REFKNOWNFOLDERID rFolder);
// We use LPCTSTR here, because we use it with SE_foo_NAME constants
// which are defined in winnt.h as UNICODE-dependent TEXT("PrivilegeName")
static BOOL Privilege(LPCTSTR pszPrivilege, BOOL bEnable);
@@ -399,7 +368,7 @@ sal_Bool SAL_CALL osl_getHomeDir(oslSecurity Security, rtl_uString **pustrDirect
        }
        else
        {
                bSuccess = GetSpecialFolder(&ustrSysDir, CSIDL_PERSONAL) &&
                bSuccess = GetSpecialFolder(&ustrSysDir, FOLDERID_Documents) &&
                                     (osl_File_E_None == osl_getFileURLFromSystemPath(ustrSysDir, pustrDirectory));
        }
    }
@@ -440,7 +409,7 @@ sal_Bool SAL_CALL osl_getConfigDir(oslSecurity Security, rtl_uString **pustrDire
                rtl_uString *ustrFile = nullptr;
                sal_Unicode sFile[_MAX_PATH];

                if ( !GetSpecialFolder( &ustrFile, CSIDL_APPDATA) )
                if ( !GetSpecialFolder( &ustrFile, FOLDERID_RoamingAppData) )
                {
                    OSL_VERIFY(GetWindowsDirectoryW(o3tl::toW(sFile), _MAX_DIR) > 0);

@@ -473,9 +442,6 @@ sal_Bool SAL_CALL osl_loadUserProfile(oslSecurity Security)

    if (Privilege(SE_RESTORE_NAME, TRUE))
    {
        HMODULE                 hUserEnvLib         = nullptr;
        LPFNLOADUSERPROFILE     fLoadUserProfile    = nullptr;
        LPFNUNLOADUSERPROFILE   fUnloadUserProfile  = nullptr;
        HANDLE                  hAccessToken        = static_cast<oslSecurityImpl*>(Security)->m_hToken;

        /* try to create user profile */
@@ -492,38 +458,25 @@ sal_Bool SAL_CALL osl_loadUserProfile(oslSecurity Security)
            }
        }

        hUserEnvLib = LoadLibraryW(L"userenv.dll");
        rtl_uString *buffer = nullptr;
        PROFILEINFOW pi;

        if (hUserEnvLib)
        getUserNameImpl(Security, &buffer, false);

        ZeroMemory(&pi, sizeof(pi));
        pi.dwSize = sizeof(pi);
        pi.lpUserName = o3tl::toW(rtl_uString_getStr(buffer));
        pi.dwFlags = PI_NOUI;

        if (LoadUserProfileW(hAccessToken, &pi))
        {
            fLoadUserProfile = reinterpret_cast<LPFNLOADUSERPROFILE>(GetProcAddress(hUserEnvLib, "LoadUserProfileW"));
            fUnloadUserProfile = reinterpret_cast<LPFNUNLOADUSERPROFILE>(GetProcAddress(hUserEnvLib, "UnloadUserProfile"));
            UnloadUserProfile(hAccessToken, pi.hProfile);

            if (fLoadUserProfile && fUnloadUserProfile)
            {
                rtl_uString *buffer = nullptr;
                PROFILEINFOW pi;

                getUserNameImpl(Security, &buffer, false);

                ZeroMemory(&pi, sizeof(pi));
                pi.dwSize = sizeof(pi);
                pi.lpUserName = o3tl::toW(rtl_uString_getStr(buffer));
                pi.dwFlags = PI_NOUI;

                if (fLoadUserProfile(hAccessToken, &pi))
                {
                    fUnloadUserProfile(hAccessToken, pi.hProfile);

                    bOk = true;
                }

                rtl_uString_release(buffer);
            }

            FreeLibrary(hUserEnvLib);
            bOk = true;
        }

        rtl_uString_release(buffer);

        if (hAccessToken && (hAccessToken != static_cast<oslSecurityImpl*>(Security)->m_hToken))
            CloseHandle(hAccessToken);
    }
@@ -535,8 +488,6 @@ void SAL_CALL osl_unloadUserProfile(oslSecurity Security)
{
    if ( static_cast<oslSecurityImpl*>(Security)->m_hProfile != nullptr )
    {
        HMODULE                 hUserEnvLib         = nullptr;
        LPFNUNLOADUSERPROFILE   fUnloadUserProfile  = nullptr;
        HANDLE                  hAccessToken        = static_cast<oslSecurityImpl*>(Security)->m_hToken;

        if ( !hAccessToken )
@@ -552,20 +503,8 @@ void SAL_CALL osl_unloadUserProfile(oslSecurity Security)
            }
        }

        hUserEnvLib = LoadLibraryW(L"userenv.dll");

        if (hUserEnvLib)
        {
            fUnloadUserProfile = reinterpret_cast<LPFNUNLOADUSERPROFILE>(GetProcAddress(hUserEnvLib, "UnloadUserProfile"));

            if (fUnloadUserProfile)
            {
                /* unloading the user profile */
                fUnloadUserProfile(hAccessToken, static_cast<oslSecurityImpl*>(Security)->m_hProfile);
            }

            FreeLibrary(hUserEnvLib);
        }
        /* unloading the user profile */
        UnloadUserProfile(hAccessToken, static_cast<oslSecurityImpl*>(Security)->m_hProfile);

        static_cast<oslSecurityImpl*>(Security)->m_hProfile = nullptr;

@@ -574,100 +513,15 @@ void SAL_CALL osl_unloadUserProfile(oslSecurity Security)
    }
}

static bool GetSpecialFolder(rtl_uString **strPath, int nFolder)
static bool GetSpecialFolder(rtl_uString **strPath, REFKNOWNFOLDERID rFolder)
{
    bool bRet = false;
    HINSTANCE hLibrary = LoadLibraryW(L"shell32.dll");

    if (hLibrary != nullptr)
    PWSTR PathW;
    if (SUCCEEDED(SHGetKnownFolderPath(rFolder, KF_FLAG_CREATE, nullptr, &PathW)))
    {
        sal_Unicode PathW[_MAX_PATH];
        BOOL (WINAPI *pSHGetSpecialFolderPathW)(HWND, LPWSTR, int, BOOL) = reinterpret_cast<BOOL (WINAPI *)(HWND, LPWSTR, int, BOOL)>(GetProcAddress(hLibrary, "SHGetSpecialFolderPathW"));

        if (pSHGetSpecialFolderPathW)
        {
            if (pSHGetSpecialFolderPathW(GetActiveWindow(), o3tl::toW(PathW), nFolder, TRUE))
            {
                rtl_uString_newFromStr( strPath, PathW);
                bRet = true;
            }
        }
        else
        {
            HRESULT (WINAPI *pSHGetSpecialFolderLocation)(HWND, int, LPITEMIDLIST *) = reinterpret_cast<HRESULT (WINAPI *)(HWND, int, LPITEMIDLIST *)>(GetProcAddress(hLibrary, "SHGetSpecialFolderLocation"));
            BOOL (WINAPI *pSHGetPathFromIDListW)(LPCITEMIDLIST, LPWSTR) = reinterpret_cast<BOOL (WINAPI *)(LPCITEMIDLIST, LPWSTR)>(GetProcAddress(hLibrary, "SHGetPathFromIDListW"));
            HRESULT (WINAPI *pSHGetMalloc)(LPMALLOC *) = reinterpret_cast<HRESULT (WINAPI *)(LPMALLOC *)>(GetProcAddress(hLibrary, "SHGetMalloc"));

            if (pSHGetSpecialFolderLocation && pSHGetPathFromIDListW && pSHGetMalloc )
            {
                LPITEMIDLIST pidl;
                LPMALLOC pMalloc;
                HRESULT  hr;

                hr = pSHGetSpecialFolderLocation(GetActiveWindow(), nFolder, &pidl);

                /* Get SHGetSpecialFolderLocation fails if directory does not exists. */
                /* If it fails we try to create the directory and redo the call */
                if (! SUCCEEDED(hr))
                {
                    HKEY hRegKey;

                    if (RegOpenKeyW(HKEY_CURRENT_USER,
                                   L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders",
                                   &hRegKey) == ERROR_SUCCESS)
                    {
                        LONG lRet;
                        DWORD lSize = sizeof(PathW);
                        DWORD Type = REG_SZ;

                        switch (nFolder)
                        {
                            case CSIDL_APPDATA:
                                lRet = RegQueryValueExW(hRegKey, L"AppData", nullptr, &Type, reinterpret_cast<LPBYTE>(PathW), &lSize);
                                  break;

                            case CSIDL_PERSONAL:
                                lRet = RegQueryValueExW(hRegKey, L"Personal", nullptr, &Type, reinterpret_cast<LPBYTE>(PathW), &lSize);
                                break;

                            default:
                                lRet = -1l;
                        }

                        if ((lRet == ERROR_SUCCESS) && (Type == REG_SZ))
                        {
                            if (_waccess(o3tl::toW(PathW), 0) < 0)
                                CreateDirectoryW(o3tl::toW(PathW), nullptr);

                            hr = pSHGetSpecialFolderLocation(GetActiveWindow(), nFolder, &pidl);
                        }

                        RegCloseKey(hRegKey);
                    }
                }

                if (SUCCEEDED(hr))
                {
                    if (pSHGetPathFromIDListW(pidl, o3tl::toW(PathW)))
                    {
                        /* if directory does not exist, create it */
                        if (_waccess(o3tl::toW(PathW), 0) < 0)
                            CreateDirectoryW(o3tl::toW(PathW), nullptr);

                        rtl_uString_newFromStr( strPath, PathW);
                        bRet = true;
                    }
                }

                if (SUCCEEDED(pSHGetMalloc(&pMalloc)))
                {
                    pMalloc->Free(pidl);
                    pMalloc->Release();
                }
            }
        }

        FreeLibrary(hLibrary);
        rtl_uString_newFromStr(strPath, o3tl::toU(PathW));
        CoTaskMemFree(PathW);
        bRet = true;
    }

    return bRet;
diff --git a/sal/osl/w32/signal.cxx b/sal/osl/w32/signal.cxx
index 79d0bcb..aa56622 100644
--- a/sal/osl/w32/signal.cxx
+++ b/sal/osl/w32/signal.cxx
@@ -27,6 +27,7 @@

#include <systools/win32/uwinapi.h>
#include <errorrep.h>
#include <werapi.h>

namespace
{
@@ -39,14 +40,7 @@ bool onInitSignal()
{
    pPreviousHandler = SetUnhandledExceptionFilter(signalHandlerFunction);

    HMODULE hFaultRep = LoadLibraryW( L"faultrep.dll" );
    if ( hFaultRep )
    {
        pfn_ADDEREXCLUDEDAPPLICATIONW pfn = reinterpret_cast<pfn_ADDEREXCLUDEDAPPLICATIONW>(GetProcAddress( hFaultRep, "AddERExcludedApplicationW" ));
        if ( pfn )
            pfn( L"SOFFICE.EXE" );
        FreeLibrary( hFaultRep );
    }
    WerAddExcludedApplication(L"SOFFICE.EXE", FALSE);

    return true;
}
diff --git a/setup_native/source/win32/customactions/quickstarter/quickstarter.cxx b/setup_native/source/win32/customactions/quickstarter/quickstarter.cxx
index 7b0f9a5..960274f 100644
--- a/setup_native/source/win32/customactions/quickstarter/quickstarter.cxx
+++ b/setup_native/source/win32/customactions/quickstarter/quickstarter.cxx
@@ -93,17 +93,14 @@ static bool IsValidHandle( HANDLE handle )

static DWORD WINAPI GetModuleFileNameExW_( HANDLE hProcess, HMODULE hModule, PWSTR lpFileName, DWORD nSize )
{
    typedef DWORD (WINAPI *FN_PROC)( HANDLE hProcess, HMODULE hModule, LPWSTR lpFileName, DWORD nSize );

    static FN_PROC  lpProc = nullptr;

    if ( !lpProc )
    {
    static auto lpProc = []() {
        HMODULE hLibrary = LoadLibraryW(L"PSAPI.DLL");

        if ( hLibrary )
            lpProc = reinterpret_cast< FN_PROC >(GetProcAddress( hLibrary, "GetModuleFileNameExW" ));
    }
        decltype(GetModuleFileNameExW)* pRet = nullptr;
        if (hLibrary)
            pRet = reinterpret_cast<decltype(GetModuleFileNameExW)*>(
                GetProcAddress(hLibrary, "GetModuleFileNameExW"));
        return pRet;
    }();

    if ( lpProc )
        return lpProc( hProcess, hModule, lpFileName, nSize );
diff --git a/vcl/Library_vclplug_win.mk b/vcl/Library_vclplug_win.mk
index 24f2d24..f64cc03 100644
--- a/vcl/Library_vclplug_win.mk
+++ b/vcl/Library_vclplug_win.mk
@@ -82,6 +82,8 @@ $(eval $(call gb_Library_add_exception_objects,vclplug_win,\
))

$(eval $(call gb_Library_use_system_win32_libs,vclplug_win,\
    d2d1 \
    dwrite \
    gdi32 \
    gdiplus \
    imm32 \
diff --git a/vcl/inc/win/DWriteTextRenderer.hxx b/vcl/inc/win/DWriteTextRenderer.hxx
index 0e81b67..92e0825 100644
--- a/vcl/inc/win/DWriteTextRenderer.hxx
+++ b/vcl/inc/win/DWriteTextRenderer.hxx
@@ -36,19 +36,7 @@ enum class D2DTextAntiAliasMode

class D2DWriteTextOutRenderer : public TextOutRenderer
{
    typedef HRESULT(WINAPI *pD2D1CreateFactory_t)(D2D1_FACTORY_TYPE,
        REFIID, const D2D1_FACTORY_OPTIONS *, void **);

    typedef HRESULT(WINAPI *pDWriteCreateFactory_t)(DWRITE_FACTORY_TYPE,
        REFIID, IUnknown **);

    static HINSTANCE mmD2d1, mmDWrite;
    static pD2D1CreateFactory_t     D2D1CreateFactory;
    static pDWriteCreateFactory_t   DWriteCreateFactory;

public:
    static bool InitModules();

    explicit D2DWriteTextOutRenderer();
    virtual ~D2DWriteTextOutRenderer() override;

@@ -74,8 +62,6 @@ public:
    void changeTextAntiAliasMode(D2DTextAntiAliasMode eMode);

private:
    static void CleanupModules();

    // This is a singleton object disable copy ctor and assignment operator
    D2DWriteTextOutRenderer(const D2DWriteTextOutRenderer &) = delete;
    D2DWriteTextOutRenderer & operator = (const D2DWriteTextOutRenderer &) = delete;
diff --git a/vcl/win/gdi/DWriteTextRenderer.cxx b/vcl/win/gdi/DWriteTextRenderer.cxx
index 6dbfdbf..117b359 100644
--- a/vcl/win/gdi/DWriteTextRenderer.cxx
+++ b/vcl/win/gdi/DWriteTextRenderer.cxx
@@ -32,43 +32,6 @@
#include <comphelper/windowserrorstring.hxx>
#include <sal/log.hxx>

HINSTANCE D2DWriteTextOutRenderer::mmD2d1 = nullptr,
          D2DWriteTextOutRenderer::mmDWrite = nullptr;
D2DWriteTextOutRenderer::pD2D1CreateFactory_t D2DWriteTextOutRenderer::D2D1CreateFactory = nullptr;
D2DWriteTextOutRenderer::pDWriteCreateFactory_t D2DWriteTextOutRenderer::DWriteCreateFactory = nullptr;

bool D2DWriteTextOutRenderer::InitModules()
{
    mmD2d1 = LoadLibraryW(L"D2d1.dll");
    mmDWrite = LoadLibraryW(L"dwrite.dll");
    if (mmD2d1 && mmDWrite)
    {
        D2D1CreateFactory = pD2D1CreateFactory_t(GetProcAddress(mmD2d1, "D2D1CreateFactory"));
        DWriteCreateFactory = pDWriteCreateFactory_t(GetProcAddress(mmDWrite, "DWriteCreateFactory"));
    }

    if (!D2D1CreateFactory || !DWriteCreateFactory)
    {
        CleanupModules();
        return false;
    }

    return true;
}

void D2DWriteTextOutRenderer::CleanupModules()
{
    if (mmD2d1)
        FreeLibrary(mmD2d1);
    if (mmDWrite)
        FreeLibrary(mmDWrite);

    mmD2d1 = nullptr;
    mmDWrite = nullptr;
    D2D1CreateFactory = nullptr;
    DWriteCreateFactory = nullptr;
}

namespace
{

@@ -167,8 +130,6 @@ D2DWriteTextOutRenderer::~D2DWriteTextOutRenderer()
        mpDWriteFactory->Release();
    if (mpD2DFactory)
        mpD2DFactory->Release();

    CleanupModules();
}

void D2DWriteTextOutRenderer::applyTextAntiAliasMode()
diff --git a/vcl/win/gdi/winlayout.cxx b/vcl/win/gdi/winlayout.cxx
index 9be60fc..797ce2e 100644
--- a/vcl/win/gdi/winlayout.cxx
+++ b/vcl/win/gdi/winlayout.cxx
@@ -210,16 +210,11 @@ TextOutRenderer & TextOutRenderer::get(bool bUseDWrite)

    if (bUseDWrite)
    {
        static bool const bSuccess(D2DWriteTextOutRenderer::InitModules());
        if (bSuccess && !pSalData->m_pD2DWriteTextOutRenderer)
        if (!pSalData->m_pD2DWriteTextOutRenderer)
        {
            pSalData->m_pD2DWriteTextOutRenderer.reset(new D2DWriteTextOutRenderer());
        }
        if (pSalData->m_pD2DWriteTextOutRenderer)
        {
            return *pSalData->m_pD2DWriteTextOutRenderer;
        }
        // else: fall back to GDI
        return *pSalData->m_pD2DWriteTextOutRenderer;
    }
    if (!pSalData->m_pExTextOutRenderer)
    {
diff --git a/vcl/win/window/salframe.cxx b/vcl/win/window/salframe.cxx
index 64d505de..16cdf0e 100644
--- a/vcl/win/window/salframe.cxx
+++ b/vcl/win/window/salframe.cxx
@@ -1794,34 +1794,26 @@ void WinSalFrame::SetApplicationID( const OUString &rApplicationID )
    // http://msdn.microsoft.com/en-us/library/windows/desktop/dd378430(v=vs.85).aspx
    // A window's properties must be removed before the window is closed.

    typedef HRESULT ( WINAPI *SHGETPROPERTYSTOREFORWINDOW )( HWND, REFIID, void ** );
    SHGETPROPERTYSTOREFORWINDOW pSHGetPropertyStoreForWindow;
    pSHGetPropertyStoreForWindow = reinterpret_cast<SHGETPROPERTYSTOREFORWINDOW>(GetProcAddress(
                                   GetModuleHandleW (L"shell32.dll"), "SHGetPropertyStoreForWindow" ));

    if( pSHGetPropertyStoreForWindow )
    IPropertyStore *pps;
    HRESULT hr = SHGetPropertyStoreForWindow(mhWnd, IID_PPV_ARGS(&pps));
    if (SUCCEEDED(hr))
    {
        IPropertyStore *pps;
        HRESULT hr = pSHGetPropertyStoreForWindow ( mhWnd, IID_PPV_ARGS(&pps) );
        if ( SUCCEEDED(hr) )
        PROPVARIANT pv;
        if (!rApplicationID.isEmpty())
        {
            PROPVARIANT pv;
            if ( !rApplicationID.isEmpty() )
            {
                hr = InitPropVariantFromString( o3tl::toW(rApplicationID.getStr()), &pv );
                mbPropertiesStored = true;
            }
            else
                // if rApplicationID we remove the property from the window, if present
                PropVariantInit( &pv );

            if ( SUCCEEDED(hr) )
            {
                hr = pps->SetValue( PKEY_AppUserModel_ID, pv );
                PropVariantClear( &pv );
            }
            pps->Release();
            hr = InitPropVariantFromString(o3tl::toW(rApplicationID.getStr()), &pv);
            mbPropertiesStored = true;
        }
        else
            // if rApplicationID we remove the property from the window, if present
            PropVariantInit(&pv);

        if (SUCCEEDED(hr))
        {
            hr = pps->SetValue(PKEY_AppUserModel_ID, pv);
            PropVariantClear(&pv);
        }
        pps->Release();
    }
}