diff options
Diffstat (limited to 'src/utilcode')
-rw-r--r-- | src/utilcode/CMakeLists.txt | 5 | ||||
-rw-r--r-- | src/utilcode/apithreadstress.cpp | 183 | ||||
-rw-r--r-- | src/utilcode/appxutil.cpp | 820 | ||||
-rw-r--r-- | src/utilcode/ccomprc.cpp | 83 | ||||
-rw-r--r-- | src/utilcode/clrconfig.cpp | 159 | ||||
-rw-r--r-- | src/utilcode/clrhost.cpp | 8 | ||||
-rw-r--r-- | src/utilcode/dlwrap.cpp | 152 | ||||
-rw-r--r-- | src/utilcode/downlevel.cpp | 4 | ||||
-rw-r--r-- | src/utilcode/ex.cpp | 10 | ||||
-rw-r--r-- | src/utilcode/longfilepathwrappers.cpp | 2 | ||||
-rw-r--r-- | src/utilcode/makepath.cpp | 203 | ||||
-rw-r--r-- | src/utilcode/newapis.cpp | 78 | ||||
-rw-r--r-- | src/utilcode/pedecoder.cpp | 75 | ||||
-rw-r--r-- | src/utilcode/peinformation.cpp | 94 | ||||
-rw-r--r-- | src/utilcode/prettyprintsig.cpp | 4 | ||||
-rw-r--r-- | src/utilcode/registrywrapper.cpp | 285 | ||||
-rw-r--r-- | src/utilcode/regutil.cpp | 697 | ||||
-rw-r--r-- | src/utilcode/safewrap.cpp | 5 | ||||
-rw-r--r-- | src/utilcode/sortversioning.cpp | 244 | ||||
-rw-r--r-- | src/utilcode/stacktrace.cpp | 4 | ||||
-rw-r--r-- | src/utilcode/stresslog.cpp | 27 | ||||
-rw-r--r-- | src/utilcode/tlbutils.cpp | 221 | ||||
-rw-r--r-- | src/utilcode/util.cpp | 246 | ||||
-rw-r--r-- | src/utilcode/utilmessagebox.cpp | 186 | ||||
-rw-r--r-- | src/utilcode/utsem.cpp | 4 |
25 files changed, 71 insertions, 3728 deletions
diff --git a/src/utilcode/CMakeLists.txt b/src/utilcode/CMakeLists.txt index 7c396732a1..dfe830d5c0 100644 --- a/src/utilcode/CMakeLists.txt +++ b/src/utilcode/CMakeLists.txt @@ -1,10 +1,6 @@ set(CMAKE_INCLUDE_CURRENT_DIR ON) -if(WIN32) - add_compile_options(/wd4996) -endif(WIN32) - set(UTILCODE_COMMON_SOURCES clrhost_nodependencies.cpp ccomprc.cpp @@ -28,7 +24,6 @@ set(UTILCODE_COMMON_SOURCES peinformation.cpp check.cpp log.cpp - apithreadstress.cpp arraylist.cpp bitvector.cpp comex.cpp diff --git a/src/utilcode/apithreadstress.cpp b/src/utilcode/apithreadstress.cpp deleted file mode 100644 index 88b09fe006..0000000000 --- a/src/utilcode/apithreadstress.cpp +++ /dev/null @@ -1,183 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// --------------------------------------------------------------------------- -// APIThreadStress.cpp (API thread stresser) -// --------------------------------------------------------------------------- - -#include "stdafx.h" - -#ifdef STRESS_THREAD - -#include "apithreadstress.h" -#include "clrhost.h" -#include "ex.h" -#include "log.h" - - - -// For now, thread stress is incompatible with hosting. We need a host CreateThread -// to fix this. -#undef SetEvent -#undef ResetEvent - -int APIThreadStress::s_threadStressCount = 0; - -APIThreadStress::APIThreadStress() -{ - WRAPPER_NO_CONTRACT; - - m_threadCount = 0; - - // Don't "fork" stress threads - if (ClrFlsGetValue(TlsIdx_StressThread) == NULL) - m_threadCount = s_threadStressCount; - - if (m_threadCount != 0) - { - m_setupOK = TRUE; - - m_hThreadArray = new (nothrow) HANDLE [ m_threadCount ]; - if (m_hThreadArray == NULL) - m_setupOK = FALSE; - else - { - HANDLE *p = m_hThreadArray; - HANDLE *pEnd = p + m_threadCount; - - while (p < pEnd) - { - DWORD id; - *p = ::CreateThread(NULL, 0, StartThread, this, 0, &id); - if (*p == NULL) - m_setupOK = FALSE; - p++; - } - } - - m_syncEvent = ClrCreateManualEvent(FALSE); - if (m_syncEvent == INVALID_HANDLE_VALUE) - m_setupOK = FALSE; - } -} - -APIThreadStress::~APIThreadStress() -{ - WRAPPER_NO_CONTRACT; - - if (m_threadCount > 0) - { - HANDLE *p = m_hThreadArray; - HANDLE *pEnd = p + m_threadCount; - - if (p != NULL) - { - while (p < pEnd) - { - if (*p != NULL) - { - if (m_threadCount > 0 && m_setupOK) - WaitForSingleObjectEx(*p, INFINITE, FALSE); - - ::CloseHandle(*p); - } - p++; - } - delete [] m_hThreadArray; - } - - if (m_syncEvent != INVALID_HANDLE_VALUE) - CloseHandle(m_syncEvent); - } -} - -void APIThreadStress::SetThreadStressCount(int threadCount) -{ - LIMITED_METHOD_CONTRACT; - - s_threadStressCount = threadCount; -} - - -DWORD WINAPI APIThreadStress::StartThread(void *arg) -{ - WRAPPER_NO_CONTRACT; - STATIC_CONTRACT_SO_NOT_MAINLINE; // not mainline so scenario - - APIThreadStress *pThis = (APIThreadStress *) arg; - - ClrFlsSetValue(TlsIdx_StressThread, pThis); - - EX_TRY - { - // Perform initial synchronization - WaitForSingleObjectEx(pThis->m_syncEvent, INFINITE, FALSE); - InterlockedIncrement(&pThis->m_runCount); - - LOG((LF_ALL, LL_INFO100, "Stressing operation on thread %d\n", GetCurrentThreadId())); - ((APIThreadStress *)arg)->Invoke(); - LOG((LF_ALL, LL_INFO100, "End stress operation on thread %d\n", GetCurrentThreadId())); - - if (InterlockedDecrement(&pThis->m_runCount) == 0) - ::SetEvent(pThis->m_syncEvent); - } - EX_CATCH - { - LOG((LF_ALL, LL_ERROR, "Exception during stress operation on thread %d\n", GetCurrentThreadId())); - } - EX_END_CATCH(SwallowAllExceptions); - - return 0; -} - -BOOL APIThreadStress::DoThreadStress() -{ - WRAPPER_NO_CONTRACT; - - if (m_threadCount > 0 && m_setupOK) - { - HANDLE *p = m_hThreadArray; - HANDLE *pEnd = p + m_threadCount; - - while (p < pEnd) - { - ::ResumeThread(*p); - p++; - } - - // Start the threads at the same time - ::SetEvent(m_syncEvent); - - return TRUE; - } - else - { - SyncThreadStress(); - return FALSE; - } -} - -void APIThreadStress::SyncThreadStress() -{ - WRAPPER_NO_CONTRACT; - - APIThreadStress *pThis = (APIThreadStress *) ClrFlsGetValue(TlsIdx_StressThread); - - if (pThis != NULL) - { - LOG((LF_ALL, LL_INFO1000, "Syncing stress operation on thread %d\n", GetCurrentThreadId())); - - ::ResetEvent(pThis->m_syncEvent); - - if (InterlockedDecrement(&pThis->m_runCount) == 0) - ::SetEvent(pThis->m_syncEvent); - else - WaitForSingleObjectEx(pThis->m_syncEvent, INFINITE, FALSE); - InterlockedIncrement(&pThis->m_runCount); - - LOG((LF_ALL, LL_INFO1000, "Resuming stress operation on thread %d\n", GetCurrentThreadId())); - } -} - -#endif // STRESS_THREAD diff --git a/src/utilcode/appxutil.cpp b/src/utilcode/appxutil.cpp index 759fbffcb1..5d095a4873 100644 --- a/src/utilcode/appxutil.cpp +++ b/src/utilcode/appxutil.cpp @@ -19,7 +19,6 @@ #include "shlwapi.h" // Path manipulation APIs -#ifdef FEATURE_CORECLR GVAL_IMPL(bool, g_fAppX); INDEBUG(bool g_fIsAppXAsked;) @@ -49,822 +48,3 @@ namespace AppX #endif }; -#else // FEATURE_CORECLR - -//--------------------------------------------------------------------------------------------- -// Convenience values - -#ifndef E_INSUFFICIENT_BUFFER - #define E_INSUFFICIENT_BUFFER (HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER)) -#endif - -#ifndef E_FILE_NOT_FOUND - #define E_FILE_NOT_FOUND (HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) -#endif - -//--------------------------------------------------------------------------------------------- -using clr::str::IsNullOrEmpty; - -//--------------------------------------------------------------------------------------------- -typedef decltype(GetCurrentPackageId) GetCurrentPackageId_t; -typedef decltype(GetCurrentPackageInfo) GetCurrentPackageInfo_t; -typedef decltype(GetCurrentPackagePath) GetCurrentPackagePath_t; -typedef decltype(OpenPackageInfoByFullName) OpenPackageInfoByFullName_t; -typedef decltype(ClosePackageInfo) ClosePackageInfo_t; -typedef decltype(GetPackageInfo) GetPackageInfo_t; - -//--------------------------------------------------------------------------------------------- -// Caches AppX ARI API-related information. -struct AppXRTInfo -{ - HMODULE m_hAppXRTMod; - bool m_fIsAppXProcess; - bool m_fIsAppXAdaptiveApp; - bool m_fIsAppXNGen; - - GetCurrentPackageId_t * m_pfnGetCurrentPackageId; - GetCurrentPackageInfo_t * m_pfnGetCurrentPackageInfo; - GetCurrentPackagePath_t * m_pfnGetCurrentPackagePath; - - NewArrayHolder<BYTE> m_pbAppContainerInfo; - DWORD m_cbAppContainerInfo; - - struct CurrentPackageInfo - { - UINT32 m_cbCurrentPackageInfo; - PBYTE m_pbCurrentPackageInfo; - UINT32 m_nCount; - - CurrentPackageInfo(UINT32 cbPkgInfo, PBYTE pbPkgInfo, UINT32 nCount) - : m_cbCurrentPackageInfo(cbPkgInfo) - , m_pbCurrentPackageInfo(pbPkgInfo) - , m_nCount(nCount) - { LIMITED_METHOD_CONTRACT; } - - ~CurrentPackageInfo() - { - LIMITED_METHOD_CONTRACT; - if (m_pbCurrentPackageInfo != nullptr) - { - delete [] m_pbCurrentPackageInfo; - m_pbCurrentPackageInfo = nullptr; - } - } - }; - - CurrentPackageInfo * m_pCurrentPackageInfo; - - NewArrayHolder<WCHAR> m_AdaptiveAppWinmetadataDir; - - AppXRTInfo() : - m_hAppXRTMod(nullptr), - m_fIsAppXProcess(false), - m_fIsAppXAdaptiveApp(false), - m_fIsAppXNGen(false), - m_pfnGetCurrentPackageId(nullptr), - m_pfnGetCurrentPackageInfo(nullptr), - m_pfnGetCurrentPackagePath(nullptr), - m_pbAppContainerInfo(nullptr), - m_pCurrentPackageInfo(nullptr), - m_AdaptiveAppWinmetadataDir(nullptr) - { LIMITED_METHOD_CONTRACT; } - - ~AppXRTInfo() - { - LIMITED_METHOD_CONTRACT; - if (m_pCurrentPackageInfo != nullptr) - { - delete m_pCurrentPackageInfo; - m_pCurrentPackageInfo = nullptr; - } - - if (m_hAppXRTMod != nullptr) - { - FreeLibrary(m_hAppXRTMod); - m_hAppXRTMod = nullptr; - } - } -}; // struct AppXRTInfo - -GPTR_IMPL(AppXRTInfo, g_pAppXRTInfo); // Relies on zero init static memory. - -#ifndef DACCESS_COMPILE - -//--------------------------------------------------------------------------------------------- -static -HRESULT GetAppContainerTokenInfoForProcess( - DWORD pid, - NewArrayHolder<BYTE>& pbAppContainerTokenInfo, - DWORD* pcbAppContainerTokenInfo) -{ - PRECONDITION(CheckPointer(pcbAppContainerTokenInfo, NULL_OK)); - - HRESULT hr = S_OK; - - pbAppContainerTokenInfo = nullptr; - - // In order to get the AppContainer SID we need to open the process token - HandleHolder hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid); - if (hProcess == NULL) - return HRESULT_FROM_GetLastError(); - - HandleHolder hToken; - if (!OpenProcessToken(hProcess, TOKEN_QUERY, &hToken)) - return HRESULT_FROM_GetLastError(); - - // Query the process to see if it's inside an AppContainer - ULONG isAppContainer = 0; - DWORD actualLength = 0; - if (!GetTokenInformation(hToken, static_cast<TOKEN_INFORMATION_CLASS>(TokenIsAppContainer), &isAppContainer, sizeof(isAppContainer), &actualLength)) - return HRESULT_FROM_GetLastError(); - - _ASSERTE(actualLength > 0); - - // Not an AppContainer so bail - if (!isAppContainer) - { - return S_FALSE; - } - - // Now we need the AppContainer SID so first get the required buffer length - actualLength = 0; - VERIFY(!GetTokenInformation(hToken, static_cast<TOKEN_INFORMATION_CLASS>(TokenAppContainerSid), NULL, 0, &actualLength)); - hr = HRESULT_FROM_GetLastError(); - _ASSERTE(hr == E_INSUFFICIENT_BUFFER); - - // Something unexpected happened - if (hr != E_INSUFFICIENT_BUFFER) - return hr; - - // Now we know the length of the AppContainer SID so create a buffer and retrieve it - pbAppContainerTokenInfo = new (nothrow) BYTE[actualLength]; - IfNullRet(pbAppContainerTokenInfo); - - if (!GetTokenInformation(hToken, static_cast<TOKEN_INFORMATION_CLASS>(TokenAppContainerSid), pbAppContainerTokenInfo.GetValue(), actualLength, &actualLength)) - return HRESULT_FROM_GetLastError(); - - if (pcbAppContainerTokenInfo != nullptr) - *pcbAppContainerTokenInfo = actualLength; - - return S_OK; -} - -//--------------------------------------------------------------------------------------------- -// Initializes a global AppXRTInfo structure if it has not already been initialized. Returns -// false only in the event of OOM; otherwise caches the result of ARI information in -// g_pAppXRTInfo. Thread safe. -static -HRESULT InitAppXRT() -{ - // This will be used for catastrophic errors. - HRESULT hr = S_OK; - - if (VolatileLoad(&g_pAppXRTInfo) == nullptr) - { - NewHolder<AppXRTInfo> pAppXRTInfo = new (nothrow) AppXRTInfo(); - IfNullRet(pAppXRTInfo); // Catastrophic error. - - pAppXRTInfo->m_fIsAppXProcess = false; - - do - { - if (!RunningOnWin8()) - { - break; - } - - LPCWSTR wzAppXRTDll = W("api-ms-win-appmodel-runtime-l1-1-0.dll"); - // Does not use GetLoadWithAlteredSearchPathFlag() because that would cause infinite recursion. - pAppXRTInfo->m_hAppXRTMod = WszLoadLibraryEx(wzAppXRTDll, nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - if (pAppXRTInfo->m_hAppXRTMod == nullptr) - { // Error is catastrophic: can't find kernel32.dll? - hr = HRESULT_FROM_GetLastError(); - break; - } - - pAppXRTInfo->m_pfnGetCurrentPackageId = reinterpret_cast<GetCurrentPackageId_t *>( - GetProcAddress(pAppXRTInfo->m_hAppXRTMod, "GetCurrentPackageId")); - if (pAppXRTInfo->m_pfnGetCurrentPackageId == nullptr) - { // Error is non-catastrophic: could be running downlevel - break; - } - - pAppXRTInfo->m_pfnGetCurrentPackageInfo = reinterpret_cast<GetCurrentPackageInfo_t *>( - GetProcAddress(pAppXRTInfo->m_hAppXRTMod, "GetCurrentPackageInfo")); - if (pAppXRTInfo->m_pfnGetCurrentPackageInfo == nullptr) - { // Error is catastrophic: GetCurrentPackageId is available but not GetCurrentPackageInfo? - hr = HRESULT_FROM_GetLastError(); - break; - } - - pAppXRTInfo->m_pfnGetCurrentPackagePath = reinterpret_cast<GetCurrentPackagePath_t *>( - GetProcAddress(pAppXRTInfo->m_hAppXRTMod, "GetCurrentPackagePath")); - if (pAppXRTInfo->m_pfnGetCurrentPackagePath == nullptr) - { // Error is catastrophic: GetCurrentPackageInfo is available but not GetCurrentPackagePath? - hr = HRESULT_FROM_GetLastError(); - break; - } - - // Determine if this is an AppX process - UINT32 cbBuffer = 0; - LONG lRes = (*pAppXRTInfo->m_pfnGetCurrentPackageId)(&cbBuffer, nullptr); - pAppXRTInfo->m_fIsAppXProcess = (lRes == ERROR_INSUFFICIENT_BUFFER); - - _ASSERTE(AppX::IsAppXSupported()); - - hr = GetAppContainerTokenInfoForProcess( - GetCurrentProcessId(), - pAppXRTInfo->m_pbAppContainerInfo, - &pAppXRTInfo->m_cbAppContainerInfo); - - if (FAILED(hr)) - { - if (pAppXRTInfo->m_fIsAppXProcess) - { // Error is catastrophic: running in true immersive process but no token info? - } - else - { // Error is non-catastrophic: reset HRESULT to S_OK. - hr = S_OK; - } - break; - } - } - while (false); - - if (InterlockedCompareExchangeT<AppXRTInfo>(&g_pAppXRTInfo, pAppXRTInfo, nullptr) == nullptr) - { - pAppXRTInfo.SuppressRelease(); - } - } - - return hr; -} - -//--------------------------------------------------------------------------------------------- -// Inline helper to check first an only init when required. -static inline HRESULT CheckInitAppXRT() -{ - return (VolatileLoad(&g_pAppXRTInfo) != nullptr) ? S_OK : InitAppXRT(); -} - -#endif // !DACCESS_COMPILE - -//--------------------------------------------------------------------------------------------- -// Contains general helper methods for interacting with AppX functionality. This code will -// gracefully fail on downlevel OS by returning false from AppX::IsAppXProcess, so always -// call this API first to check before calling any of the others defined in this namespace. -// -// See http://windows/windows8/docs/Windows%208%20Feature%20Documents/Developer%20Experience%20(DEVX)/Apps%20Experience%20(APPX)/Modern%20Client/App%20Runtime%20Improvements%20API%20Developer%20Platform%20Spec.docm -// for more information. - -namespace AppX -{ -#ifdef DACCESS_COMPILE - - //----------------------------------------------------------------------------------------- - // DAC-only IsAppXProcess. Returns false if g_pAppXRTInfo has not been initialized. - bool DacIsAppXProcess() - { - LIMITED_METHOD_DAC_CONTRACT; - return (g_pAppXRTInfo != nullptr && g_pAppXRTInfo->m_fIsAppXProcess); - } - -#else // DACCESS_COMPILE - - //--------------------------------------------------------------------------------------------- - // cleans up resources allocated in InitAppXRT() - void ShutDown() - { - if (VolatileLoad(&g_pAppXRTInfo) != nullptr) - { - delete g_pAppXRTInfo; - g_pAppXRTInfo = nullptr; - } - } - - //----------------------------------------------------------------------------------------- - // Returns true if the current process is immersive. - // NOTE: a return value of true doesn't necessarily indicate that the process is a - // real Metro app, e.g. it could be an ngen process compiling an AppX assembly. - bool IsAppXProcess() - { - LIMITED_METHOD_CONTRACT; - HRESULT hr = S_OK; - - if (FAILED(hr = CheckInitAppXRT())) - { - SetLastError(hr); // HRESULT_FROM_WIN32 is idempotent when error value is HRESULT. - return false; - } - - return g_pAppXRTInfo->m_fIsAppXProcess; - } - - //----------------------------------------------------------------------------------------- - // Returns true if the current process is immersive. - // Only produces reliable results after IsAppXProcess is inititalized - bool IsAppXProcess_Initialized_NoFault() - { - LIMITED_METHOD_CONTRACT; - if (VolatileLoad(&g_pAppXRTInfo) == nullptr) - { - return false; - } - return g_pAppXRTInfo->m_fIsAppXProcess; - } - - bool IsAppXNGen() - { - LIMITED_METHOD_CONTRACT; - return VolatileLoad(&g_pAppXRTInfo) != nullptr && g_pAppXRTInfo->m_fIsAppXNGen; - } - - //----------------------------------------------------------------------------------------- - HRESULT InitCurrentPackageInfoCache() - { - LIMITED_METHOD_CONTRACT; - HRESULT hr = S_OK; - - UINT32 cbBuffer = 0; - hr = HRESULT_FROM_WIN32((*g_pAppXRTInfo->m_pfnGetCurrentPackageInfo)(PACKAGE_FILTER_CLR_DEFAULT, &cbBuffer, nullptr, nullptr)); - if (hr != E_INSUFFICIENT_BUFFER) - return hr; - - NewArrayHolder<BYTE> pbBuffer(new (nothrow) BYTE[cbBuffer]); - IfNullRet(pbBuffer); - - UINT32 nCount = 0; - IfFailRet(HRESULT_FROM_WIN32((*g_pAppXRTInfo->m_pfnGetCurrentPackageInfo)(PACKAGE_FILTER_CLR_DEFAULT, &cbBuffer, pbBuffer, &nCount))); - - NewHolder<AppXRTInfo::CurrentPackageInfo> pPkgInfo( - new (nothrow) AppXRTInfo::CurrentPackageInfo(cbBuffer, pbBuffer.Extract(), nCount)); - IfNullRet(pPkgInfo); - - if (InterlockedCompareExchangeT<AppXRTInfo::CurrentPackageInfo>( - &g_pAppXRTInfo->m_pCurrentPackageInfo, pPkgInfo, nullptr) == nullptr) - { - pPkgInfo.SuppressRelease(); - } - - return S_OK; - } - - //----------------------------------------------------------------------------------------- - FORCEINLINE HRESULT CheckInitCurrentPackageInfoCache() - { - WRAPPER_NO_CONTRACT; - PRECONDITION(IsAppXProcess()); - - if (!IsAppXProcess()) - return E_UNEXPECTED; - - if (g_pAppXRTInfo->m_pCurrentPackageInfo == nullptr) - return InitCurrentPackageInfoCache(); - else - return S_OK; - } - - //----------------------------------------------------------------------------------------- - LPCWSTR GetHeadPackageMoniker() - { - STANDARD_VM_CONTRACT; - - IfFailThrow(CheckInitCurrentPackageInfoCache()); - return reinterpret_cast<PPACKAGE_INFO>( - g_pAppXRTInfo->m_pCurrentPackageInfo->m_pbCurrentPackageInfo)->packageFullName; - } - - //----------------------------------------------------------------------------------------- - // Returns the current process' PACKAGE_ID in the provided buffer. See the ARI spec (above) - // for more information. - HRESULT GetCurrentPackageId( - PUINT32 pBufferLength, - PBYTE pBuffer) - { - LIMITED_METHOD_CONTRACT; - HRESULT hr = S_OK; - - IfFailRet(CheckInitAppXRT()); - IfFailRet(HRESULT_FROM_WIN32((*g_pAppXRTInfo->m_pfnGetCurrentPackageId)(pBufferLength, pBuffer))); - - return S_OK; - } - - //----------------------------------------------------------------------------------------- - // Returns the current process' PACKAGE_INFO in the provided buffer. See the ARI spec - // (above) for more information. - HRESULT GetCurrentPackageInfo( - UINT32 uiFlags, - PUINT32 pcbBuffer, - PBYTE pbBuffer, - PUINT32 pnCount) - { - LIMITED_METHOD_CONTRACT; - PRECONDITION(IsAppXProcess()); - PRECONDITION(CheckPointer(pcbBuffer)); - - HRESULT hr = S_OK; - - IfFailRet(CheckInitAppXRT()); - - if (pcbBuffer == nullptr) - return E_INVALIDARG; - - if (uiFlags == PACKAGE_FILTER_CLR_DEFAULT) - { - IfFailRet(CheckInitCurrentPackageInfoCache()); - - DWORD cbBuffer = *pcbBuffer; - *pcbBuffer = g_pAppXRTInfo->m_pCurrentPackageInfo->m_cbCurrentPackageInfo; - if (pnCount != nullptr) - { - *pnCount = g_pAppXRTInfo->m_pCurrentPackageInfo->m_nCount; - } - - if (pbBuffer == nullptr || cbBuffer < g_pAppXRTInfo->m_pCurrentPackageInfo->m_cbCurrentPackageInfo) - { - return E_INSUFFICIENT_BUFFER; - } - memcpy(pbBuffer, g_pAppXRTInfo->m_pCurrentPackageInfo->m_pbCurrentPackageInfo, g_pAppXRTInfo->m_pCurrentPackageInfo->m_cbCurrentPackageInfo); - } - else - { - IfFailRet(HRESULT_FROM_WIN32((*g_pAppXRTInfo->m_pfnGetCurrentPackageInfo)(uiFlags, pcbBuffer, pbBuffer, pnCount))); - } - - return S_OK; - } - - //----------------------------------------------------------------------------------------- - bool IsAdaptiveApp() - { - LIMITED_METHOD_CONTRACT; - - HRESULT hr = S_OK; - static bool cachedIsAdaptiveApp = false; - - if (!IsAppXProcess()) - { - return false; - } - - if (!cachedIsAdaptiveApp) - { - cachedIsAdaptiveApp = true; - LPWSTR adaptiveAppWinmetaDataDir = NULL; - - if (SUCCEEDED(hr = AppX::GetWinMetadataDirForAdaptiveApps(&adaptiveAppWinmetaDataDir))) - { - g_pAppXRTInfo->m_fIsAppXAdaptiveApp = clr::fs::Dir::Exists(adaptiveAppWinmetaDataDir); - - } - else - { - SetLastError(hr); - g_pAppXRTInfo->m_fIsAppXAdaptiveApp = false; - } - - } - - return g_pAppXRTInfo->m_fIsAppXAdaptiveApp; - } - - - //----------------------------------------------------------------------------------------- - // length : Upon success, contains the the length of packagePath - // [in/out] - // - // packageRoot : Upon success, contains the full packagePath - // [out] [ Note: The memory has to be preallocated for the above length] - // - HRESULT GetCurrentPackagePath(_Inout_ UINT32* length, _Out_opt_ PWSTR packageRoot) - { - PRECONDITION(IsAppXProcess()); - PRECONDITION(CheckPointer(length)); - - HRESULT hr; - IfFailRet(CheckInitAppXRT()); - - IfFailRet(HRESULT_FROM_WIN32((*g_pAppXRTInfo->m_pfnGetCurrentPackagePath)(length, packageRoot))); - return S_OK; - } - - //----------------------------------------------------------------------------------------- - // winMetadDataDir : Upon success, contains the absolute path for the winmetadata directory for the adaptive app - // [out] NOTE: The string the pointer points to is global memory and never should be modified - // - HRESULT GetWinMetadataDirForAdaptiveApps(_Out_ LPWSTR* winMetadDataDir) - { - - PRECONDITION(IsAppXProcess()); - - HRESULT hr; - - IfFailRet(CheckInitAppXRT()); - - if (g_pAppXRTInfo->m_AdaptiveAppWinmetadataDir == nullptr) - { - LPCWSTR wzWinMetadataFolder=W("\\WinMetadata"); - NewArrayHolder<WCHAR> wzCompletePath; - UINT32 length=0; - - hr = GetCurrentPackagePath(&length, NULL); - if (hr != HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER)) - return hr; - - NewArrayHolder<WCHAR> wzPath_holder = new (nothrow) WCHAR[length]; - - IfNullRet(wzPath_holder); - IfFailRet(GetCurrentPackagePath(&length, wzPath_holder.GetValue())); - - DWORD cchFullPathBuf = length + (DWORD)wcslen(wzWinMetadataFolder) + 1; - IfNullRet(wzCompletePath = new (nothrow) WCHAR[cchFullPathBuf]); - IfFailRet(clr::fs::Path::Combine(wzPath_holder.GetValue(), wzWinMetadataFolder, &cchFullPathBuf, wzCompletePath.GetValue())); - g_pAppXRTInfo->m_AdaptiveAppWinmetadataDir = wzCompletePath.Extract(); - } - - *winMetadDataDir = g_pAppXRTInfo->m_AdaptiveAppWinmetadataDir; - - return S_OK; - } - -#if defined(FEATURE_APPX_BINDER) - //----------------------------------------------------------------------------------------- - // Iterates the current process' packages and returns the first package that contains a - // file matching wzFileName. - // - // wzFileName : The file to look for in the current process' packages. If this is a - // [in] relative path, then it appends the path to the root of each package in - // sequence to see if the resulting path points to an existing file. If this - // is an absolute path, then for each package it determines if the package - // root is a prefix of wzFileName. - // pcchPathName : Upon entry contains the length of the buffer pwzPathName, and upon return - // [in/out] contains either the number of characters written or the buffer size - // required. - // pwzPathName : Upon success, contains the absolute path for the first matching file. - // [out] - HRESULT FindFileInCurrentPackage( - PCWSTR wzFileName, - PUINT32 pcchPathName, - PWSTR pwzPathName, - UINT32 uiFlags, - __in PCWSTR *rgwzAltPaths, - __in UINT32 cAltPaths, - FindFindInPackageFlags findInCurrentPackageFlags) - { - LIMITED_METHOD_CONTRACT; - PRECONDITION(IsAppXProcess()); - PRECONDITION(CheckPointer(wzFileName)); - PRECONDITION(CheckPointer(pcchPathName)); - PRECONDITION(CheckPointer(pwzPathName)); - - HRESULT hr = S_OK; - - if (!IsAppXProcess()) - return E_UNEXPECTED; - - // PACKAGE_FILTER_ALL_LOADED is obsolete, and shouldn't be used. - // We also don't currently handle the case where PACKAGE_FILTER_HEAD isn't set. - _ASSERTE(uiFlags != PACKAGE_FILTER_ALL_LOADED && (uiFlags & PACKAGE_FILTER_HEAD) != 0); - if (uiFlags == PACKAGE_FILTER_ALL_LOADED || (uiFlags & PACKAGE_FILTER_HEAD) == 0) - return E_NOTIMPL; - - // File name must be non-null and relative - if (IsNullOrEmpty(wzFileName) || pcchPathName == nullptr || pwzPathName == nullptr) - return E_INVALIDARG; - - // If we've been provided a full path and the file doesn't actually exist - // then we can immediately say that this function will fail with "file not found". - bool fIsRelative = clr::fs::Path::IsRelative(wzFileName); - if (!fIsRelative && !clr::fs::File::Exists(wzFileName)) - return E_FILE_NOT_FOUND; - - IfFailRet(CheckInitCurrentPackageInfoCache()); - - DWORD const cchFileName = static_cast<DWORD>(wcslen(wzFileName)); - DWORD cchFullPathBuf = _MAX_PATH; - NewArrayHolder<WCHAR> wzFullPathBuf = new (nothrow) WCHAR[cchFullPathBuf]; - IfNullRet(wzFullPathBuf); - - auto FindFileInCurrentPackageHelper = [&](LPCWSTR wzPath) -> HRESULT - { - HRESULT hr = S_OK; - - if (!(findInCurrentPackageFlags & FindFindInPackageFlags_AllowLongFormatPath) && clr::fs::Path::HasLongFormatPrefix(wzPath)) - return COR_E_BAD_PATHNAME; // We can't handle long format paths. - - // If the path is relative, concatenate the package root and the file name and see - // if the file exists. - if (fIsRelative) - { - DWORD cchFullPath = cchFullPathBuf; - hr = clr::fs::Path::Combine(wzPath, wzFileName, &cchFullPath, wzFullPathBuf); - if (hr == E_INSUFFICIENT_BUFFER) - { - IfNullRet(wzFullPathBuf = new (nothrow) WCHAR[cchFullPathBuf = (cchFullPath + 1)]); - hr = clr::fs::Path::Combine(wzPath, wzFileName, &cchFullPath, wzFullPathBuf); - } - IfFailRet(hr); - - if (!clr::fs::Path::IsValid(wzFullPathBuf, cchFullPath, !!(findInCurrentPackageFlags & FindFindInPackageFlags_AllowLongFormatPath))) - return COR_E_BAD_PATHNAME; - - if (clr::fs::File::Exists(wzFullPathBuf)) - { - DWORD cchPathName = *pcchPathName; - *pcchPathName = cchFullPath; - return StringCchCopy(pwzPathName, cchPathName, wzFullPathBuf); - } - } - // If the path is absolute, see if the file name contains the pacakge root as a prefix - // and if the file exists. - else - { - DWORD cchPath = static_cast<DWORD>(wcslen(wzPath)); - - // Determine if wzPath is a path prefix of wzFileName - if (cchPath < cchFileName && - _wcsnicmp(wzPath, wzFileName, cchPath) == 0 && - (wzFileName[cchPath] == W('\\') || wzPath[cchPath-1] == W('\\'))) // Ensure wzPath is not just a prefix, but a path prefix - { - if (clr::fs::File::Exists(wzFileName)) - { - DWORD cchPathName = *pcchPathName; - *pcchPathName = cchFileName; - return StringCchCopy(pwzPathName, cchPathName, wzFileName); - } - } - } - - return S_FALSE; - }; // FindFileInCurrentPackageHelper - - if (!(findInCurrentPackageFlags & FindFindInPackageFlags_SkipCurrentPackageGraph)) - { - PCPACKAGE_INFO pCurNode = reinterpret_cast<PPACKAGE_INFO>( - g_pAppXRTInfo->m_pCurrentPackageInfo->m_pbCurrentPackageInfo); - PCPACKAGE_INFO pEndNode = pCurNode + g_pAppXRTInfo->m_pCurrentPackageInfo->m_nCount; - for (; pCurNode != pEndNode; ++pCurNode) - { - IfFailRet(FindFileInCurrentPackageHelper(pCurNode->path)); - - if (hr == S_OK) - { - return hr; - } - - // End search if dependent packages should not be checked. - if ((uiFlags & PACKAGE_FILTER_DIRECT) == 0) - { - break; - } - } - } - - // Process alternative paths - for (UINT iAltPath = 0; iAltPath < cAltPaths; iAltPath++) - { - IfFailRet(FindFileInCurrentPackageHelper(rgwzAltPaths[iAltPath])); - - if (hr == S_OK) - { - return hr; - } - } - - return E_FILE_NOT_FOUND; - } -#endif // FEATURE_APPX_BINDER - - //----------------------------------------------------------------------------------------- - HRESULT GetAppContainerTokenInfoForProcess( - DWORD dwPid, - NewArrayHolder<BYTE>& pbAppContainerTokenInfo, - DWORD* pcbAppContainerTokenInfo) - { - LIMITED_METHOD_CONTRACT; - - HRESULT hr = S_OK; - - pbAppContainerTokenInfo = nullptr; - - if (!IsAppXSupported()) - { - return S_FALSE; - } - - if (dwPid == GetCurrentProcessId()) - { - if (FAILED(hr = CheckInitAppXRT())) - { - SetLastError(hr); - return S_FALSE; - } - - if (g_pAppXRTInfo->m_pbAppContainerInfo == nullptr) - { - return S_FALSE; - } - else - { - pbAppContainerTokenInfo = g_pAppXRTInfo->m_pbAppContainerInfo.GetValue(); - pbAppContainerTokenInfo.SuppressRelease(); // Caller does not need to free mem. - if (pcbAppContainerTokenInfo != nullptr) - { - *pcbAppContainerTokenInfo = g_pAppXRTInfo->m_cbAppContainerInfo; - } - return S_OK; - } - } - else - { - return ::GetAppContainerTokenInfoForProcess(dwPid, pbAppContainerTokenInfo, pcbAppContainerTokenInfo); - } - } - - // Called during NGen to pretend that we're in a certain package. Due to Windows restriction, we can't - // start NGen worker processes in the right package environment (only in the right AppContainer). So - // NGen calls this function with a package name, to indicate that all AppX-related code should behave as - // if the current process is running in that package. - HRESULT SetCurrentPackageForNGen(__in PCWSTR pszPackageFullName) - { - LIMITED_METHOD_CONTRACT; - - HRESULT hr = S_OK; - - IfFailRet(CheckInitAppXRT()); - - _ASSERTE(IsAppXSupported()); - _ASSERTE(g_pAppXRTInfo->m_hAppXRTMod != nullptr); - - HMODULE hAppXRTMod = g_pAppXRTInfo->m_hAppXRTMod; - OpenPackageInfoByFullName_t *pfnOpenPackageInfoByFullName - = reinterpret_cast<OpenPackageInfoByFullName_t*>(GetProcAddress(hAppXRTMod, "OpenPackageInfoByFullName")); - _ASSERTE(pfnOpenPackageInfoByFullName != nullptr); - if (pfnOpenPackageInfoByFullName == nullptr) - return HRESULT_FROM_GetLastError(); - - ClosePackageInfo_t *pfnClosePackageInfo - = reinterpret_cast<ClosePackageInfo_t*>(GetProcAddress(hAppXRTMod, "ClosePackageInfo")); - _ASSERTE(pfnClosePackageInfo != nullptr); - if (pfnClosePackageInfo == nullptr) - return HRESULT_FROM_GetLastError(); - - GetPackageInfo_t *pfnGetPackageInfo - = reinterpret_cast<GetPackageInfo_t*>(GetProcAddress(hAppXRTMod, "GetPackageInfo")); - _ASSERTE(pfnGetPackageInfo != nullptr); - if (pfnGetPackageInfo == nullptr) - return HRESULT_FROM_GetLastError(); - - PACKAGE_INFO_REFERENCE packageInfoReference; - hr = HRESULT_FROM_WIN32(pfnOpenPackageInfoByFullName(pszPackageFullName, 0, &packageInfoReference)); - if (FAILED(hr)) - return hr; - - // Automatically close packageInfoReference before we return. - class PackageInfoReferenceHolder - { - public: - PackageInfoReferenceHolder(ClosePackageInfo_t *pfnClosePackageInfo, PACKAGE_INFO_REFERENCE &packageInfoReference) - :m_pfnClosePackageInfo(pfnClosePackageInfo), - m_packageInfoReference(packageInfoReference) - { - } - ~PackageInfoReferenceHolder() { m_pfnClosePackageInfo(m_packageInfoReference); } - private: - ClosePackageInfo_t *m_pfnClosePackageInfo; - PACKAGE_INFO_REFERENCE &m_packageInfoReference; - } pirh(pfnClosePackageInfo, packageInfoReference); - - UINT32 cbBuffer = 0; - hr = HRESULT_FROM_WIN32(pfnGetPackageInfo(packageInfoReference, PACKAGE_FILTER_CLR_DEFAULT, &cbBuffer, nullptr, nullptr)); - if (hr != E_INSUFFICIENT_BUFFER) - return hr; - - NewArrayHolder<BYTE> pbBuffer(new (nothrow) BYTE[cbBuffer]); - IfNullRet(pbBuffer); - - UINT32 nCount = 0; - IfFailRet(HRESULT_FROM_WIN32(pfnGetPackageInfo(packageInfoReference, PACKAGE_FILTER_CLR_DEFAULT, &cbBuffer, pbBuffer, &nCount))); - - NewHolder<AppXRTInfo::CurrentPackageInfo> pPkgInfo( - new (nothrow) AppXRTInfo::CurrentPackageInfo(cbBuffer, pbBuffer.Extract(), nCount)); - IfNullRet(pPkgInfo); - - if (InterlockedCompareExchangeT<AppXRTInfo::CurrentPackageInfo>( - &g_pAppXRTInfo->m_pCurrentPackageInfo, pPkgInfo, nullptr) == nullptr) - { - pPkgInfo.SuppressRelease(); - } - - g_pAppXRTInfo->m_fIsAppXProcess = true; - g_pAppXRTInfo->m_fIsAppXNGen = true; - - return hr; - } - -#endif // DACCESS_COMPILE -} // namespace AppX - - -#endif // FEATURE_CORECLR diff --git a/src/utilcode/ccomprc.cpp b/src/utilcode/ccomprc.cpp index a4c79fc127..ed902dc6ca 100644 --- a/src/utilcode/ccomprc.cpp +++ b/src/utilcode/ccomprc.cpp @@ -261,12 +261,8 @@ HRESULT CCompRC::AddMapNode(LocaleID langId, HRESOURCEDLL hInst, BOOL fMissing) //***************************************************************************** // Initialize //***************************************************************************** -#ifndef FEATURE_CORECLR -LPCWSTR CCompRC::m_pDefaultResource = W("mscorrc.dll"); -#else // !FEATURE_CORECLR LPCWSTR CCompRC::m_pDefaultResource = W("mscorrc.debug.dll"); LPCWSTR CCompRC::m_pFallbackResource= W("mscorrc.dll"); -#endif // !FEATURE_CORECLR #ifdef FEATURE_PAL LPCSTR CCompRC::m_pDefaultResourceDomain = "mscorrc.debug"; @@ -482,7 +478,6 @@ CCompRC* CCompRC::GetDefaultResourceDll() return &m_DefaultResourceDll; } -#ifdef FEATURE_CORECLR LONG CCompRC::m_dwFallbackInitialized = 0; CCompRC CCompRC::m_FallbackResourceDll; @@ -510,7 +505,6 @@ CCompRC* CCompRC::GetFallbackResourceDll() return &m_FallbackResourceDll; } -#endif // FEATURE_CORECLR //***************************************************************************** @@ -747,7 +741,6 @@ HRESULT CCompRC::LoadString(ResourceCategory eCategory, LocaleID langId, UINT iR // Failed to load string if ( hr != E_OUTOFMEMORY && ShouldUseFallback()) { -#ifdef FEATURE_CORECLR CCompRC* pFallback=CCompRC::GetFallbackResourceDll(); if (pFallback) { @@ -761,13 +754,11 @@ HRESULT CCompRC::LoadString(ResourceCategory eCategory, LocaleID langId, UINT iR if(SUCCEEDED(hr)) return hr; } -#endif switch (eCategory) { case Optional: hr = E_FAIL; break; -#ifdef FEATURE_CORECLR case DesktopCLR: hr = E_FAIL; break; @@ -837,12 +828,6 @@ HRESULT CCompRC::LoadString(ResourceCategory eCategory, LocaleID langId, UINT iR // if we got here then we couldn't get the fallback message // the fallback message is required so just falling through into "Required" -#else // FEATURE_CORECLR - // everything that's not optional goes here for Desktop - case DesktopCLR: - case Debugging: - case Error: -#endif case Required: if ( hr != E_OUTOFMEMORY) @@ -1035,7 +1020,6 @@ HRESULT CCompRC::LoadLibraryThrows(HRESOURCEDLL * pHInst) PathString rcPath; // Path to resource DLL. // Try first in the same directory as this dll. -#if defined(FEATURE_CORECLR) VALIDATECORECLRCALLBACKS(); @@ -1046,73 +1030,6 @@ HRESULT CCompRC::LoadLibraryThrows(HRESOURCEDLL * pHInst) hr = LoadLibraryHelper(pHInst, rcPath); -#else // FEATURE_CORECLR - - if (!WszGetModuleFileName(GetModuleInst(), rcPath)) - return HRESULT_FROM_GetLastError(); - - CopySystemDirectory(rcPath, rcPath); - - hr = LoadLibraryHelper(pHInst, rcPath); - if (hr == E_OUTOFMEMORY) - return hr; - - // In case of default rc file, also try CORSystemDirectory. - // Note that GetRequestedRuntimeInfo is a function in ths shim. As of 12/06, this is the only - // place where utilcode appears to take a dependency on the shim. This forces everyone that links - // with us to also dynamically link to mscoree.dll. Perhaps this should be a delay-load to prevent - // that static dependency and have a gracefull fallback when the shim isn't installed. - // We don't do this in DAC builds because mscordacwks.dll cannot take a dependency on other CLR - // dlls (eg. you must be able to examine a managed dump on a machine without any CLR installed). -#ifndef DACCESS_COMPILE - if (FAILED(hr) && m_pResourceFile == m_pDefaultResource) - { -#ifdef SELF_NO_HOST - WCHAR rcVersion[MAX_VERSION_STRING]; - DWORD rcVersionSize; - - DWORD corSystemPathSize; - - // The reason for using GetRequestedRuntimeInfo is the ability to suppress message boxes - // with RUNTIME_INFO_DONT_SHOW_ERROR_DIALOG. - COUNT_T size = MAX_PATH; - hr = LegacyActivationShim::GetRequestedRuntimeInfo( - NULL, - W("v")VER_PRODUCTVERSION_NO_QFE_STR_L, - NULL, - 0, - RUNTIME_INFO_UPGRADE_VERSION|RUNTIME_INFO_DONT_SHOW_ERROR_DIALOG|RUNTIME_INFO_CONSIDER_POST_2_0, - rcPath.OpenUnicodeBuffer(size-1), - size, - &corSystemPathSize, - rcVersion, - NumItems(rcVersion), - &rcVersionSize); - - rcPath.CloseBuffer(corSystemPathSize); - - if (SUCCEEDED(hr)) - { - if (rcVersionSize > 0) - { - rcPath.Append(rcVersion); - rcPath.Append(W("\\")); - } - } -#else - // If we're hosted, we have the advantage of a CoreClrCallbacks reference. - // More importantly, we avoid calling back to mscoree.dll. - - hr = GetClrCallbacks().m_pfnGetCORSystemDirectory(rcPath); -#endif - if (SUCCEEDED(hr)) - { - hr = LoadLibraryHelper(pHInst, rcPath); - } - } -#endif // !DACCESS_COMPILE - -#endif // FEATURE_CORECLR #endif // CROSSGEN_COMPILE diff --git a/src/utilcode/clrconfig.cpp b/src/utilcode/clrconfig.cpp index 163974999d..7bd404b5d4 100644 --- a/src/utilcode/clrconfig.cpp +++ b/src/utilcode/clrconfig.cpp @@ -30,10 +30,6 @@ CLRConfig::GetConfigValueFunction CLRConfig::s_GetConfigValueCallback = NULL; // CLRConfig::GetPerformanceDefaultValueFunction CLRConfig::s_GetPerformanceDefaultValueCallback = NULL; -#ifdef FEATURE_WIN_DB_APPCOMPAT -PFN_CptQuirkIsEnabled3 CLRConfig::s_IsQuirkEnabledCallback = NULL; -PFN_CptQuirkGetData2 CLRConfig::s_GetQuirkValueCallback = NULL; -#endif // // Creating structs using the macro table in CLRConfigValues.h @@ -100,79 +96,6 @@ PFN_CptQuirkGetData2 CLRConfig::s_GetQuirkValueCallback = NULL; #undef CONFIG_STRING_INFO_DIRECT_ACCESS -#ifdef FEATURE_WIN_DB_APPCOMPAT - -#define MAX_QUIRK_LENGTH 60 -#define WIN_DB_COMPONENT_NAME W("NETFX.") -#define WIN_DB_COMPONENT_NAME_LENGTH 6 - -// queries the DB if the quirk is enabled. If the quirk is enabled then it also gets the value associated with the quirk. -// pass in quirkData as NULL if the value is not required and only enabled/disabled is needed. -// Length of quirk cannot be greater than 60. If it is greater than 60 then this api returns E_FAIL. -HRESULT CLRConfig::getQuirkEnabledAndValueFromWinDB(LPCWSTR wszQuirkName, BOOL* isEnabled, CPT_QUIRK_DATA* quirkData) -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - SO_TOLERANT; - PRECONDITION(CheckPointer(isEnabled, NULL_NOT_OK)); - } - CONTRACTL_END; - - if(wszQuirkName == NULL) - return E_FAIL; - - WCHAR wszCompleteQuirkName[MAX_QUIRK_LENGTH + WIN_DB_COMPONENT_NAME_LENGTH + 1]; - WCHAR wszComponentName[] = WIN_DB_COMPONENT_NAME; - size_t cchCompleteQuirkName = MAX_QUIRK_LENGTH + WIN_DB_COMPONENT_NAME_LENGTH + 1; - - _ASSERT(wcslen(wszComponentName) == WIN_DB_COMPONENT_NAME_LENGTH); - - size_t cchOrig = wcslen(wszQuirkName); - if(cchOrig > MAX_QUIRK_LENGTH) - { - return E_FAIL; - } - - // Create comlete name of the quirk. Windows expects complete quirkName i.e. componentName.quirkName - // eg. ETWEnabled will become NETFX.ETWEnabled - errno_t err = wcsncpy_s(wszCompleteQuirkName, cchCompleteQuirkName, wszComponentName, WIN_DB_COMPONENT_NAME_LENGTH); - if (err != 0) - { - return E_FAIL; - } - - err = wcscat_s(wszCompleteQuirkName, cchCompleteQuirkName, wszQuirkName); - if (err != 0) - { - return E_FAIL; - } - - - UINT32 version = 0xFFFFFFFF; - BOOL fIsEnabled; - //call windows api - // Version passed must be 0xFFFFFFFF for NETFX. Passing any other version requires more - // understanding of the windows API. - fIsEnabled = s_IsQuirkEnabledCallback(wszCompleteQuirkName,version); - - if(fIsEnabled && quirkData != NULL) - { - quirkData->Size = sizeof(CPT_QUIRK_DATA); - // Query for quirkData - if(!SUCCEEDED(s_GetQuirkValueCallback(wszCompleteQuirkName, quirkData))) - { - return E_FAIL; - } - } - - *isEnabled = fIsEnabled; - - return S_OK; -} - -#endif // Return if a quirk is a enabled. @@ -190,22 +113,6 @@ BOOL CLRConfig::IsConfigEnabled(const ConfigDWORDInfo & info) DWORD result = info.defaultValue; -#ifdef FEATURE_WIN_DB_APPCOMPAT - // Windows Shim DB should be the first place to look as it applies microsoft enforced policy - // and overrides setting at any other place like config or registry - if(CheckLookupOption(info, IgnoreWindowsQuirkDB) == FALSE && - s_IsQuirkEnabledCallback != NULL )// Check that IsQuirkEnabledCallback function has been registered. - { - BOOL enabledInDB = FALSE; - if(SUCCEEDED(getQuirkEnabledAndValueFromWinDB(info.name, &enabledInDB, NULL))) - { - if(enabledInDB) - { - return TRUE; - } - } - } -#endif // // Set up REGUTIL options. // @@ -328,40 +235,6 @@ DWORD CLRConfig::GetConfigValue(const ConfigDWORDInfo & info, bool acceptExplici _ASSERTE (isDefault != nullptr); -#ifdef FEATURE_WIN_DB_APPCOMPAT - // Windows Shim DB should be the first place to look as it applies microsoft enforced policy - // and overrides setting at any other place like config or registry - if(CheckLookupOption(info, IgnoreWindowsQuirkDB) == FALSE && - s_IsQuirkEnabledCallback != NULL )// Check that IsQuirkEnabledCallback function has been registered. - { - BOOL isEnabledInDB = FALSE; - CPT_QUIRK_DATA quirkData; - if(SUCCEEDED(getQuirkEnabledAndValueFromWinDB(info.name, &isEnabledInDB, &quirkData))) - { - if(isEnabledInDB) - { - WCHAR *end; - errno = 0; - DWORD resultMaybe = wcstoul(quirkData.CommandLine, &end, 0); - - // errno is ERANGE if the number is out of range, and end is set to pvalue if - // no valid conversion exists. - if (errno != ERANGE && end != quirkData.CommandLine) - { - *isDefault = false; - return resultMaybe; - } - else - { - // If an invalid value is defined we treat it as the default value. - // i.e. we don't look further. - *isDefault = true; - return info.defaultValue; - } - } - } - } -#endif // FEATURE_WIN_DB_APPCOMPAT // // Set up REGUTIL options. @@ -557,30 +430,6 @@ HRESULT CLRConfig::GetConfigValue(const ConfigStringInfo & info, __deref_out_z L LPWSTR result = NULL; -#ifdef FEATURE_WIN_DB_APPCOMPAT - // Windows Shim DB should be the first place to look as it applies microsoft enforced policy - // and overrides setting at any other place like config or registry - if(CheckLookupOption(info, IgnoreWindowsQuirkDB) == FALSE && - s_IsQuirkEnabledCallback != NULL )// Check that IsQuirkEnabledCallback function has been registered. - { - - BOOL isEnabledInDB = FALSE; - CPT_QUIRK_DATA quirkData; - if(SUCCEEDED(getQuirkEnabledAndValueFromWinDB(info.name, &isEnabledInDB, &quirkData))) - { - if(isEnabledInDB) - { - size_t len = wcslen(quirkData.CommandLine) + 1; - result = new (nothrow) WCHAR[len]; - if (result == NULL) - { - RETURN E_OUTOFMEMORY; - } - wcscpy_s(result, len, quirkData.CommandLine); - } - } - } -#endif // FEATURE_WIN_DB_APPCOMPAT // // Set up REGUTIL options. @@ -808,14 +657,6 @@ void CLRConfig::RegisterGetPerformanceDefaultValueCallback(GetPerformanceDefault s_GetPerformanceDefaultValueCallback = func; } -#ifdef FEATURE_WIN_DB_APPCOMPAT -void CLRConfig::RegisterWinDbQuirkApis(PFN_CptQuirkIsEnabled3 func1, PFN_CptQuirkGetData2 func2) -{ - LIMITED_METHOD_CONTRACT; - s_IsQuirkEnabledCallback = func1; - s_GetQuirkValueCallback = func2; -} -#endif // FEATURE_WIN_DB_APPCOMPAT // // Helper method to translate LookupOptions to REGUTIL::CORConfigLevel. diff --git a/src/utilcode/clrhost.cpp b/src/utilcode/clrhost.cpp index 8a61eee966..15678a9861 100644 --- a/src/utilcode/clrhost.cpp +++ b/src/utilcode/clrhost.cpp @@ -16,9 +16,7 @@ #include "contract.h" #include "tls.h" -#if defined(FEATURE_CORECLR) || !defined(SELF_NO_HOST) || defined(DACCESS_COMPILE) || defined(CROSSGEN_COMPILE) CoreClrCallbacks g_CoreClrCallbacks; -#endif // In some cirumstance (e.g, the thread suspecd another thread), allocation on heap @@ -206,7 +204,6 @@ int RFS_HashStack () #endif // FAILPOINTS_ENABLED -#if defined(FEATURE_CORECLR) || !defined(SELF_NO_HOST) || defined(DACCESS_COMPILE) //----------------------------------------------------------------------------------- // This is the approved way to get a module handle to mscorwks.dll (or coreclr.dll). @@ -264,7 +261,6 @@ HMODULE GetCLRModule () return g_CoreClrCallbacks.m_hmodCoreCLR; } -#endif // defined(FEATURE_CORECLR) || !defined(SELF_NO_HOST) || defined(DACCESS_COMPILE) #if defined(SELF_NO_HOST) @@ -402,7 +398,6 @@ LoadsTypeHolder::~LoadsTypeHolder() // versions in the same process. //-------------------------------------------------------------------------- -#if defined(FEATURE_CORECLR) || !defined(SELF_NO_HOST) || defined(DACCESS_COMPILE) //-------------------------------------------------------------------------- // One-time initialized called by coreclr.dll in its dllmain. @@ -435,7 +430,7 @@ void OnUninitializedCoreClrCallbacks() // (other than coreclr.dll) that links to utilcode.lib, or that you're using a nohost // variant of utilcode.lib but hitting code that assumes there is a CLR in the process. // - // Under FEATURE_CORECLR (and not SELF_NO_HOST), it is expected that coreclr.dll + // It is expected that coreclr.dll // is the ONLY dll that links to utilcode libraries. // // If you must introduce a new dll that links to utilcode.lib, it is your responsibility @@ -456,4 +451,3 @@ void OnUninitializedCoreClrCallbacks() } #endif // _DEBUG -#endif // defined(FEATURE_CORECLR) || !defined(SELF_NO_HOST) || defined(DACCESS_COMPILE) diff --git a/src/utilcode/dlwrap.cpp b/src/utilcode/dlwrap.cpp index 0c9026a421..a6771c9daa 100644 --- a/src/utilcode/dlwrap.cpp +++ b/src/utilcode/dlwrap.cpp @@ -77,155 +77,3 @@ VerQueryValueW_NoThrow( } -#if !defined(FEATURE_CORECLR) && !defined(CROSSGEN_COMPILE) -// The following functions are not used in CoreCLR. Normally LINKER can remove these functions -// from generated files. But LINKER does it in two steps: -// 1. If no function in a source file is used, the file is ignored by LINKER -// 2. If one function is used, LINKER will first make sure all imported functions in the file -// is available, and then it will remove unused functions. -// Instead of specifying all libs for imported functions needed by the following codes, we just -// remove them from compiling phase. -__success(return) -BOOL -CreateUrlCacheEntryW_NoThrow( - IN LPCWSTR lpszUrlName, - IN DWORD dwExpectedFileSize, - IN LPCWSTR lpszFileExtension, - __out_ecount(MAX_LONGPATH+1) LPWSTR lpszFileName, - IN DWORD dwReserved - ) -{ - WRAPPER_NO_CONTRACT; - HRESULT hr=S_OK; - BOOL bRet=FALSE; - EX_TRY - { - bRet=CreateUrlCacheEntryW(lpszUrlName,dwExpectedFileSize,lpszFileExtension, - lpszFileName,dwReserved); - } - EX_CATCH_HRESULT(hr); - if (hr!=S_OK) - SetLastError(hr); - return bRet; - -} - -BOOL -CommitUrlCacheEntryW_NoThrow( - IN LPCWSTR lpszUrlName, - IN LPCWSTR lpszLocalFileName, - IN FILETIME ExpireTime, - IN FILETIME LastModifiedTime, - IN DWORD CacheEntryType, - IN LPCWSTR lpHeaderInfo, - IN DWORD dwHeaderSize, - IN LPCWSTR lpszFileExtension, - IN LPCWSTR lpszOriginalUrl - ) -{ - WRAPPER_NO_CONTRACT; - HRESULT hr=S_OK; - BOOL bRet=FALSE; - EX_TRY - { - bRet=CommitUrlCacheEntryW(lpszUrlName,lpszLocalFileName,ExpireTime, - LastModifiedTime,CacheEntryType,(LPWSTR)lpHeaderInfo, - dwHeaderSize,lpszFileExtension,lpszOriginalUrl); - } - EX_CATCH_HRESULT(hr); - if (hr!=S_OK) - SetLastError(hr); - return bRet; - -} - -BOOL -InternetTimeToSystemTimeA_NoThrow( - IN LPCSTR lpszTime, // NULL terminated string - OUT SYSTEMTIME *pst, // output in GMT time - IN DWORD dwReserved - ) -{ - WRAPPER_NO_CONTRACT; - HRESULT hr=S_OK; - BOOL bRet=FALSE; - EX_TRY - { - bRet=InternetTimeToSystemTimeA(lpszTime,pst,dwReserved); - } - EX_CATCH_HRESULT(hr); - if (hr!=S_OK) - SetLastError(hr); - return bRet; - -} - -HRESULT -CoInternetCreateSecurityManager_NoThrow( - IServiceProvider *pSP, - IInternetSecurityManager **ppSM, - DWORD dwReserved - ) -{ - WRAPPER_NO_CONTRACT; - HRESULT hr=S_OK; - EX_TRY - { - hr=CoInternetCreateSecurityManager(pSP,ppSM, dwReserved); - } - EX_CATCH_HRESULT(hr); - return hr; -} - -HRESULT -URLDownloadToCacheFileW_NoThrow( - LPUNKNOWN lpUnkcaller, - LPCWSTR szURL, - __out_ecount(dwBufLength) LPWSTR szFileName, - DWORD dwBufLength, - DWORD dwReserved, - IBindStatusCallback *pBSC - ) -{ - WRAPPER_NO_CONTRACT; - HRESULT hr=S_OK; - EX_TRY - { - hr=URLDownloadToCacheFileW(lpUnkcaller,szURL,szFileName,dwBufLength,dwReserved,pBSC); - } - EX_CATCH_HRESULT(hr); - return hr; -} - -HRESULT -CoInternetGetSession_NoThrow( - WORD dwSessionMode, - IInternetSession **ppIInternetSession, - DWORD dwReserved - ) -{ - WRAPPER_NO_CONTRACT; - HRESULT hr=S_OK; - EX_TRY - { - hr=CoInternetGetSession(dwSessionMode,ppIInternetSession,dwReserved); - } - EX_CATCH_HRESULT(hr); - return hr; -} - -HRESULT -CopyBindInfo_NoThrow( - const BINDINFO * pcbiSrc, BINDINFO * pbiDest - ) -{ - WRAPPER_NO_CONTRACT; - HRESULT hr=S_OK; - EX_TRY - { - hr=CopyBindInfo(pcbiSrc,pbiDest ); - } - EX_CATCH_HRESULT(hr); - return hr; -} -#endif // FEATURE_CORECLR && !CROSSGEN_COMPILE diff --git a/src/utilcode/downlevel.cpp b/src/utilcode/downlevel.cpp index ec8d3f5a15..6ff7b82815 100644 --- a/src/utilcode/downlevel.cpp +++ b/src/utilcode/downlevel.cpp @@ -1924,11 +1924,11 @@ namespace DownLevel if (dwFindNLSStringFlags & (FIND_ENDSWITH | FIND_FROMEND)) { - retValue = NewApis::LastIndexOfString(lpLocaleName, lpStringSource, cchSource, lpStringValue, cchValue, (int) dwFindNLSStringFlags & FIND_NLS_STRING_FLAGS_NEGATION, dwFindNLSStringFlags & FIND_ENDSWITH); + retValue = NewApis::LastIndexOfString(lpLocaleName, lpStringSource, cchSource, lpStringValue, cchValue, (int) dwFindNLSStringFlags & FIND_NLS_STRING_FLAGS_NEGATION, dwFindNLSStringFlags & FIND_ENDSWITH, pcchFound); } else { - retValue = NewApis::IndexOfString(lpLocaleName, lpStringSource, cchSource, lpStringValue, cchValue, (int) dwFindNLSStringFlags & FIND_NLS_STRING_FLAGS_NEGATION, dwFindNLSStringFlags & FIND_STARTSWITH); + retValue = NewApis::IndexOfString(lpLocaleName, lpStringSource, cchSource, lpStringValue, cchValue, (int) dwFindNLSStringFlags & FIND_NLS_STRING_FLAGS_NEGATION, dwFindNLSStringFlags & FIND_STARTSWITH, pcchFound); } return retValue; } diff --git a/src/utilcode/ex.cpp b/src/utilcode/ex.cpp index bb164571ad..92b25b0aaf 100644 --- a/src/utilcode/ex.cpp +++ b/src/utilcode/ex.cpp @@ -2037,9 +2037,9 @@ static DWORD MarkAsThrownByUsWorker(UINT numArgs, /*out*/ ULONG_PTR exceptionArg exceptionArgs[0] = arg0; -#if !defined(FEATURE_UTILCODE_NO_DEPENDENCIES) && (defined(FEATURE_CORECLR) || !defined(SELF_NO_HOST) || defined(DACCESS_COMPILE)) +#if !defined(FEATURE_UTILCODE_NO_DEPENDENCIES) exceptionArgs[INSTANCE_TAGGED_SEH_PARAM_ARRAY_SIZE - 1] = (ULONG_PTR) (GetCLRModule()); -#endif // !defined(FEATURE_UTILCODE_NO_DEPENDENCIES) && defined(FEATURE_CORECLR) || !defined(SELF_NO_HOST) || defined(DACCESS_COMPILE) +#endif // !defined(FEATURE_UTILCODE_NO_DEPENDENCIES) return INSTANCE_TAGGED_SEH_PARAM_ARRAY_SIZE; } @@ -2086,15 +2086,15 @@ BOOL WasThrownByUs(const EXCEPTION_RECORD *pcER, DWORD dwExceptionCode) { return FALSE; } -#if!defined(FEATURE_UTILCODE_NO_DEPENDENCIES) && (defined(FEATURE_CORECLR) || !defined(SELF_NO_HOST) || defined(DACCESS_COMPILE)) +#if!defined(FEATURE_UTILCODE_NO_DEPENDENCIES) if ( ((ULONG_PTR)(GetCLRModule())) != pcER->ExceptionInformation[INSTANCE_TAGGED_SEH_PARAM_ARRAY_SIZE - 1] ) { return FALSE; } return TRUE; -#else // !(!defined(FEATURE_UTILCODE_NO_DEPENDENCIES) && (defined(FEATURE_CORECLR) || !defined(SELF_NO_HOST) || defined(DACCESS_COMPILE))) +#else // !(!defined(FEATURE_UTILCODE_NO_DEPENDENCIES) return FALSE; -#endif // !defined(FEATURE_UTILCODE_NO_DEPENDENCIES) && defined(FEATURE_CORECLR) || !defined(SELF_NO_HOST) || defined(DACCESS_COMPILE) +#endif // !defined(FEATURE_UTILCODE_NO_DEPENDENCIES) } diff --git a/src/utilcode/longfilepathwrappers.cpp b/src/utilcode/longfilepathwrappers.cpp index 5272d35807..2e493d02b5 100644 --- a/src/utilcode/longfilepathwrappers.cpp +++ b/src/utilcode/longfilepathwrappers.cpp @@ -1187,7 +1187,6 @@ FindFirstFileExWrapper( } #endif //!FEATURE_PAL -#if defined(FEATURE_CORECLR) || defined(CROSSGEN_COMPILE) #ifndef FEATURE_PAL @@ -1247,7 +1246,6 @@ BOOL PAL_GetPALDirectoryWrapper(SString& pbuffer) #endif // FEATURE_PAL -#endif // FEATURE_CORECLR || CROSSGEN_COMPILE //Implementation of LongFile Helpers const WCHAR LongFile::DirectorySeparatorChar = W('\\'); diff --git a/src/utilcode/makepath.cpp b/src/utilcode/makepath.cpp index 701c525cf4..6e0b56281c 100644 --- a/src/utilcode/makepath.cpp +++ b/src/utilcode/makepath.cpp @@ -15,158 +15,6 @@ #include "utilcode.h" #include "ex.h" -#ifndef FEATURE_CORECLR -/*** -*void MakePath() - build path name from components -* -*Purpose: -* create a path name from its individual components -* -*Entry: -* WCHAR *path - pointer to buffer for constructed path -* WCHAR *drive - pointer to drive component, may or may not contain -* trailing ':' -* WCHAR *dir - pointer to subdirectory component, may or may not include -* leading and/or trailing '/' or '\' characters -* WCHAR *fname - pointer to file base name component -* WCHAR *ext - pointer to extension component, may or may not contain -* a leading '.'. -* -*Exit: -* path - pointer to constructed path name -* -*Exceptions: -* -*******************************************************************************/ - -void MakePath ( - __out_ecount (MAX_LONGPATH) WCHAR *path, - __in LPCWSTR drive, - __in LPCWSTR dir, - __in LPCWSTR fname, - __in LPCWSTR ext - ) -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - FORBID_FAULT; - } - CONTRACTL_END - - const WCHAR *p; - DWORD count = 0; - - /* we assume that the arguments are in the following form (although we - * do not diagnose invalid arguments or illegal filenames (such as - * names longer than 8.3 or with illegal characters in them) - * - * drive: - * A ; or - * A: - * dir: - * \top\next\last\ ; or - * /top/next/last/ ; or - * either of the above forms with either/both the leading - * and trailing / or \ removed. Mixed use of '/' and '\' is - * also tolerated - * fname: - * any valid file name - * ext: - * any valid extension (none if empty or null ) - */ - - /* copy drive */ - - if (drive && *drive) { - *path++ = *drive; - *path++ = _T(':'); - count += 2; - } - - /* copy dir */ - - if ((p = dir)) { - while (*p) { - *path++ = *p++; - count++; - - if (count == MAX_LONGPATH) { - --path; - *path = _T('\0'); - return; - } - } - -#ifdef _MBCS - if (*(p=_mbsdec(dir,p)) != _T('/') && *p != _T('\\')) { -#else /* _MBCS */ - // suppress warning for the following line; this is safe but would require significant code - // delta for prefast to understand. -#ifdef _PREFAST_ - #pragma warning( suppress: 26001 ) -#endif - if (*(p-1) != _T('/') && *(p-1) != _T('\\')) { -#endif /* _MBCS */ - *path++ = _T('\\'); - count++; - - if (count == MAX_LONGPATH) { - --path; - *path = _T('\0'); - return; - } - } - } - - /* copy fname */ - - if ((p = fname)) { - while (*p) { - *path++ = *p++; - count++; - - if (count == MAX_LONGPATH) { - --path; - *path = _T('\0'); - return; - } - } - } - - /* copy ext, including 0-terminator - check to see if a '.' needs - * to be inserted. - */ - - if ((p = ext)) { - if (*p && *p != _T('.')) { - *path++ = _T('.'); - count++; - - if (count == MAX_LONGPATH) { - --path; - *path = _T('\0'); - return; - } - } - - while ((*path++ = *p++)) { - count++; - - if (count == MAX_LONGPATH) { - --path; - *path = _T('\0'); - return; - } - } - } - else { - /* better add the 0-terminator */ - *path = _T('\0'); - } -} -#endif // !FEATURE_CORECLR /*** *void Makepath() - build path name from components @@ -307,57 +155,6 @@ void MakePath ( szPath.Shrink(count + 1); } -#if !defined(FEATURE_CORECLR) -static LPCWSTR g_wszProcessExePath = NULL; - -HRESULT GetProcessExePath(LPCWSTR *pwszProcessExePath) -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - CONSISTENCY_CHECK(CheckPointer(pwszProcessExePath)); - } - CONTRACTL_END; - - HRESULT hr = S_OK; - - if (g_wszProcessExePath == NULL) - { - DWORD cchProcName = 0; - NewArrayHolder<WCHAR> wszProcName; - EX_TRY - { - PathString wszProcNameString; - cchProcName = WszGetModuleFileName(NULL, wszProcNameString); - if (cchProcName == 0) - { - hr = HRESULT_FROM_GetLastError(); - } - else - { - wszProcName = wszProcNameString.GetCopyOfUnicodeString(); - } - } - EX_CATCH_HRESULT(hr); - - if (FAILED(hr)) - { - return hr; - } - - if (InterlockedCompareExchangeT(&g_wszProcessExePath, const_cast<LPCWSTR>(wszProcName.GetValue()), NULL) == NULL) - { - wszProcName.SuppressRelease(); - } - } - _ASSERTE(g_wszProcessExePath != NULL); - _ASSERTE(SUCCEEDED(hr)); - - *pwszProcessExePath = g_wszProcessExePath; - return hr; -} -#endif // Returns the directory for HMODULE. So, if HMODULE was for "C:\Dir1\Dir2\Filename.DLL", // then this would return "C:\Dir1\Dir2\" (note the trailing backslash). diff --git a/src/utilcode/newapis.cpp b/src/utilcode/newapis.cpp index 3717f0280d..e7d4b9f08b 100644 --- a/src/utilcode/newapis.cpp +++ b/src/utilcode/newapis.cpp @@ -32,27 +32,6 @@ namespace NewApis FARPROC result = NULL; -#if !defined(FEATURE_CORECLR) && !defined(CROSSGEN_COMPILE) - - // First try to use the function defined in the culture dll - // if we are running on a platform prior to Win7 - if(!IsWindows7Platform()) - { - // only need to load the culture dll's handle once then we can hold onto it - static HMODULE hCulture = NULL; - // if we haven't loaded the culture dll yet - if (hCulture == NULL) - { - UtilCode::LoadLibraryShim(MAKEDLLNAME_W(W("culture")), NULL, 0, &hCulture); - } - - // make sure we were successful before using the handle - if (hCulture != NULL) - { - result=GetProcAddress(hCulture,lpProcName); - } - } -#endif // !FEATURE_CORECLR && !CROSSGEN_COMPILE // next try the kernel if(result==NULL) @@ -203,9 +182,6 @@ namespace NewApis GetLocaleInfoEx (__in LPCWSTR lpLocaleName, __in LCTYPE LCType, __out_ecount_opt(cchData) LPWSTR lpLCData, __in int cchData) { _ASSERTE((lpLCData == NULL && cchData == 0) || (lpLCData != NULL && cchData > 0)); - // ComNlsInfo::nativeInitCultureData calls GetLocaleInfoEx with LcType LOCALE_SNAME - // to determine if this is a valid culture. We shouldn't assert in this case, but - // all others we should. _ASSERTE(LCType == LOCALE_SNAME || NotLeakingFrameworkOnlyCultures(lpLocaleName)); int retVal; @@ -775,12 +751,14 @@ inline BOOL IsInvariantCasing(__in LPCWSTR lpLocaleName, __in DWORD dwMapFlags) int IndexOfString( __in LPCWSTR lpLocaleName, __in_ecount(cchCount1) LPCWSTR pString1, // String to search in __in int cchCount1, // length of pString1 - __in_ecount(cchCount2) LPCWSTR pString2, // String we're looking for + __in_ecount(cchCount2) LPCWSTR pString2, // String we're looking for __in int cchCount2, // length of pString2 __in DWORD dwFlags, // search flags - __in BOOL startWith) // true if we need to check for prefix case + __in BOOL startWith, // true if we need to check for prefix case + __out_opt LPINT pcchFound) // length of the string we found in source { int iRetVal = -1; + int foundLengthInSource = 0; // // Check the ranges. @@ -809,6 +787,7 @@ inline BOOL IsInvariantCasing(__in LPCWSTR lpLocaleName, __in DWORD dwMapFlags) if (dwFlags == COMPARE_OPTIONS_ORDINAL) { iRetVal = FastIndexOfString(pString1, cchCount1, pString2, cchCount2); + foundLengthInSource = cchCount2; goto lExit; } //For dwFlags, 0 is the default, 1 is ignore case, we can handle both. @@ -822,6 +801,11 @@ inline BOOL IsInvariantCasing(__in LPCWSTR lpLocaleName, __in DWORD dwMapFlags) iRetVal = FastIndexOfString(pString1, cchCount1, pString2, cchCount2); else iRetVal = FastIndexOfStringInsensitive(pString1, cchCount1, pString2, cchCount2); + + // both are ascii strings, + // the length should be the same as the length of the string we are searching for. + foundLengthInSource = cchCount2; + goto lExit; } } @@ -853,6 +837,7 @@ inline BOOL IsInvariantCasing(__in LPCWSTR lpLocaleName, __in DWORD dwMapFlags) if (result == CSTR_EQUAL) { iRetVal = iOffset; + foundLengthInSource = iLength; break; } else if (result == 0) @@ -869,6 +854,9 @@ inline BOOL IsInvariantCasing(__in LPCWSTR lpLocaleName, __in DWORD dwMapFlags) { iRetVal = -1; } + + if(iRetVal != -1 && pcchFound != NULL) + *pcchFound = foundLengthInSource; return iRetVal; } @@ -880,13 +868,16 @@ inline BOOL IsInvariantCasing(__in LPCWSTR lpLocaleName, __in DWORD dwMapFlags) int LastIndexOfString( __in LPCWSTR lpLocaleName, __in_ecount(cchCount1) LPCWSTR pString1, // String to search in __in int cchCount1, // length of pString1 - __in_ecount(cchCount2) LPCWSTR pString2, // String we're looking for + __in_ecount(cchCount2) LPCWSTR pString2, // String we're looking for __in int cchCount2, // length of pString2 __in DWORD dwFlags, - __in BOOL endWith) // check suffix case + __in BOOL endWith, // check suffix case + __out_opt LPINT pcchFound) // length of the string we found in source { INT32 iRetVal = -1; BOOL comparedOrdinal = FALSE; + + int foundLengthInSource = 0; // Check for empty strings if (cchCount1 == 0) @@ -917,6 +908,7 @@ inline BOOL IsInvariantCasing(__in LPCWSTR lpLocaleName, __in DWORD dwMapFlags) { iRetVal = FastLastIndexOfString(pString1, cchCount1, pString2, cchCount2); comparedOrdinal = TRUE; + foundLengthInSource = cchCount2; goto lExit; } @@ -931,6 +923,8 @@ inline BOOL IsInvariantCasing(__in LPCWSTR lpLocaleName, __in DWORD dwMapFlags) else iRetVal = FastLastIndexOfStringInsensitive(pString1, cchCount1, pString2, cchCount2); comparedOrdinal = TRUE; + + foundLengthInSource = cchCount2; goto lExit; } } @@ -944,6 +938,7 @@ inline BOOL IsInvariantCasing(__in LPCWSTR lpLocaleName, __in DWORD dwMapFlags) if (NewApis::CompareStringEx(lpLocaleName, dwFlags, pString2, cchCount2, &pString1[cchCount1 + iOffset - iLength], iLength, NULL, NULL, 0) == CSTR_EQUAL) { iRetVal= cchCount1 + iOffset - iLength; + foundLengthInSource = iLength; break; } } @@ -961,6 +956,9 @@ inline BOOL IsInvariantCasing(__in LPCWSTR lpLocaleName, __in DWORD dwMapFlags) iRetVal = -1; } } + + if(iRetVal != -1 && pcchFound != NULL) + *pcchFound = foundLengthInSource; return iRetVal; } @@ -1094,9 +1092,7 @@ inline BOOL IsInvariantCasing(__in LPCWSTR lpLocaleName, __in DWORD dwMapFlags) retVal = ::LCIDToLocaleName(Locale, lpName, cchName, dwFlags | LOCALE_ALLOW_NEUTRAL_NAMES); #else -#ifdef FEATURE_CORECLR retVal = DownLevel::LCIDToLocaleName(Locale, lpName,cchName,dwFlags | LOCALE_ALLOW_NEUTRAL_NAMES); -#endif // FEATURE_CORECLR typedef int (WINAPI *PFNLCIDToLocaleName)(LCID, LPWSTR,int ,DWORD); static PFNLCIDToLocaleName pFNLCIDToLocaleName=NULL; @@ -1138,9 +1134,7 @@ inline BOOL IsInvariantCasing(__in LPCWSTR lpLocaleName, __in DWORD dwMapFlags) #if !defined(ENABLE_DOWNLEVEL_FOR_NLS) return ::LocaleNameToLCID(lpName, dwFlags | LOCALE_ALLOW_NEUTRAL_NAMES); #else -#ifdef FEATURE_CORECLR retVal = DownLevel::LocaleNameToLCID(lpName, dwFlags | LOCALE_ALLOW_NEUTRAL_NAMES); -#endif // FEATURE_CORECLR typedef int (WINAPI *PFNLocaleNameToLCID)(LPCWSTR,DWORD); static PFNLocaleNameToLCID pFNLocaleNameToLCID=NULL; @@ -1278,26 +1272,6 @@ inline BOOL IsInvariantCasing(__in LPCWSTR lpLocaleName, __in DWORD dwMapFlags) } -#if !defined(FEATURE_CORECLR) - BOOL GetNlsVersionEx(__in NLS_FUNCTION Function, __in LPCWSTR lpLocaleName, __inout LPNLSVERSIONINFOEX lpVersionInfo) - { - - typedef BOOL (WINAPI *PFNGetNLSVersionEx)(NLS_FUNCTION, LPCWSTR, LPNLSVERSIONINFOEX); - - static PFNGetNLSVersionEx pFNGetNLSVersionEx=NULL; - - // See if we still need to find our function - if (pFNGetNLSVersionEx == NULL) - { - // We only call this on Win8 and above, so this should always work. - pFNGetNLSVersionEx = (PFNGetNLSVersionEx) GetSystemProcAddressForSortingApi("GetNLSVersionEx", NULL); - } - - _ASSERTE(pFNGetNLSVersionEx != NULL); - - return pFNGetNLSVersionEx(Function, lpLocaleName, lpVersionInfo); - } -#endif // This is a Windows 7 and above function // This returns the "specific" locale from an input name, ie: "en" returns "en-US", diff --git a/src/utilcode/pedecoder.cpp b/src/utilcode/pedecoder.cpp index c437c21c35..79fe244bda 100644 --- a/src/utilcode/pedecoder.cpp +++ b/src/utilcode/pedecoder.cpp @@ -34,7 +34,7 @@ CHECK PEDecoder::CheckFormat() const { CHECK(CheckCorHeader()); -#if !defined(FEATURE_MIXEDMODE) && !defined(FEATURE_PREJIT) +#if !defined(FEATURE_PREJIT) CHECK(IsILOnly()); #endif @@ -1075,8 +1075,8 @@ CHECK PEDecoder::CheckCorHeader() const if (IsStrongNameSigned()) CHECK(HasStrongNameSignature()); - // IL library files (really a misnomer - these are native images) only - // may have a native image header + // IL library files (really a misnomer - these are native images or ReadyToRun images) + // only they can have a native image header if ((pCor->Flags&VAL32(COMIMAGE_FLAGS_IL_LIBRARY)) == 0) { CHECK(VAL32(pCor->ManagedNativeHeader.Size) == 0); @@ -1173,12 +1173,6 @@ CHECK PEDecoder::CheckCorHeader() const CHECK_OK; } -#if !defined(FEATURE_CORECLR) -#define WHIDBEY_SP2_VERSION_MAJOR 2 -#define WHIDBEY_SP2_VERSION_MINOR 0 -#define WHIDBEY_SP2_VERSION_BUILD 50727 -#define WHIDBEY_SP2_VERSION_PRIVATE_BUILD 3053 -#endif // !defined(FEATURE_CORECLR) // This function exists to provide compatibility between two different native image @@ -1236,71 +1230,10 @@ IMAGE_DATA_DIRECTORY *PEDecoder::GetMetaDataHelper(METADATA_SECTION_TYPE type) c // COR_HEADER and so the value of pDirRet is correct if (HasNativeHeader()) { -#ifdef FEATURE_CORECLR if (type == METADATA_SECTION_MANIFEST) pDirRet = &GetNativeHeader()->ManifestMetaData; -#else // FEATURE_CORECLR - - IMAGE_DATA_DIRECTORY *pDirNativeHeader = &GetNativeHeader()->ManifestMetaData; - - // This code leverages the fact that pre-Whidbey SP2 private build numbers can never - // be greater than Whidbey SP2 private build number, because otherwise major setup - // issues would arise. To prevent this, it is standard to bump the private build - // number up a significant amount for SPs, as was the case between Whidbey SP1 and - // Whidbey SP2. - // - // Since we could be reading an older version of native image, we tell - // GetNativeVersionInfoMaybeNull to skip checking the native header. - CORCOMPILE_VERSION_INFO *pVerInfo = GetNativeVersionInfoMaybeNull(true); - bool fIsPreWhidbeySP2 = false; - - // If pVerInfo is NULL, we assume that we're in an NGEN compilation domain and that - // the information has not yet been written. Since an NGEN compilation domain running - // in the v4.0 runtime can only complie v4.0 native images, we'll assume the default - // fIsPreWhidbeySP2 value (false) is correct. - if (pVerInfo != NULL && pVerInfo->wVersionMajor <= WHIDBEY_SP2_VERSION_MAJOR) - { - if (pVerInfo->wVersionMajor < WHIDBEY_SP2_VERSION_MAJOR) - fIsPreWhidbeySP2 = true; - else if (pVerInfo->wVersionMajor == WHIDBEY_SP2_VERSION_MAJOR) - { - // If the sp2 minor version isn't 0, we need this logic: - // if (pVerInfo->wVersionMinor < WHIDBEY_SP2_VERSION_MINOR) - // fIsPreWhidbeySP2 = true; - // else - // However, if it is zero, with that logic we get a warning about the comparison - // of an unsigned variable to zero always being false. - _ASSERTE(WHIDBEY_SP2_VERSION_MINOR == 0); - - if (pVerInfo->wVersionMinor == WHIDBEY_SP2_VERSION_MINOR) - { - if (pVerInfo->wVersionBuildNumber < WHIDBEY_SP2_VERSION_BUILD) - fIsPreWhidbeySP2 = true; - else if (pVerInfo->wVersionBuildNumber == WHIDBEY_SP2_VERSION_BUILD) - { - if (pVerInfo->wVersionPrivateBuildNumber < WHIDBEY_SP2_VERSION_PRIVATE_BUILD) - fIsPreWhidbeySP2 = true; - } - } - } - } - - // In pre-Whidbey SP2, pDirRet points to manifest and pDirNativeHeader points to full. - if (fIsPreWhidbeySP2) - { - if (type == METADATA_SECTION_FULL) - pDirRet = pDirNativeHeader; - } - // In Whidbey SP2 and later, pDirRet points to full and pDirNativeHeader points to manifest. - else - { - if (type == METADATA_SECTION_MANIFEST) - pDirRet = pDirNativeHeader; - } - -#endif // FEATURE_CORECLR } @@ -1896,7 +1829,7 @@ BOOL PEDecoder::HasNativeHeader() const #ifdef FEATURE_PREJIT // Pretend that ready-to-run images do not have native header - RETURN (((GetCorHeader()->Flags & VAL32(COMIMAGE_FLAGS_IL_LIBRARY)) != 0) && !HasReadyToRunHeader()); + RETURN (GetCorHeader() && ((GetCorHeader()->Flags & VAL32(COMIMAGE_FLAGS_IL_LIBRARY)) != 0) && !HasReadyToRunHeader()); #else RETURN FALSE; #endif diff --git a/src/utilcode/peinformation.cpp b/src/utilcode/peinformation.cpp index 948948a4da..20a9fe18b0 100644 --- a/src/utilcode/peinformation.cpp +++ b/src/utilcode/peinformation.cpp @@ -11,100 +11,6 @@ #include "utilcode.h" #include "peinformation.h" -#if defined(FEATURE_FUSION) && !defined(DACCESS_COMPILE) - -extern BOOL g_fWow64Process; // Wow64 Process - -PEKIND GetCurrentRealProcessorPEKIND() -{ - PEKIND curProcessorPEKind = TargetNativePEKIND(); - -#ifdef _TARGET_X86_ - if (g_fWow64Process) - { - SYSTEM_INFO si = {0}; - - GetNativeSystemInfo(&si); - switch (si.wProcessorArchitecture) - { - case PROCESSOR_ARCHITECTURE_AMD64: - curProcessorPEKind = peAMD64; - break; - default: - _ASSERTE(FALSE); - curProcessorPEKind = peInvalid; - break; - } - } -#endif // _TARGET_X86_ - - return curProcessorPEKind; -} - -HRESULT RuntimeIsValidAssemblyOnThisPlatform_CheckProcessorArchitecture(PEKIND processorArchitecture, BOOL bForInstall) -{ - LIMITED_METHOD_CONTRACT; - - HRESULT hr = S_OK; - - // MSIL / legacy images always allowed - if (IsPEMSIL(processorArchitecture) || (processorArchitecture == peNone)) - { - goto Exit; - } - else if (IsPE32(processorArchitecture)) - { -#ifdef _TARGET_ARM_ - // ARM can use only native ones - if (processorArchitecture != TargetNativePEKIND()) - { - hr = HRESULT_FROM_WIN32(ERROR_BAD_FORMAT); - goto Exit; - } - -#else //!_TARGET_ARM_ - //ARM assemblies can be installed only on ARM - if (processorArchitecture == peARM) - { - hr = HRESULT_FROM_WIN32(ERROR_BAD_FORMAT); - goto Exit; - } -#endif //!_TARGET_ARM_ - - if (bForInstall) - { - goto Exit; - } - else - { - // won't allow bind to x86 while in 64 bit process. - if (!IsProcess32()) - { - hr = HRESULT_FROM_WIN32(ERROR_BAD_FORMAT); - } - goto Exit; - } - } - // 64 bit images must match processor type - else if(IsPE64(processorArchitecture)) - { - if (!IsProcess32() && (processorArchitecture == TargetNativePEKIND())) - { - goto Exit; - } - else if (bForInstall && (GetCurrentRealProcessorPEKIND() == processorArchitecture)) - { - goto Exit; - } - } - - // Everything else, fails match - hr = HRESULT_FROM_WIN32(ERROR_BAD_FORMAT); - -Exit: - return hr; -} -#endif // FEATURE_FUSION && !DACCESS_COMPILE HRESULT TranslatePEToArchitectureType(CorPEKind CLRPeKind, DWORD dwImageType, PEKIND * pPeKind) { diff --git a/src/utilcode/prettyprintsig.cpp b/src/utilcode/prettyprintsig.cpp index 7e9028ddab..fc0844ce4a 100644 --- a/src/utilcode/prettyprintsig.cpp +++ b/src/utilcode/prettyprintsig.cpp @@ -167,7 +167,7 @@ LPCWSTR PrettyPrintSigWorker( //***************************************************************************** //***************************************************************************** -// pretty prints 'type' to the buffer 'out' returns a poitner to the next type, +// pretty prints 'type' to the buffer 'out' returns a pointer to the next type, // or 0 on a format failure static PCCOR_SIGNATURE PrettyPrintType( @@ -562,7 +562,7 @@ HRESULT PrettyPrintSigWorkerInternal( #endif //***************************************************************************** //***************************************************************************** -// pretty prints 'type' to the buffer 'out' returns a poitner to the next type, +// pretty prints 'type' to the buffer 'out' returns a pointer to the next type, // or 0 on a format failure __checkReturn diff --git a/src/utilcode/registrywrapper.cpp b/src/utilcode/registrywrapper.cpp index f6b88db977..b3c4b42946 100644 --- a/src/utilcode/registrywrapper.cpp +++ b/src/utilcode/registrywrapper.cpp @@ -74,288 +74,3 @@ #include "clrconfig.h" #include "strsafe.h" -#if !defined(FEATURE_UTILCODE_NO_DEPENDENCIES) && !defined(FEATURE_CORECLR) - -static LPCWSTR kRegistryRootKey = W("SOFTWARE\\"); -static const HKEY kRegistryRootHive = HKEY_LOCAL_MACHINE; -static LPCWSTR kWow6432Node = W("Wow6432Node\\"); -static LPCWSTR kMicrosoftDotNetFrameworkPolicy = W("Microsoft\\.NETFramework\\Policy"); -static LPCWSTR wszHKLM = W("HKLM\\"); -static WCHAR * g_registryRoot = NULL; -static volatile bool g_initialized = false; -static const WCHAR BACKSLASH_CHARACTER[] = W("\\"); - -// -// Called the first time we use ClrRegCreateKeyEx or ClrRegOpenKeyEx to determine if the registry redirection -// config value has been set. If so, we parse it into g_registryRoot -// If the config string is mal-formed, we don't set the global variable. -// -HRESULT ParseRegistryRootConfigValue() -{ - if (!IsNgenOffline()) - { - return ERROR_SUCCESS; - } - - CLRConfigStringHolder configValue(CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_RegistryRoot)); - // Since IsNgenOffline returned true, this better not be NULL - if (configValue == NULL) - return ERROR_BAD_ARGUMENTS; - - if (_wcsnicmp(configValue, wszHKLM, wcslen(wszHKLM)) != 0) - { - return ERROR_BAD_ARGUMENTS; - } - - // The rest of the string is the location of the redirected registry key - LPWSTR configValueKey = (LPWSTR)configValue; - configValueKey = _wcsninc(configValueKey, wcslen(wszHKLM)); - - size_t len = wcslen(configValueKey) + 1; - - bool appendBackslash = false; - if (configValueKey[wcslen(configValueKey) - 1] != W('\\')) - { - appendBackslash = true; - len += wcslen(BACKSLASH_CHARACTER); - } - g_registryRoot = new (nothrow) WCHAR[len]; - - if (g_registryRoot == NULL) - { - return ERROR_NOT_ENOUGH_MEMORY; - } - - wcscpy_s(g_registryRoot, len, configValueKey); - if (appendBackslash) - { - StringCchCat(g_registryRoot, len, BACKSLASH_CHARACTER); - } - - return ERROR_SUCCESS; -} - -// -// This is our check that the target machine is 32/64bit -// If 32bit only, there will be no Wow6432Node key -// If 64bit, there will be a Wow6432Node key -// -HRESULT CheckWow6432NodeNetFxExists(bool * fResult) -{ - static bool bInitialized = false; - static bool bNodeExists = false; - HRESULT hr = ERROR_SUCCESS; - - if (!bInitialized) - { - size_t redirectedLength = wcslen(g_registryRoot) + wcslen(kWow6432Node) + wcslen(kMicrosoftDotNetFrameworkPolicy) + 1; - LPWSTR lpRedirectedKey = new (nothrow) WCHAR[redirectedLength]; - - if (lpRedirectedKey == NULL) - { - return ERROR_NOT_ENOUGH_MEMORY; - } - - wcscpy_s(lpRedirectedKey, redirectedLength, g_registryRoot); - StringCchCat(lpRedirectedKey, redirectedLength, kWow6432Node); - StringCchCat(lpRedirectedKey, redirectedLength, kMicrosoftDotNetFrameworkPolicy); - - HKEY hkey; - hr = RegOpenKeyExW(HKEY_LOCAL_MACHINE, lpRedirectedKey, 0, KEY_READ, &hkey); - bNodeExists = hr == ERROR_SUCCESS; - - if (hr == ERROR_FILE_NOT_FOUND) - { - hr = ERROR_SUCCESS; - } - - if (hkey) - { - RegCloseKey(hkey); - } - bInitialized = true; - } - *fResult = bNodeExists; - return hr; -} - -HRESULT CheckUseWow6432Node(REGSAM samDesired, bool * fResult) -{ - HRESULT hr = ERROR_SUCCESS; - bool fWow6432NodeExists = false; - - hr = CheckWow6432NodeNetFxExists(&fWow6432NodeExists); - if (hr == ERROR_SUCCESS) - { - if (!fWow6432NodeExists) - { - *fResult = false; - } else - { -#if defined(_WIN64) - *fResult = false; -#else - *fResult = true; -#endif - // If KEY_WOW64_64KEY or KEY_WOW64_32KEY are set, override - // If both are set, the actual registry call will fail with ERROR_INVALID_PARAMETER - // so no worries here - if (samDesired & KEY_WOW64_64KEY) - { - *fResult = false; - } else if (samDesired & KEY_WOW64_32KEY) - { - *fResult = true; - } - } - } - return hr; -} - -// -// lpRedirectedKey is allocated and returned from this method. Caller owns the new string and -// should release -// -__success(return == ERROR_SUCCESS) -HRESULT RedirectKey(REGSAM samDesired, HKEY hKey, LPCWSTR lpKey, __deref_out_z LPWSTR * lpRedirectedKey) -{ - if (hKey != kRegistryRootHive || _wcsnicmp(lpKey, kRegistryRootKey, wcslen(kRegistryRootKey)) != 0) - { - *lpRedirectedKey = NULL; - return ERROR_SUCCESS; - } - - LPCWSTR lpRootStrippedKey = lpKey + wcslen(kRegistryRootKey); - size_t redirectedLength = wcslen(g_registryRoot) + wcslen(lpRootStrippedKey) + 1; - - bool bUseWow = false; - HRESULT hr = CheckUseWow6432Node(samDesired, &bUseWow); - - if (hr != ERROR_SUCCESS) - { - return hr; - } - - if (bUseWow) - { - redirectedLength += wcslen(kWow6432Node); - } - - *lpRedirectedKey = new (nothrow) WCHAR[redirectedLength]; - - if (*lpRedirectedKey == NULL) - { - return ERROR_NOT_ENOUGH_MEMORY; - } - - wcscpy_s(*lpRedirectedKey, redirectedLength, g_registryRoot); - if (bUseWow) - { - StringCchCat(*lpRedirectedKey, redirectedLength, kWow6432Node); - } - - StringCchCat(*lpRedirectedKey, redirectedLength, lpRootStrippedKey); - - return ERROR_SUCCESS; -} - -LONG ClrRegCreateKeyEx( - HKEY hKey, - LPCWSTR lpSubKey, - DWORD Reserved, - __in_opt LPWSTR lpClass, - DWORD dwOptions, - REGSAM samDesired, - LPSECURITY_ATTRIBUTES lpSecurityAttributes, - PHKEY phkResult, - LPDWORD lpdwDisposition - ) -{ - HRESULT hr; - if (!g_initialized) - { - hr = ParseRegistryRootConfigValue(); - if (hr != ERROR_SUCCESS) - return hr; - g_initialized = true; - } - - if (g_registryRoot != NULL) - { - NewArrayHolder<WCHAR> lpRedirectedKey(NULL); - hr = RedirectKey(samDesired, hKey, lpSubKey, &lpRedirectedKey); - // We don't want to touch the registry if we're low on memory and can't redirect properly. It could lead - // to use reading and writing to two separate registries and corrupting both in the process - if (hr != ERROR_SUCCESS) - return hr; - LPCWSTR lpKeyToUse = lpRedirectedKey == NULL ? lpSubKey : lpRedirectedKey; - return RegCreateKeyExW(hKey, lpKeyToUse, Reserved, lpClass, dwOptions, samDesired, lpSecurityAttributes, phkResult, lpdwDisposition); - } - return RegCreateKeyExW(hKey, lpSubKey, Reserved, lpClass, dwOptions, samDesired, lpSecurityAttributes, phkResult, lpdwDisposition); -} // ClrRegCreateKeyEx - -LONG ClrRegOpenKeyEx( - HKEY hKey, - LPCWSTR lpSubKey, - DWORD ulOptions, - REGSAM samDesired, - PHKEY phkResult - ) -{ - HRESULT hr; - if (!g_initialized) - { - hr = ParseRegistryRootConfigValue(); - if (hr != ERROR_SUCCESS) - return hr; - g_initialized = true; - } - - if (g_registryRoot != NULL) - { - NewArrayHolder<WCHAR> lpRedirectedKey(NULL); - hr = RedirectKey(samDesired, hKey, lpSubKey, &lpRedirectedKey); - // We don't want to touch the registry if we're low on memory and can't redirect properly. It could lead - // to use reading and writing to two separate registries and corrupting both in the process - if (hr != ERROR_SUCCESS) - return hr; - LPCWSTR lpKeyToUse = lpRedirectedKey == NULL ? lpSubKey : lpRedirectedKey; - return RegOpenKeyExW(hKey, lpKeyToUse, ulOptions, samDesired, phkResult); - } - return RegOpenKeyExW(hKey, lpSubKey, ulOptions, samDesired, phkResult); -} - -// -// Determine whether we're running Offline Ngen for Build Lab based on the settings of several Config Values. -// -bool IsNgenOffline() -{ - static volatile bool fInitialized = false; - static volatile bool fNgenOffline = false; - - if (!fInitialized) - { - REGUTIL::CORConfigLevel kCorConfigLevel = static_cast<REGUTIL::CORConfigLevel>(REGUTIL::COR_CONFIG_ENV); - CLRConfigStringHolder pwzConfigInstallRoot = REGUTIL::GetConfigString_DontUse_(CLRConfig::INTERNAL_InstallRoot, - TRUE /* Prepend Complus */, - kCorConfigLevel, - FALSE /* fUsePerfCache */); - CLRConfigStringHolder pwzConfigNicPath(CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_NicPath)); - CLRConfigStringHolder pwzRegistryRoot(CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_RegistryRoot)); - CLRConfigStringHolder pwzConfigAssemblyPath(CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_AssemblyPath)); - CLRConfigStringHolder pwzConfigAssemblyPath2(CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_AssemblyPath2)); - if (pwzConfigInstallRoot != NULL && - pwzConfigNicPath != NULL && - pwzConfigAssemblyPath != NULL && - pwzConfigAssemblyPath2 != NULL && - pwzRegistryRoot != NULL) - { - fNgenOffline = true; - } - fInitialized = true; - } - - return fNgenOffline; -} - -#endif //!FEATURE_UTILCODE_NO_DEPENDENCIES && !FEATURE_CORECLR diff --git a/src/utilcode/regutil.cpp b/src/utilcode/regutil.cpp index d611ef965f..c38c38907a 100644 --- a/src/utilcode/regutil.cpp +++ b/src/utilcode/regutil.cpp @@ -111,19 +111,6 @@ LPWSTR REGUTIL::EnvGetString(LPCWSTR name, BOOL fPrependCOMPLUS) #ifdef ALLOW_REGISTRY -#ifndef FEATURE_CORECLR - -//***************************************************************************** -// Gives the use the ability to turn on/off REGUTIL's ability to read from -// the registry. This is useful in mscoree.dll on startup, in order to avoid -// loading advapi32 and rpcrt4 until we're ready for them -//***************************************************************************** -void REGUTIL::AllowRegistryUse(BOOL fAllowUse) -{ - s_fUseRegistry = fAllowUse; -}// AllowRegistryUse - -#endif // !FEATURE_CORECLR #endif // ALLOW_REGISTRY @@ -522,690 +509,6 @@ DWORD REGUTIL::GetConfigFlag_DontUse_(LPCWSTR name, DWORD bitToSet, BOOL defValu #ifdef ALLOW_REGISTRY -#ifndef FEATURE_CORECLR - -//***************************************************************************** -// Open's the given key and returns the value desired. If the key or value is -// not found, then the default is returned. -//***************************************************************************** -long REGUTIL::GetLong( // Return value from registry or default. - LPCTSTR szName, // Name of value to get. - long iDefault, // Default value to return if not found. - LPCTSTR szKey, // Name of key, NULL==default. - HKEY hKeyVal) // What key to work on. -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - FORBID_FAULT; - SO_TOLERANT; - } - CONTRACTL_END; - - long iValue; // The value to read. - DWORD iType; // Type of value to get. - DWORD iSize; // Size of buffer. - HKEY hKey; // Key for the registry entry. - - _ASSERTE(UseRegistry()); - - FAULT_NOT_FATAL(); // We don't report OOM errors here, we return a default value. - - // Open the key if it is there. - if (ERROR_SUCCESS != WszRegOpenKeyEx(hKeyVal, (szKey) ? szKey : FRAMEWORK_REGISTRY_KEY_W, 0, KEY_READ, &hKey)) - return (iDefault); - - // Read the key value if found. - iType = REG_DWORD; - iSize = sizeof(long); - if (ERROR_SUCCESS != WszRegQueryValueEx(hKey, szName, NULL, - &iType, (LPBYTE)&iValue, &iSize) || iType != REG_DWORD) - iValue = iDefault; - - // We're done with the key now. - VERIFY(!RegCloseKey(hKey)); - return (iValue); -} - - -// Opens or creates desired reg key, then writes iValue -//***************************************************************************** -long REGUTIL::SetOrCreateLong( // Return value from registry or default. - LPCTSTR szName, // Name of value to get. - long iValue, // Value to set. - LPCTSTR szKey, // Name of key, NULL==default. - HKEY hKeyVal) // What key to work on. -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - } - CONTRACTL_END; - - _ASSERTE(UseRegistry()); - - long lRtn; // Return code. - HKEY hKey; // Key for the registry entry. - - - // Open the key if it is there, else create it - if (WszRegCreateKeyEx(hKeyVal, - (szKey) ? szKey : FRAMEWORK_REGISTRY_KEY_W, - 0, - NULL, - REG_OPTION_NON_VOLATILE, - KEY_WRITE, - NULL, - &hKey, - NULL) != ERROR_SUCCESS) - { - return (-1); - } - - // Read the key value if found. - lRtn = WszRegSetValueEx(hKey, szName, NULL, REG_DWORD, (const BYTE *) &iValue, sizeof(DWORD)); - - // We're done with the key now. - VERIFY(!RegCloseKey(hKey)); - return (lRtn); -} - - -//***************************************************************************** -// Open's the given key and returns the value desired. If the key or value is -// not found, then the default is returned. -//***************************************************************************** -long REGUTIL::SetLong( // Return value from registry or default. - LPCTSTR szName, // Name of value to get. - long iValue, // Value to set. - LPCTSTR szKey, // Name of key, NULL==default. - HKEY hKeyVal) // What key to work on. -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - } - CONTRACTL_END; - - _ASSERTE(UseRegistry()); - - long lRtn; // Return code. - HKEY hKey; // Key for the registry entry. - - // Open the key if it is there. - if (ERROR_SUCCESS != WszRegOpenKey(hKeyVal, (szKey) ? szKey : FRAMEWORK_REGISTRY_KEY_W, &hKey)) - return (-1); - - // Read the key value if found. - lRtn = WszRegSetValueEx(hKey, szName, NULL, REG_DWORD, (const BYTE *) &iValue, sizeof(DWORD)); - - // We're done with the key now. - VERIFY(!RegCloseKey(hKey)); - return (lRtn); -} - -//***************************************************************************** -// Set an entry in the registry of the form: -// HKEY_CLASSES_ROOT\szKey\szSubkey = szValue. If szSubkey or szValue are -// NULL, omit them from the above expression. -//***************************************************************************** -BOOL REGUTIL::SetKeyAndValue( // TRUE or FALSE. - LPCTSTR szKey, // Name of the reg key to set. - LPCTSTR szSubkey, // Optional subkey of szKey. - LPCTSTR szValue) // Optional value for szKey\szSubkey. -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - } - CONTRACTL_END; - - _ASSERTE(UseRegistry()); - - size_t nLen = _tcslen(szKey) + 1; - if (szSubkey) - nLen += (_tcslen(szSubkey) + 1); - - NewArrayHolder<TCHAR> rcKey = new (nothrow) TCHAR[nLen]; // Buffer for the full key name. - if (rcKey == NULL) - return FALSE; - - HKEY hKey = NULL; // Handle to the new reg key. - - // Init the key with the base key name. - _tcscpy_s(rcKey, nLen, szKey); - - // Append the subkey name (if there is one). - if (szSubkey != NULL) - { - _tcscat_s(rcKey, nLen, _T("\\")); - _tcscat_s(rcKey, nLen, szSubkey); - } - - // Create the registration key. - if (WszRegCreateKeyEx(HKEY_CLASSES_ROOT, rcKey, 0, NULL, - REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, - &hKey, NULL) != ERROR_SUCCESS) - return(FALSE); - - // Set the value (if there is one). - if (szValue != NULL) - if( WszRegSetValueEx(hKey, NULL, 0, REG_SZ, (BYTE *) szValue, - (Wszlstrlen(szValue)+1) * sizeof(TCHAR)) != ERROR_SUCCESS ) { - VERIFY(!RegCloseKey(hKey)); - return(FALSE); - } - - VERIFY(!RegCloseKey(hKey)); - return(TRUE); -} - - -//***************************************************************************** -// Delete an entry in the registry of the form: -// HKEY_CLASSES_ROOT\szKey\szSubkey. -//***************************************************************************** -LONG REGUTIL::DeleteKey( // TRUE or FALSE. - LPCTSTR szKey, // Name of the reg key to set. - LPCTSTR szSubkey) // Subkey of szKey. -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - } - CONTRACTL_END; - - _ASSERTE(UseRegistry()); - - size_t nLen = _tcslen(szKey) + 1; - if (szSubkey) - nLen += (_tcslen(szSubkey) + 1); - - NewArrayHolder<TCHAR> rcKey = new (nothrow) TCHAR[nLen]; // Buffer for the full key name. - if (rcKey == NULL) - return ERROR_NOT_ENOUGH_MEMORY; - - // Init the key with the base key name. - _tcscpy_s(rcKey, nLen, szKey); - - // Append the subkey name (if there is one). - if (szSubkey != NULL) - { - _tcscat_s(rcKey, nLen, _T("\\")); - _tcscat_s(rcKey, nLen, szSubkey); - } - - // Delete the registration key. - return WszRegDeleteKey(HKEY_CLASSES_ROOT, rcKey); -} - - -//***************************************************************************** -// Open the key, create a new keyword and value pair under it. -//***************************************************************************** -BOOL REGUTIL::SetRegValue( // Return status. - LPCTSTR szKeyName, // Name of full key. - LPCTSTR szKeyword, // Name of keyword. - LPCTSTR szValue) // Value of keyword. -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - } - CONTRACTL_END; - - _ASSERTE(UseRegistry()); - - HKEY hKey; // Handle to the new reg key. - - // Create the registration key. - if (WszRegCreateKeyEx(HKEY_CLASSES_ROOT, szKeyName, 0, NULL, - REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, - &hKey, NULL) != ERROR_SUCCESS) - return (FALSE); - - // Set the value (if there is one). - if (szValue != NULL) - if( WszRegSetValueEx(hKey, szKeyword, 0, REG_SZ, (BYTE *)szValue, - (Wszlstrlen(szValue)+1) * sizeof(TCHAR)) != ERROR_SUCCESS) { - VERIFY(!RegCloseKey(hKey)); - return(FALSE); - } - - VERIFY(!RegCloseKey(hKey)); - return (TRUE); -} - - -//***************************************************************************** -// Does standard registration of a CoClass with a progid. -//***************************************************************************** -HRESULT REGUTIL::RegisterCOMClass( // Return code. - REFCLSID rclsid, // Class ID. - LPCTSTR szDesc, // Description of the class. - LPCTSTR szProgIDPrefix, // Prefix for progid. - int iVersion, // Version # for progid. - LPCTSTR szClassProgID, // Class progid. - LPCTSTR szThreadingModel, // What threading model to use. - LPCTSTR szModule, // Path to class. - HINSTANCE hInst, // Handle to module being registered - LPCTSTR szAssemblyName, // Optional Assembly, - LPCTSTR szVersion, // Optional Runtime version (directory containing runtime) - BOOL fExternal, // flag - External to mscoree. - BOOL fRelativePath) // flag - Relative path in szModule -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - } - CONTRACTL_END; - - WCHAR rcCLSID[256]; // CLSID\\szID. - WCHAR rcInproc[_MAX_PATH+64]; // CLSID\\InprocServer32 - WCHAR rcProgID[256]; // szProgIDPrefix.szClassProgID - WCHAR rcIndProgID[256]; // rcProgID.iVersion - WCHAR rcShim[_MAX_PATH]; - HRESULT hr; - - // Format the prog ID values. - VERIFY(_snwprintf_s(rcIndProgID, _countof(rcIndProgID), _TRUNCATE, W("%s.%s"), szProgIDPrefix, szClassProgID)); - - VERIFY(_snwprintf_s(rcProgID, _countof(rcProgID), _TRUNCATE, W("%s.%d"), rcIndProgID, iVersion)); - - // Do the initial portion. - if (FAILED(hr = RegisterClassBase(rclsid, szDesc, rcProgID, rcIndProgID, rcCLSID, NumItems(rcCLSID)))) - return (hr); - - VERIFY(_snwprintf_s(rcInproc, _countof(rcInproc), _TRUNCATE, W("%s\\%s"), rcCLSID, W("InprocServer32"))); - - if (!fExternal){ - SetKeyAndValue(rcCLSID, W("InprocServer32"), szModule); - } - else{ - LPCTSTR pSep = szModule; - if (!fRelativePath && szModule) { - pSep = wcsrchr(szModule, W('\\')); - if(pSep == NULL) - pSep = szModule; - else - pSep++; - } - HMODULE hMod = WszLoadLibrary(W("mscoree.dll")); - if (!hMod) - return E_FAIL; - - DWORD ret; - VERIFY(ret = WszGetModuleFileName(hMod, rcShim, NumItems(rcShim))); - FreeLibrary(hMod); - if( !ret ) - return E_FAIL; - - // Set the server path. - SetKeyAndValue(rcCLSID, W("InprocServer32"), rcShim); - if(pSep) - SetKeyAndValue(rcCLSID, W("Server"), pSep); - - if(szAssemblyName) { - SetRegValue(rcInproc, W("Assembly"), szAssemblyName); - SetRegValue(rcInproc, W("Class"), rcIndProgID); - } - } - - // Set the runtime version, it needs to be passed in from the outside - if(szVersion != NULL) { - LPCTSTR pSep2 = NULL; - LPTSTR pSep1 = const_cast<LPTSTR>(wcsrchr(szVersion, W('\\'))); - if(pSep1 != NULL) { - *pSep1 = '\0'; - pSep2 = wcsrchr(szVersion, W('\\')); - if (!pSep2) - pSep2 = szVersion; - else - pSep2 = pSep2++; // exclude '\\' - } - else - pSep2 = szVersion; - - size_t bufLen = wcslen(rcInproc)+wcslen(pSep2)+2; - WCHAR* rcVersion = new (nothrow) WCHAR[bufLen]; - if(rcVersion==NULL) - return (E_OUTOFMEMORY); - wcscpy_s(rcVersion, bufLen, rcInproc); - wcscat_s(rcVersion, bufLen, W("\\")); - wcscat_s(rcVersion, bufLen, pSep2); - SetRegValue(rcVersion, W("ImplementedInThisVersion"), W("")); - delete[] rcVersion; - - if(pSep1 != NULL) - *pSep1 = W('\\'); - } - - // Add the threading model information. - SetRegValue(rcInproc, W("ThreadingModel"), szThreadingModel); - return (S_OK); -} - - - -//***************************************************************************** -// Does standard registration of a CoClass with a progid. -// NOTE: This is the non-side-by-side execution version. -//***************************************************************************** -HRESULT REGUTIL::RegisterCOMClass( // Return code. - REFCLSID rclsid, // Class ID. - LPCTSTR szDesc, // Description of the class. - LPCTSTR szProgIDPrefix, // Prefix for progid. - int iVersion, // Version # for progid. - LPCTSTR szClassProgID, // Class progid. - LPCTSTR szThreadingModel, // What threading model to use. - LPCTSTR szModule, // Path to class. - BOOL bInprocServer) // Whether we register the server as inproc or local -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - } - CONTRACTL_END; - - WCHAR rcCLSID[256]; // CLSID\\szID. - WCHAR rcInproc[_MAX_PATH+64]; // CLSID\\InprocServer32 - WCHAR rcProgID[256]; // szProgIDPrefix.szClassProgID - WCHAR rcIndProgID[256]; // rcProgID.iVersion - HRESULT hr; - - // Format the prog ID values. - VERIFY(_snwprintf_s(rcIndProgID, _countof(rcIndProgID), _TRUNCATE, W("%s.%s"), szProgIDPrefix, szClassProgID)); - - VERIFY(_snwprintf_s(rcProgID, _countof(rcProgID), _TRUNCATE, W("%s.%d"), rcIndProgID, iVersion)); - - // Do the initial portion. - if (FAILED(hr = RegisterClassBase(rclsid, szDesc, rcProgID, rcIndProgID, rcCLSID, NumItems(rcCLSID)))) - return (hr); - - WCHAR *szServerType = bInprocServer ? W("InprocServer32") : W("LocalServer32"); - - // Set the server path. - SetKeyAndValue(rcCLSID, szServerType , szModule); - - // Add the threading model information. - VERIFY(_snwprintf_s(rcInproc, _countof(rcInproc), _TRUNCATE, W("%s\\%s"), rcCLSID, szServerType)); - - SetRegValue(rcInproc, W("ThreadingModel"), szThreadingModel); - return (S_OK); -} - - - -//***************************************************************************** -// Register the basics for a in proc server. -//***************************************************************************** -HRESULT REGUTIL::RegisterClassBase( // Return code. - REFCLSID rclsid, // Class ID we are registering. - LPCTSTR szDesc, // Class description. - LPCTSTR szProgID, // Class prog ID. - LPCTSTR szIndepProgID, // Class version independant prog ID. - __out_ecount(cchOutCLSID) LPTSTR szOutCLSID, // CLSID formatted in character form. - DWORD cchOutCLSID) // Out CLS ID buffer size -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - } - CONTRACTL_END; - - TCHAR szID[64]; // The class ID to register. - - // Create some base key strings. - GuidToLPWSTR(rclsid, szID, NumItems(szID)); - - size_t nLen = _tcslen(_T("CLSID\\")) + _tcslen( szID) + 1; - if( cchOutCLSID < nLen ) - return E_INVALIDARG; - - _tcscpy_s(szOutCLSID, cchOutCLSID, W("CLSID\\")); - _tcscat_s(szOutCLSID, cchOutCLSID, szID); - - // Create ProgID keys. - SetKeyAndValue(szProgID, NULL, szDesc); - SetKeyAndValue(szProgID, W("CLSID"), szID); - - // Create VersionIndependentProgID keys. - SetKeyAndValue(szIndepProgID, NULL, szDesc); - SetKeyAndValue(szIndepProgID, W("CurVer"), szProgID); - SetKeyAndValue(szIndepProgID, W("CLSID"), szID); - - // Create entries under CLSID. - SetKeyAndValue(szOutCLSID, NULL, szDesc); - SetKeyAndValue(szOutCLSID, W("ProgID"), szProgID); - SetKeyAndValue(szOutCLSID, W("VersionIndependentProgID"), szIndepProgID); - SetKeyAndValue(szOutCLSID, W("NotInsertable"), NULL); - return (S_OK); -} - - - -//***************************************************************************** -// Unregister the basic information in the system registry for a given object -// class. -//***************************************************************************** -HRESULT REGUTIL::UnregisterCOMClass( // Return code. - REFCLSID rclsid, // Class ID we are registering. - LPCTSTR szProgIDPrefix, // Prefix for progid. - int iVersion, // Version # for progid. - LPCTSTR szClassProgID, // Class progid. - BOOL fExternal) // flag - External to mscoree. -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - } - CONTRACTL_END; - - WCHAR rcCLSID[64]; // CLSID\\szID. - WCHAR rcProgID[128]; // szProgIDPrefix.szClassProgID - WCHAR rcIndProgID[128]; // rcProgID.iVersion - - // Format the prog ID values. - VERIFY(_snwprintf_s(rcProgID, _countof(rcProgID), _TRUNCATE, W("%s.%s"), szProgIDPrefix, szClassProgID)); - - VERIFY(_snwprintf_s(rcIndProgID, _countof(rcIndProgID), _TRUNCATE, W("%s.%d"), rcProgID, iVersion)); - - UnregisterClassBase(rclsid, rcProgID, rcIndProgID, rcCLSID, NumItems(rcCLSID)); - DeleteKey(rcCLSID, W("InprocServer32")); - if (fExternal){ - DeleteKey(rcCLSID, W("Server")); - DeleteKey(rcCLSID, W("Version")); - } - GuidToLPWSTR(rclsid, rcCLSID, NumItems(rcCLSID)); - DeleteKey(W("CLSID"), rcCLSID); - return (S_OK); -} - - -//***************************************************************************** -// Unregister the basic information in the system registry for a given object -// class. -// NOTE: This is the non-side-by-side execution version. -//***************************************************************************** -HRESULT REGUTIL::UnregisterCOMClass( // Return code. - REFCLSID rclsid, // Class ID we are registering. - LPCTSTR szProgIDPrefix, // Prefix for progid. - int iVersion, // Version # for progid. - LPCTSTR szClassProgID) // Class progid. -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - } - CONTRACTL_END; - - WCHAR rcCLSID[64]; // CLSID\\szID. - WCHAR rcProgID[128]; // szProgIDPrefix.szClassProgID - WCHAR rcIndProgID[128]; // rcProgID.iVersion - - // Format the prog ID values. - VERIFY(_snwprintf_s(rcProgID, _countof(rcProgID), _TRUNCATE, W("%s.%s"), szProgIDPrefix, szClassProgID)); - - VERIFY(_snwprintf_s(rcIndProgID, _countof(rcIndProgID), _TRUNCATE, W("%s.%d"), rcProgID, iVersion)); - - UnregisterClassBase(rclsid, rcProgID, rcIndProgID, rcCLSID, NumItems(rcCLSID)); - DeleteKey(rcCLSID, W("InprocServer32")); - DeleteKey(rcCLSID, W("LocalServer32")); - - GuidToLPWSTR(rclsid, rcCLSID, NumItems(rcCLSID)); - DeleteKey(W("CLSID"), rcCLSID); - return (S_OK); -} - - -//***************************************************************************** -// Delete the basic settings for an inproc server. -//***************************************************************************** -HRESULT REGUTIL::UnregisterClassBase( // Return code. - REFCLSID rclsid, // Class ID we are registering. - LPCTSTR szProgID, // Class prog ID. - LPCTSTR szIndepProgID, // Class version independant prog ID. - __out_ecount(cchOutCLSID) LPTSTR szOutCLSID, // Return formatted class ID here. - DWORD cchOutCLSID) // Out CLS ID buffer size -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - } - CONTRACTL_END; - - TCHAR szID[64]; // The class ID to register. - - // Create some base key strings. - GuidToLPWSTR(rclsid, szID, NumItems(szID)); - size_t nLen = _tcslen(_T("CLSID\\")) + _tcslen( szID) + 1; - if( cchOutCLSID < nLen ) - return E_INVALIDARG; - - _tcscpy_s(szOutCLSID, cchOutCLSID, W("CLSID\\")); - _tcscat_s(szOutCLSID, cchOutCLSID, szID); - - // Delete the version independant prog ID settings. - DeleteKey(szIndepProgID, W("CurVer")); - DeleteKey(szIndepProgID, W("CLSID")); - WszRegDeleteKey(HKEY_CLASSES_ROOT, szIndepProgID); - - // Delete the prog ID settings. - DeleteKey(szProgID, W("CLSID")); - WszRegDeleteKey(HKEY_CLASSES_ROOT, szProgID); - - // Delete the class ID settings. - DeleteKey(szOutCLSID, W("ProgID")); - DeleteKey(szOutCLSID, W("VersionIndependentProgID")); - DeleteKey(szOutCLSID, W("NotInsertable")); - WszRegDeleteKey(HKEY_CLASSES_ROOT, szOutCLSID); - return (S_OK); -} - - -//***************************************************************************** -// Register a type library. -//***************************************************************************** -HRESULT REGUTIL::RegisterTypeLib( // Return code. - REFGUID rtlbid, // TypeLib ID we are registering. - int iVersion, // Typelib version. - LPCTSTR szDesc, // TypeLib description. - LPCTSTR szModule) // Path to the typelib. -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - } - CONTRACTL_END; - - WCHAR szID[64]; // The typelib ID to register. - WCHAR szTLBID[256]; // TypeLib\\szID. - WCHAR szHelpDir[_MAX_PATH]; - WCHAR szDrive[_MAX_DRIVE] = {0}; - WCHAR szDir[_MAX_DIR] = {0}; - WCHAR szVersion[64]; - LPWSTR szTmp; - - // Create some base key strings. - GuidToLPWSTR(rtlbid, szID, NumItems(szID)); - - _tcscpy_s(szTLBID, _countof(szTLBID), W("TypeLib\\")); - _tcscat_s(szTLBID, _countof(szTLBID), szID); - - VERIFY(_snwprintf_s(szVersion, _countof(szVersion), _TRUNCATE, W("%d.0"), iVersion)); - - // Create Typelib keys. - SetKeyAndValue(szTLBID, NULL, NULL); - SetKeyAndValue(szTLBID, szVersion, szDesc); - _tcscat_s(szTLBID, _countof(szTLBID), W("\\")); - _tcscat_s(szTLBID, _countof(szTLBID), szVersion); - SetKeyAndValue(szTLBID, W("0"), NULL); - SetKeyAndValue(szTLBID, W("0\\win32"), szModule); - SetKeyAndValue(szTLBID, W("FLAGS"), W("0")); - SplitPath(szModule, szDrive, _MAX_DRIVE, szDir, _MAX_DIR, NULL, 0, NULL, 0); - _tcscpy_s(szHelpDir, _countof(szHelpDir), szDrive); - if ((szTmp = CharPrev(szDir, szDir + Wszlstrlen(szDir))) != NULL) - *szTmp = '\0'; - _tcscat_s(szHelpDir, _countof(szHelpDir), szDir); - SetKeyAndValue(szTLBID, W("HELPDIR"), szHelpDir); - return (S_OK); -} - - -//***************************************************************************** -// Remove the registry keys for a type library. -//***************************************************************************** -HRESULT REGUTIL::UnregisterTypeLib( // Return code. - REFGUID rtlbid, // TypeLib ID we are registering. - int iVersion) // Typelib version. -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - } - CONTRACTL_END; - - WCHAR szID[64]; // The typelib ID to register. - WCHAR szTLBID[256]; // TypeLib\\szID. - WCHAR szTLBVersion[256]; // TypeLib\\szID\\szVersion - WCHAR szVersion[64]; - - // Create some base key strings. - GuidToLPWSTR(rtlbid, szID, NumItems(szID)); - - VERIFY(_snwprintf_s(szVersion, _countof(szVersion), _TRUNCATE, W("%d.0"), iVersion)); - - _tcscpy_s(szTLBID, _countof(szTLBID), W("TypeLib\\")); - _tcscat_s(szTLBID, _countof(szTLBID), szID); - _tcscpy_s(szTLBVersion, _countof(szTLBVersion), szTLBID); - _tcscat_s(szTLBVersion, _countof(szTLBVersion), W("\\")); - _tcscat_s(szTLBVersion, _countof(szTLBVersion), szVersion); - - // Delete Typelib keys. - DeleteKey(szTLBVersion, W("HELPDIR")); - DeleteKey(szTLBVersion, W("FLAGS")); - DeleteKey(szTLBVersion, W("0\\win32")); - DeleteKey(szTLBVersion, W("0")); - DeleteKey(szTLBID, szVersion); - WszRegDeleteKey(HKEY_CLASSES_ROOT, szTLBID); - return (0); -} - -#endif // !FEATURE_CORECLR // diff --git a/src/utilcode/safewrap.cpp b/src/utilcode/safewrap.cpp index 4a6ecdb93c..294743d519 100644 --- a/src/utilcode/safewrap.cpp +++ b/src/utilcode/safewrap.cpp @@ -40,12 +40,9 @@ void ClrGetCurrentDirectory(SString & value) // An actual API failure in GetCurrentDirectory failure should be very rare, so we'll throw on those. if (len == 0) - { - value.CloseBuffer(0); + { ThrowLastError(); } - - value.CloseBuffer(); } // Nothrowing wrapper. diff --git a/src/utilcode/sortversioning.cpp b/src/utilcode/sortversioning.cpp index 5420947842..65781cdc1a 100644 --- a/src/utilcode/sortversioning.cpp +++ b/src/utilcode/sortversioning.cpp @@ -136,230 +136,6 @@ namespace SortVersioning return i; } -#if !defined(FEATURE_CORECLR) && !defined(CROSSGEN_COMPILE) - //////////////////////////////////////////////////////////////////////////// - // - // LoadSortModuleAndInvariant() - // - // Attempts to load the given dll. If that is successful, attempts to - // load the invariant data. If that is successful, returns the module handle - // and the addresses of the SortGetHandle function and SortCloseHandle function - // - // failure is indicated by returning NULL for the module handle and the - // function addresses - // - //////////////////////////////////////////////////////////////////////////// - - HMODULE LoadSortModuleAndInvariant( - __in LPCWSTR sDllName, - __in DWORD dwVersion, - __out SORTGETHANDLE* ppGetHandle, - __out SORTCLOSEHANDLE* ppCloseHandle - ) - { - *ppGetHandle = NULL; - *ppCloseHandle = NULL; - HMODULE hSort; - - if(FAILED(UtilCode::LoadLibraryShim(sDllName, NULL, NULL, &hSort))) - { - return NULL; - } - - SORTGETHANDLE pGetHandle = (SORTGETHANDLE)GetProcAddress(hSort, "SortGetHandle"); - SORTCLOSEHANDLE pCloseHandle = (SORTCLOSEHANDLE)GetProcAddress(hSort, "SortCloseHandle"); - - // If we didn't load the procs, then remember that - if (pCloseHandle == NULL || pGetHandle == NULL) - { - ::FreeLibrary(hSort); - return NULL; - } - - // Verify that the data file's available - NLSVERSIONINFO sortVersion; - sortVersion.dwNLSVersionInfoSize = sizeof(NLSVERSIONINFO); - sortVersion.dwNLSVersion = dwVersion; - sortVersion.dwDefinedVersion = dwVersion; - - // Invariant must be there and is kinda common, so we'll just get it - PSORTHANDLE pSort = pGetHandle(W(""), &sortVersion, NULL); - if (!pSort) - { - // Yikes, invariant failed, forget about it. - ::FreeLibrary(hSort); - return NULL; - } - - // Since we found it, may as well remember it. - const SORTHANDLE * const pSortInHash = InsertSortHashNode(pSort); - - // If we got a different one back then free the one we added - if (pSortInHash != pSort && pSortInHash) - { - // We got a different one from the hash (someone beat us to the cache) - // so use that and discard the new one. - pCloseHandle(pSort); - } - - *ppGetHandle = pGetHandle; - *ppCloseHandle = pCloseHandle; - return hSort; - } - - // Attempts to load a Sort DLL. If this fails, the values of the __out parameters are unchanged. - __success(return) - BOOL LoadSortDllAndPublish( - __in LPCWSTR sDllName, - __in DWORD dwVersion, - __out __encoded_pointer SORTGETHANDLE* ppGetHandle, - __out __encoded_pointer SORTCLOSEHANDLE* ppCloseHandle, - __out HMODULE* phSortDll) - { - HMODULE hSortDll; - SORTGETHANDLE pGetHandle; - SORTCLOSEHANDLE pCloseHandle; - - hSortDll = LoadSortModuleAndInvariant(sDllName, dwVersion, &pGetHandle, &pCloseHandle); - - if(hSortDll != NULL) { - *phSortDll = hSortDll; - *ppGetHandle = (SORTGETHANDLE)EncodePointer(pGetHandle); - *ppCloseHandle = (SORTCLOSEHANDLE)EncodePointer(pCloseHandle); - return TRUE; - } - - return FALSE; - } - - //////////////////////////////////////////////////////////////////////////// - // - // GetSortGetHandle() - // - // Get the SortGetHandle() function for the proper dll version. - // - //////////////////////////////////////////////////////////////////////////// - SORTGETHANDLE GetSortGetHandle(__in DWORD dwVersion) - { - if(dwVersion == SORT_VERSION_DEFAULT) - { - // If we haven't tried to load the module/proc before do so now - if (g_hSortDefault == (HMODULE)-1) - { - LoadSortDllAndPublish(SORT_DEFAULT_DLL_NAME, SORT_VERSION_DEFAULT, &g_pDefaultGetHandle, &g_pDefaultCloseHandle, &g_hSortDefault); - } - - // This check is necessary because the LoadSortDllAndPublish call may have failed since some platforms - // won't have nlssorting.dll (e.g. Windows 8 and above). - if (g_hSortDefault != (HMODULE)-1) - { - return (SORTGETHANDLE)DecodePointer(g_pDefaultGetHandle); - } - } - - HMODULE* pHSortModule; - SORTGETHANDLE* ppGetHandle; - SORTCLOSEHANDLE* ppCloseHandle; - - if(dwVersion == SORT_VERSION_V4) - { - ppGetHandle = &g_pV4GetHandle; - ppCloseHandle = &g_pV4CloseHandle; - pHSortModule = &g_hSortCompatV4; - } - else if(dwVersion == SORT_VERSION_WHIDBEY) - { - ppGetHandle = &g_pV2GetHandle; - ppCloseHandle = &g_pV2CloseHandle; - pHSortModule = &g_hSortCompatV2; - } - else - { - // Unsupported sorting version. - return NULL; - } - - if(*pHSortModule == (HMODULE) -1) - { - // get module name - the module name should be "Sort"+dwVersion.ToString("x8")+".dll" - WCHAR moduleName[] = W("Sort00000000.dll"); - // replace the "00000000" with the hexadecimal of dwVersion - LPCWSTR hex = W("0123456789abcdef"); - WCHAR* p = &moduleName[4+8]; // position at end of number part of dll name - - unsigned int value = dwVersion; - - while (value != 0 && p != moduleName) { - int digit = value & 0xF; - *--p = hex[digit]; - value >>= 4; - } - - if(!LoadSortDllAndPublish(&moduleName[0], dwVersion, ppGetHandle, ppCloseHandle, pHSortModule)) - { - // We failed to load a versioned sort dll, try to fall back to the current version. - // If we haven't tried to load the module/proc before do so now - if (g_hSortDefault == (HMODULE)-1) - { - LoadSortDllAndPublish(SORT_DEFAULT_DLL_NAME, SORT_VERSION_DEFAULT, &g_pDefaultGetHandle, &g_pDefaultCloseHandle, &g_hSortDefault); - } - - *pHSortModule = g_hSortDefault; - *ppCloseHandle = g_pDefaultCloseHandle; - *ppGetHandle = g_pDefaultGetHandle; - } - } - - // At this point, we've either loaded a sorting dll or we've exausted all options. - if(*pHSortModule == (HMODULE) -1) - { - // Couldn't find anything, give up. - return NULL; - } - else - { - return (SORTGETHANDLE)DecodePointer(*ppGetHandle); - } - - // Unknown version requested - return NULL; - } - - void DoSortCloseHandle(__in DWORD dwVersion, __in PSORTHANDLE pSort) - { - if (dwVersion == SORT_VERSION_DEFAULT) - { - SORTCLOSEHANDLE pDefaultCloseHandle = (SORTCLOSEHANDLE)DecodePointer(g_pDefaultCloseHandle); - if(pDefaultCloseHandle != NULL) - { - (pDefaultCloseHandle)(pSort); - return; - } - } - - if (dwVersion == SORT_VERSION_V4) - { - SORTCLOSEHANDLE pV4CloseHandle = (SORTCLOSEHANDLE)DecodePointer(g_pV4CloseHandle); - if(pV4CloseHandle != NULL) - { - (pV4CloseHandle)(pSort); - return; - } - } - - - if (dwVersion == SORT_VERSION_WHIDBEY) - { - SORTCLOSEHANDLE pV2CloseHandle = (SORTCLOSEHANDLE)DecodePointer(g_pV2CloseHandle); - if(pV2CloseHandle != NULL) - { - (pV2CloseHandle)(pSort); - return; - } - } - } - -#else // !defined(FEATURE_CORECLR) && !defined(CROSSGEN_COMPILE) SORTGETHANDLE GetSortGetHandle(__in DWORD dwVersion) { @@ -370,7 +146,6 @@ namespace SortVersioning { } -#endif // !defined(FEATURE_CORECLR) && !defined(CROSSGEN_COMPILE) //////////////////////////////////////////////////////////////////////////// // @@ -663,26 +438,7 @@ namespace SortVersioning //////////////////////////////////////////////////////////////////////////// DWORD SortNLSVersion() { -#ifdef FEATURE_CORECLR return SORT_VERSION_DEFAULT; -#else - static bool sortNLSVersionConfigChecked = false; - static DWORD sortNLSVersion = SORT_VERSION_DEFAULT; - - if(!sortNLSVersionConfigChecked) - { - BEGIN_SO_INTOLERANT_CODE_NO_THROW_CHECK_THREAD(return false); - sortNLSVersion = CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_CompatSortNLSVersion); - if(sortNLSVersion == 0) - { - sortNLSVersion = SORT_VERSION_DEFAULT; - } - END_SO_INTOLERANT_CODE; - - sortNLSVersionConfigChecked = true; - } - return sortNLSVersion; -#endif // !FEATURE_CORECLR } //////////////////////////////////////////////////////////////////////////// diff --git a/src/utilcode/stacktrace.cpp b/src/utilcode/stacktrace.cpp index 858fac723e..3dee1802f4 100644 --- a/src/utilcode/stacktrace.cpp +++ b/src/utilcode/stacktrace.cpp @@ -949,7 +949,7 @@ void MagicDeinit(void) } } -#if defined(_TARGET_X86_) && defined(FEATURE_CORECLR) +#if defined(_TARGET_X86_) /**************************************************************************** * ClrCaptureContext * *-------------------* @@ -989,4 +989,4 @@ ClrCaptureContext(__out PCONTEXT ctx) ret 4 } } -#endif // _TARGET_X86_ && FEATURE_CORECLR +#endif // _TARGET_X86 diff --git a/src/utilcode/stresslog.cpp b/src/utilcode/stresslog.cpp index d364b06dd6..91c5c0e8ef 100644 --- a/src/utilcode/stresslog.cpp +++ b/src/utilcode/stresslog.cpp @@ -608,12 +608,7 @@ FORCEINLINE BOOL StressLog::InlinedETWLogOn(unsigned facility, unsigned level) STATIC_CONTRACT_LEAF; STATIC_CONTRACT_SUPPORTS_DAC; -#if defined(FEATURE_EVENT_TRACE) && !defined(FEATURE_CORECLR) && !defined(DACCESS_COMPILE) - return ((Microsoft_Windows_DotNETRuntimeStressHandle != 0) && - (ETW_CATEGORY_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_STRESS_PROVIDER_Context, (UCHAR)level, facility) != 0)); -#else return FALSE; -#endif } BOOL StressLog::ETWLogOn(unsigned facility, unsigned level) @@ -671,28 +666,6 @@ void StressLog::LogMsg (unsigned level, unsigned facility, int cArgs, const char } // Stress Log ETW feature available only on the desktop versions of the runtime -#if !defined(FEATURE_CORECLR) - // The previous LogMsg call could have modified the Args, so we need to reset it - if(InlinedETWLogOn(facility, level)) - { -#define MAX_STRESSLOG_DATA_ETW_LENGTH 256 - CHAR logMessage[MAX_STRESSLOG_DATA_ETW_LENGTH]; - - va_start(Args, format); - ULONG messageLength = (USHORT)_vsnprintf_s(logMessage, COUNTOF(logMessage), MAX_STRESSLOG_DATA_ETW_LENGTH-1, format, Args); - va_end(Args); - - if(messageLength >= 0 && - messageLength < MAX_STRESSLOG_DATA_ETW_LENGTH) // this condition has been added to make prefast happy - { - logMessage[messageLength] = 0; - } - messageLength++; - logMessage[MAX_STRESSLOG_DATA_ETW_LENGTH-1] = 0; - FireEtwStressLogEvent_V1((UINT32)facility, (UCHAR)level, logMessage, GetClrInstanceId()); -#undef MAX_STRESSLOG_DATA_ETW_LENGTH - } -#endif // !FEATURE_CORECLR #endif //!DACCESS_COMPILE } diff --git a/src/utilcode/tlbutils.cpp b/src/utilcode/tlbutils.cpp deleted file mode 100644 index ed42c28fc8..0000000000 --- a/src/utilcode/tlbutils.cpp +++ /dev/null @@ -1,221 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// -// Utilities used to help manipulating typelibs. - -#include "stdafx.h" // Precompiled header key. - -#include "tlbutils.h" -#include "dispex.h" -#include "posterror.h" -#include "ndpversion.h" - -#define CUSTOM_MARSHALER_ASM ", CustomMarshalers, Version=" VER_ASSEMBLYVERSION_STR ", Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" - -static const LPCWSTR DLL_EXTENSION = {W(".dll")}; -static const int DLL_EXTENSION_LEN = 4; -static const LPCWSTR EXE_EXTENSION = {W(".exe")}; -static const int EXE_EXTENSION_LEN = 4; - -const StdConvertibleItfInfo aStdConvertibleInterfaces[] = -{ - { "System.Runtime.InteropServices.Expando.IExpando", (GUID*)&IID_IDispatchEx, - "System.Runtime.InteropServices.CustomMarshalers.ExpandoToDispatchExMarshaler" CUSTOM_MARSHALER_ASM, "IExpando" }, - - { "System.Reflection.IReflect", (GUID*)&IID_IDispatchEx, - "System.Runtime.InteropServices.CustomMarshalers.ExpandoToDispatchExMarshaler" CUSTOM_MARSHALER_ASM, "IReflect" }, - - { "System.Collections.IEnumerator", (GUID*)&IID_IEnumVARIANT, - "System.Runtime.InteropServices.CustomMarshalers.EnumeratorToEnumVariantMarshaler" CUSTOM_MARSHALER_ASM, "" }, - - { "System.Type", (GUID*)&IID_ITypeInfo, - "System.Runtime.InteropServices.CustomMarshalers.TypeToTypeInfoMarshaler" CUSTOM_MARSHALER_ASM, "" }, -}; - -// This method returns the custom marshaler info to convert the native interface -// to its managed equivalent. Or null if the interface is not a standard convertible interface. -const StdConvertibleItfInfo *GetConvertionInfoFromNativeIID(REFGUID rGuidNativeItf) -{ - CONTRACT (const StdConvertibleItfInfo*) - { - NOTHROW; - POSTCONDITION(CheckPointer(RETVAL, NULL_OK)); - } - CONTRACT_END; - - // Look in the table of interfaces that have standard convertions to see if the - // specified interface is there. - for (int i = 0; i < sizeof(aStdConvertibleInterfaces) / sizeof(StdConvertibleItfInfo); i++) - { - if (IsEqualGUID(rGuidNativeItf, *(aStdConvertibleInterfaces[i].m_pNativeTypeIID))) - RETURN &aStdConvertibleInterfaces[i]; - } - - // The interface is not in the table. - RETURN NULL; -} - -//***************************************************************************** -// Given a typelib, determine the managed namespace name. -//***************************************************************************** -HRESULT GetNamespaceNameForTypeLib( // S_OK or error. - ITypeLib *pITLB, // [IN] The TypeLib. - BSTR *pwzNamespace) // [OUT] Put the namespace name here. -{ - CONTRACTL - { - DISABLED(NOTHROW); // PostError goes down a throwing path right now. Revisit this when fixed. - PRECONDITION(CheckPointer(pITLB)); - PRECONDITION(CheckPointer(pwzNamespace)); - } - CONTRACTL_END; - - HRESULT hr = S_OK; // A result. - ITypeLib2 *pITLB2=0; //For getting custom value. - TLIBATTR *pAttr=0; // Typelib attributes. - BSTR szPath=0; // Typelib path. - - // If custom attribute for namespace exists, use it. - if (pITLB->QueryInterface(IID_ITypeLib2, (void **)&pITLB2) == S_OK) - { - VARIANT vt; - VariantInit(&vt); - if (pITLB2->GetCustData(GUID_ManagedName, &vt) == S_OK) - { - if (V_VT(&vt) == VT_BSTR) - { - // If the namespace ends with .dll then remove the extension. - LPWSTR pDest = wcsstr(vt.bstrVal, DLL_EXTENSION); - if (pDest && (pDest[DLL_EXTENSION_LEN] == 0 || pDest[DLL_EXTENSION_LEN] == ' ')) - *pDest = 0; - - if (!pDest) - { - // If the namespace ends with .exe then remove the extension. - pDest = wcsstr(vt.bstrVal, EXE_EXTENSION); - if (pDest && (pDest[EXE_EXTENSION_LEN] == 0 || pDest[EXE_EXTENSION_LEN] == ' ')) - *pDest = 0; - } - - if (pDest) - { - // We removed the extension so re-allocate a string of the new length. - *pwzNamespace = SysAllocString(vt.bstrVal); - SysFreeString(vt.bstrVal); - } - else - { - // There was no extension to remove so we can use the string returned - // by GetCustData(). - *pwzNamespace = vt.bstrVal; - } - - goto ErrExit; - } - else - { - VariantClear(&vt); - } - } - } - - // No custom attribute, use library name. - IfFailGo(pITLB->GetDocumentation(MEMBERID_NIL, pwzNamespace, 0, 0, 0)); - -ErrExit: - if (szPath) - ::SysFreeString(szPath); - if (pAttr) - pITLB->ReleaseTLibAttr(pAttr); - if (pITLB2) - pITLB2->Release(); - - return hr; -} // HRESULT GetNamespaceNameForTypeLib() - -//***************************************************************************** -// Given an ITypeInfo, determine the managed name. Optionally supply a default -// namespace, otherwise derive namespace from containing typelib. -//***************************************************************************** -HRESULT GetManagedNameForTypeInfo( // S_OK or error. - ITypeInfo *pITI, // [IN] The TypeInfo. - LPCWSTR wzNamespace, // [IN, OPTIONAL] Default namespace name. - LPCWSTR wzAsmName, // [IN, OPTIONAL] Assembly name. - BSTR *pwzName) // [OUT] Put the name here. -{ - CONTRACTL - { - DISABLED(NOTHROW); - PRECONDITION(CheckPointer(pITI)); - PRECONDITION(CheckPointer(wzNamespace, NULL_OK)); - PRECONDITION(CheckPointer(wzAsmName, NULL_OK)); - PRECONDITION(CheckPointer(pwzName)); - } - CONTRACTL_END; - - HRESULT hr = S_OK; // A result. - ITypeInfo2 *pITI2=0; // For getting custom value. - ITypeLib *pITLB=0; // Containing typelib. - - BSTR bstrName=0; // Typeinfo's name. - BSTR bstrNamespace=0; // Typelib's namespace. - int cchFullyQualifiedName; // Size of namespace + name buffer. - int cchAsmName=0; // The size of the assembly name. - int cchAsmQualifiedName=0; // The size of the assembly qualified name buffer. - CQuickArray<WCHAR> qbFullyQualifiedName; // The fully qualified type name. - - // Check for a custom value with name. - if (pITI->QueryInterface(IID_ITypeInfo2, (void **)&pITI2) == S_OK) - { - VARIANT vt; // For getting custom value. - ::VariantInit(&vt); - if (pITI2->GetCustData(GUID_ManagedName, &vt) == S_OK && vt.vt == VT_BSTR) - { // There is a custom value with the name. Just believe it. - *pwzName = vt.bstrVal; - vt.bstrVal = 0; - vt.vt = VT_EMPTY; - goto ErrExit; - } - } - - // Still need name, get the namespace. - if (wzNamespace == 0) - { - IfFailGo(pITI->GetContainingTypeLib(&pITLB, 0)); - IfFailGo(GetNamespaceNameForTypeLib(pITLB, &bstrNamespace)); - wzNamespace = bstrNamespace; - } - - // Get the name, and combine with namespace. - IfFailGo(pITI->GetDocumentation(MEMBERID_NIL, &bstrName, 0,0,0)); - cchFullyQualifiedName = (int)(wcslen(bstrName) + wcslen(wzNamespace) + 1); - IfFailGo(qbFullyQualifiedName.ReSizeNoThrow(cchFullyQualifiedName + 1)); - ns::MakePath(qbFullyQualifiedName.Ptr(), cchFullyQualifiedName + 1, wzNamespace, bstrName); - - // If the assembly name is specified, then add it to the type name. - if (wzAsmName) - { - cchAsmName = (int)wcslen(wzAsmName); - cchAsmQualifiedName = cchFullyQualifiedName + cchAsmName + 3; - IfNullGo(*pwzName = ::SysAllocStringLen(0, cchAsmQualifiedName)); - ns::MakeAssemblyQualifiedName(*pwzName, cchAsmQualifiedName, qbFullyQualifiedName.Ptr(), cchFullyQualifiedName, wzAsmName, cchAsmName); - } - else - { - IfNullGo(*pwzName = ::SysAllocStringLen(qbFullyQualifiedName.Ptr(), cchFullyQualifiedName)); - } - -ErrExit: - if (bstrName) - ::SysFreeString(bstrName); - if (bstrNamespace) - ::SysFreeString(bstrNamespace); - if (pITLB) - pITLB->Release(); - if (pITI2) - pITI2->Release(); - - return (hr); -} // HRESULT GetManagedNameForTypeInfo() diff --git a/src/utilcode/util.cpp b/src/utilcode/util.cpp index 33722e5297..c215a49213 100644 --- a/src/utilcode/util.cpp +++ b/src/utilcode/util.cpp @@ -19,9 +19,6 @@ #include "cor.h" #include "corinfo.h" -#ifndef FEATURE_CORECLR -#include "metahost.h" -#endif // !FEATURE_CORECLR const char g_RTMVersion[]= "v1.0.3705"; @@ -882,6 +879,27 @@ BYTE * ClrVirtualAllocWithinRange(const BYTE *pMinAddr, #endif } +#if !defined(FEATURE_REDHAWK) && defined(_TARGET_AMD64_) && !defined(FEATURE_PAL) +// Calculate greatest common divisor +DWORD GCD(DWORD u, DWORD v) +{ + while (v != 0) + { + DWORD dwTemp = v; + v = u % v; + u = dwTemp; + } + + return u; +} + +// Calculate least common multiple +DWORD LCM(DWORD u, DWORD v) +{ + return u / GCD(u, v) * v; +} +#endif + /*static*/ BOOL CPUGroupInfo::InitCPUGroupInfoArray() { CONTRACTL @@ -943,11 +961,13 @@ BYTE * ClrVirtualAllocWithinRange(const BYTE *pMinAddr, m_CPUGroupInfoArray[i].nr_active = (WORD)pRecord->Group.GroupInfo[i].ActiveProcessorCount; m_CPUGroupInfoArray[i].active_mask = pRecord->Group.GroupInfo[i].ActiveProcessorMask; m_nProcessors += m_CPUGroupInfoArray[i].nr_active; - dwWeight *= (DWORD)m_CPUGroupInfoArray[i].nr_active; + dwWeight = LCM(dwWeight, (DWORD)m_CPUGroupInfoArray[i].nr_active); } - //NOTE: the weight setting should work fine with 4 CPU groups upto 64 LPs each. the minimum number of threads - // per group before the weight overflow is 2^32/(2^6x2^6x2^6) = 2^14 (i.e. 16K threads) + // The number of threads per group that can be supported will depend on the number of CPU groups + // and the number of LPs within each processor group. For example, when the number of LPs in + // CPU groups is the same and is 64, the number of threads per group before weight overflow + // would be 2^32/2^6 = 2^26 (64M threads) for (DWORD i = 0; i < m_nGroups; i++) { m_CPUGroupInfoArray[i].groupWeight = dwWeight / (DWORD)m_CPUGroupInfoArray[i].nr_active; @@ -3322,114 +3342,6 @@ BOOL FileExists(LPCWSTR filename) return TRUE; } -#ifndef FEATURE_CORECLR -// Current users for FileLock are ngen and ngen service - -FileLockHolder::FileLockHolder() -{ - _hLock = INVALID_HANDLE_VALUE; -} - -FileLockHolder::~FileLockHolder() -{ - Release(); -} - -// the amount of time we want to wait -#define FILE_LOCK_RETRY_TIME 100 - -void FileLockHolder::Acquire(LPCWSTR lockName, HANDLE hInterrupt, BOOL* pInterrupted) -{ - WRAPPER_NO_CONTRACT; - - DWORD dwErr = 0; - DWORD dwAccessDeniedRetry = 0; - const DWORD MAX_ACCESS_DENIED_RETRIES = 10; - - if (pInterrupted) - { - *pInterrupted = FALSE; - } - - _ASSERTE(_hLock == INVALID_HANDLE_VALUE); - - for (;;) { - _hLock = WszCreateFile(lockName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_FLAG_DELETE_ON_CLOSE, NULL); - if (_hLock != INVALID_HANDLE_VALUE) { - return; - } - - dwErr = GetLastError(); - // Logically we should only expect ERROR_SHARING_VIOLATION, but Windows can also return - // ERROR_ACCESS_DENIED for underlying NtStatus DELETE_PENDING. That happens when another process - // (gacutil.exe or indexer) have the file opened. Unfortunately there is no public API that would - // allow us to detect this NtStatus and distinguish it from 'real' access denied (candidates are - // RtlGetLastNtStatus that is not documented on MSDN and NtCreateFile that is internal and can change - // at any time), so we retry on access denied, but only for a limited number of times. - if (dwErr == ERROR_SHARING_VIOLATION || - (dwErr == ERROR_ACCESS_DENIED && ++dwAccessDeniedRetry <= MAX_ACCESS_DENIED_RETRIES)) - { - // Somebody is holding the lock. Let's sleep, and come back again. - if (hInterrupt) - { - _ASSERTE(pInterrupted && - "If you can be interrupted, you better want to know if you actually were interrupted"); - if (WaitForSingleObject(hInterrupt, FILE_LOCK_RETRY_TIME) == WAIT_OBJECT_0) - { - if (pInterrupted) - { - *pInterrupted = TRUE; - } - - // We've been interrupted, so return without acquiring - return; - } - } - else - { - ClrSleepEx(FILE_LOCK_RETRY_TIME, FALSE); - } - } - else { - ThrowHR(HRESULT_FROM_WIN32(dwErr)); - } - } -} - - -HRESULT FileLockHolder::AcquireNoThrow(LPCWSTR lockName, HANDLE hInterrupt, BOOL* pInterrupted) -{ - HRESULT hr = S_OK; - - EX_TRY - { - Acquire(lockName, hInterrupt, pInterrupted); - } - EX_CATCH_HRESULT(hr); - - return hr; -} - -BOOL FileLockHolder::IsTaken(LPCWSTR lockName) -{ - - // We don't want to do an acquire the lock to know if its taken, so we want to see if the file - // exists. However, in situations like unplugging a machine, a DELETE_ON_CLOSE still leaves the file - // around. We try to delete it here. If the lock is acquired, DeleteFile will fail, as the file is - // not opened with SHARE_DELETE. - WszDeleteFile(lockName); - - return FileExists(lockName); -} - -void FileLockHolder::Release() -{ - if (_hLock != INVALID_HANDLE_VALUE) { - CloseHandle(_hLock); - _hLock = INVALID_HANDLE_VALUE; - } -} -#endif // FEATURE_CORECLR //====================================================================== // This function returns true, if it can determine that the instruction pointer @@ -3587,59 +3499,6 @@ RUNTIMEVERSIONINFO RUNTIMEVERSIONINFO::notDefined; BOOL IsV2RuntimeLoaded(void) { -#ifndef FEATURE_CORECLR - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - CANNOT_TAKE_LOCK; - } - CONTRACTL_END; - - ReleaseHolder<ICLRMetaHost> pMetaHost(NULL); - ReleaseHolder<IEnumUnknown> pEnum(NULL); - ReleaseHolder<IUnknown> pUnk(NULL); - ReleaseHolder<ICLRRuntimeInfo> pRuntime(NULL); - HRESULT hr; - - HModuleHolder hModule = WszLoadLibrary(MSCOREE_SHIM_W); - if (hModule == NULL) - return FALSE; - - CLRCreateInstanceFnPtr pfnCLRCreateInstance = (CLRCreateInstanceFnPtr)::GetProcAddress(hModule, "CLRCreateInstance"); - if (pfnCLRCreateInstance == NULL) - return FALSE; - - hr = (*pfnCLRCreateInstance)(CLSID_CLRMetaHost, IID_ICLRMetaHost, (LPVOID *)&pMetaHost); - if (FAILED(hr)) - return FALSE; - - hr = pMetaHost->EnumerateLoadedRuntimes(GetCurrentProcess(), &pEnum); - if (FAILED(hr)) - return FALSE; - - while (pEnum->Next(1, &pUnk, NULL) == S_OK) - { - hr = pUnk->QueryInterface(IID_ICLRRuntimeInfo, (void **)&pRuntime); - if (FAILED(hr)) - continue; - - WCHAR wszVersion[30]; - DWORD cchVersion = _countof(wszVersion); - hr = pRuntime->GetVersionString(wszVersion, &cchVersion); - if (FAILED(hr)) - continue; - - // Is it a V2 runtime? - if ((cchVersion < 3) || - ((wszVersion[0] != W('v')) && (wszVersion[0] != W('V'))) || - (wszVersion[1] != W('2')) || - (wszVersion[2] != W('.'))) - continue; - - return TRUE; - } -#endif // FEATURE_CORECLR return FALSE; } @@ -3650,11 +3509,6 @@ BOOL IsClrHostedLegacyComObject(REFCLSID rclsid) // let's simply check for all CLSIDs that are known to be runtime implemented and capped to 2.0 return ( rclsid == CLSID_ComCallUnmarshal || -#ifdef FEATURE_INCLUDE_ALL_INTERFACES - rclsid == CLSID_CorRuntimeHost || - rclsid == CLSID_CLRRuntimeHost || - rclsid == CLSID_CLRProfiling || -#endif rclsid == CLSID_CorMetaDataDispenser || rclsid == CLSID_CorMetaDataDispenserRuntime || rclsid == CLSID_TypeNameFactory); @@ -3663,54 +3517,6 @@ BOOL IsClrHostedLegacyComObject(REFCLSID rclsid) -#if !defined(FEATURE_CORECLR) && !defined(SELF_NO_HOST) && !defined(FEATURE_UTILCODE_NO_DEPENDENCIES) - -namespace UtilCode -{ - -#pragma warning(push) -#pragma warning(disable:4996) // For use of deprecated LoadLibraryShim - - // When a NULL version is passed to LoadLibraryShim, this told the shim to bind the already-loaded - // runtime or to the latest runtime. In hosted environments, we already know a runtime (or two) is - // loaded, and since we are no longer guaranteed that a call to mscoree!LoadLibraryShim with a NULL - // version will return the correct runtime, this code uses the ClrCallbacks infrastructure - // available to get the ICLRRuntimeInfo for the runtime in which this code is hosted, and then - // calls ICLRRuntimeInfo::LoadLibrary to make sure that the load occurs within the context of the - // correct runtime. - HRESULT LoadLibraryShim(LPCWSTR szDllName, LPCWSTR szVersion, LPVOID pvReserved, HMODULE *phModDll) - { - HRESULT hr = S_OK; - - if (szVersion != NULL) - { // If a version is provided, then we just fall back to the legacy function to allow - // it to construct the explicit path and load from that location. - //@TODO: Can we verify that all callers of LoadLibraryShim in hosted environments always pass null and eliminate this code? - return ::LoadLibraryShim(szDllName, szVersion, pvReserved, phModDll); - } - - // - // szVersion is NULL, which means we should load the DLL from the hosted environment's directory. - // - - typedef ICLRRuntimeInfo *GetCLRRuntime_t(); - GetCLRRuntime_t *pfnGetCLRRuntime = - reinterpret_cast<GetCLRRuntime_t *>((*GetClrCallbacks().m_pfnGetCLRFunction)("GetCLRRuntime")); - if (pfnGetCLRRuntime == NULL) - return E_UNEXPECTED; - - ICLRRuntimeInfo* pRI = (*pfnGetCLRRuntime)(); - if (pRI == NULL) - return E_UNEXPECTED; - - return pRI->LoadLibrary(szDllName, phModDll); - } - -#pragma warning(pop) - -} - -#endif //!FEATURE_CORECLR && !SELF_NO_HOST && !FEATURE_UTILCODE_NO_DEPENDENCIES namespace Clr { diff --git a/src/utilcode/utilmessagebox.cpp b/src/utilcode/utilmessagebox.cpp index 4559d16b7f..58fd7554c2 100644 --- a/src/utilcode/utilmessagebox.cpp +++ b/src/utilcode/utilmessagebox.cpp @@ -24,29 +24,6 @@ #include "commctrl.h" #endif -#if !defined(SELF_NO_HOST) && !defined(FEATURE_CORECLR) - -// -// This should be used for runtime dialog box, because we assume the resource is from mscorrc.dll -// For tools like ildasm or Shim which uses their own resource file, you need to define IDS_RTL in -// their resource file and define a function like this and append the style returned from the function -// to every calls to WszMessageBox. -// -UINT GetCLRMBRTLStyle() -{ - WRAPPER_NO_CONTRACT; - - UINT mbStyle = 0; - WCHAR buff[MAX_LONGPATH]; - if(SUCCEEDED(UtilLoadStringRC(IDS_RTL, buff, MAX_LONGPATH, true))) { - if(wcscmp(buff, W("RTL_True")) == 0) { - mbStyle = 0x00080000 |0x00100000; // MB_RIGHT || MB_RTLREADING - } - } - return mbStyle; -} - -#endif //!defined(SELF_NO_HOST) && !defined(FEATURE_CORECLR) BOOL ShouldDisplayMsgBoxOnCriticalFailure() { @@ -72,16 +49,6 @@ BOOL ShouldDisplayMsgBoxOnCriticalFailure() } -#if !defined(FEATURE_CORESYSTEM) && !defined(FEATURE_CORECLR) -enum ProbedTaskDialogIndirectState -{ - ProbedTaskDialogIndirectState_NotProbed = 0, - ProbedTaskDialogIndirectState_NotAvailable = 1, - ProbedTaskDialogIndirectState_Available = 2 -}; - -static ProbedTaskDialogIndirectState siProbedTaskDialogIndirect = ProbedTaskDialogIndirectState_NotProbed; -#endif // !FEATURE_CORESYSTEM && !FEATURE_CORECLR // We'd like to use TaskDialogIndirect for asserts coming from managed code in particular @@ -109,157 +76,7 @@ int MessageBoxImpl( } CONTRACTL_END; -#if defined(FEATURE_CORESYSTEM) || defined (FEATURE_CORECLR) return WszMessageBox(hWnd, message, title, uType); -#else - bool mustUseMessageBox = false; // Mac, Silverlight, pre-Vista? Do we support this type of message box? - decltype(TaskDialogIndirect)* pfnTaskDialogIndirect = NULL; - ULONG_PTR cookie = NULL; // For activation context. - bool activatedActivationContext = false; - HModuleHolder hmodComctl32; - HANDLE hActCtx = INVALID_HANDLE_VALUE; - - // Note: TaskDialogIndirect is only in the v6 and above versions of comctl32. Windows - // stores that library in the WinSxS directory in a directory with - // "Microsoft.Windows.Common-Controls" in the name. Your application can only see - // this library if the linker has added a manifest dependency on the V6 common controls - // to your application. Or, you can create an activation context to make this work, - // if your library also has the appropriate manifest dependency. - // Also, I'm not going to leave comctl32.dll mapped, to ensure it can't somehow - // interfere with older versions. Therefore, re-load comctl32.dll every time through - // this method. We will record whether TaskDialogIndirect is available though, so - // we can fall back to MessageBox faster. - - // We don't yet have a perfect mapping from all MessageBox behavior to TaskDialogIndirect behavior. - // Use MessageBox to avoid most of this complexity. - if (((uType & MB_ICONMASK) != MB_ICONWARNING) && (uType & MB_ICONMASK) != MB_ICONERROR || - (uType & MB_TYPEMASK) != MB_ABORTRETRYIGNORE || - (uType & MB_DEFMASK) != 0 || - (uType & MB_MODEMASK) != 0 || - (uType & MB_MISCMASK) != 0) - mustUseMessageBox = true; - else if (mustUseMessageBox || siProbedTaskDialogIndirect == ProbedTaskDialogIndirectState_NotAvailable) - mustUseMessageBox = true; - else { - // Replace our application's ActivationContext temporarily, load comctl32 - // & look for TaskDialogIndirect. Don't cache pointer. - // The following code was suggested by some Windows experts. We do not want - // to add a manifest to our library saying we use comctl32 v6, because that - // will mean loading a lot of extra libraries on startup (a significant perf hit). - // We could either store the manifest as a resource, or more creatively since - // we are effectively a Windows component, rely on %windir%\WindowsShell.manifest. - ACTCTX ctx = { sizeof(ACTCTX) }; - ctx.dwFlags = 0; - StackSString manifestPath; // Point this at %windir%\WindowsShell.manifest, for comctl32 version 6. - UINT numChars = WszGetWindowsDirectory(manifestPath.OpenUnicodeBuffer(MAX_PATH_FNAME), MAX_PATH_FNAME); - if (numChars == 0 || numChars >= MAX_PATH_FNAME) - { - _ASSERTE(0); // How did this fail? - } - else { - manifestPath.CloseBuffer(numChars); - if (manifestPath[manifestPath.GetCount() - 1] != W('\\')) - manifestPath.Append(W('\\')); - manifestPath.Append(W("WindowsShell.manifest")); // Other Windows components have already loaded this. - ctx.lpSource = manifestPath.GetUnicode(); - hActCtx = CreateActCtx(&ctx); - if (hActCtx != INVALID_HANDLE_VALUE) - { - if (!ActivateActCtx(hActCtx, &cookie)) - { - cookie = NULL; - _ASSERTE(0); // Why did ActivateActCtx fail? (We'll continue executing & cope with the failure.) - } - else { - activatedActivationContext = true; - // Activation context was replaced - now we can load comctl32 version 6. - hmodComctl32 = WszLoadLibrary(W("comctl32.dll")); - - if (hmodComctl32 != INVALID_HANDLE_VALUE) { - pfnTaskDialogIndirect = (decltype(TaskDialogIndirect)*)GetProcAddress(hmodComctl32, "TaskDialogIndirect"); - if (pfnTaskDialogIndirect == NULL) { - hmodComctl32.Release(); - } - } - } - } - } - - siProbedTaskDialogIndirect = (pfnTaskDialogIndirect == NULL) ? ProbedTaskDialogIndirectState_NotAvailable : ProbedTaskDialogIndirectState_Available; - mustUseMessageBox = (pfnTaskDialogIndirect == NULL); - } - - int result = MB_OK; - if (mustUseMessageBox) { - result = WszMessageBox(hWnd, message, title, uType); - } - else { - _ASSERTE(pfnTaskDialogIndirect != NULL); - int nButtonPressed = 0; - TASKDIALOGCONFIG config = {0}; - config.cbSize = sizeof(config); - config.hwndParent = hWnd; - config.dwCommonButtons = 0; - config.pszWindowTitle = title; - config.dwFlags = (uType & MB_RTLREADING) ? TDF_RTL_LAYOUT : 0; - - // Set the user-visible icon in the window. - _ASSERTE(((uType & MB_ICONMASK) == MB_ICONWARNING) || ((uType & MB_ICONMASK) == MB_ICONERROR)); - config.pszMainIcon = ((uType & MB_ICONMASK) == MB_ICONWARNING) ? TD_WARNING_ICON : TD_ERROR_ICON; - - config.pszMainInstruction = title; - config.pszContent = message; - config.pszExpandedInformation = detailedText; - - // Set up the buttons - // Note about button hot keys: Windows keeps track of of where the last input came from - // (ie, mouse or keyboard). If you use the mouse to interact w/ one dialog box and then use - // the keyboard, the next dialog will not include hot keys. This is a Windows feature to - // minimize clutter on the screen for mouse users. - _ASSERTE((uType & MB_TYPEMASK) == MB_ABORTRETRYIGNORE); - StackSString abortLabel, debugLabel, ignoreLabel; - const WCHAR *pAbortLabel, *pDebugLabel, *pIgnoreLabel; - - if (abortLabel.LoadResource(CCompRC::Optional, IDS_DIALOG_BOX_ABORT_BUTTON)) - pAbortLabel = abortLabel.GetUnicode(); - else - pAbortLabel = W("&Abort"); - if (debugLabel.LoadResource(CCompRC::Optional, IDS_DIALOG_BOX_DEBUG_BUTTON)) - pDebugLabel = debugLabel.GetUnicode(); - else - pDebugLabel = W("&Debug"); - if (ignoreLabel.LoadResource(CCompRC::Optional, IDS_DIALOG_BOX_IGNORE_BUTTON)) - pIgnoreLabel = ignoreLabel.GetUnicode(); - else - pIgnoreLabel = W("&Ignore"); - - const TASKDIALOG_BUTTON abortDebugIgnoreButtons[] = { - { IDOK, pAbortLabel }, - { IDRETRY, pDebugLabel }, - { IDIGNORE, pIgnoreLabel } - }; - config.pButtons = abortDebugIgnoreButtons; - config.cButtons = 3; - - HRESULT hr = pfnTaskDialogIndirect(&config, &nButtonPressed, NULL, NULL); - _ASSERTE(hr == S_OK); - if (hr == S_OK) { - result = nButtonPressed; - } - else { - result = IDOK; - } - - _ASSERTE(result == IDOK || result == IDRETRY || result == IDIGNORE); - } - - if (activatedActivationContext) { - DeactivateActCtx(0, cookie); - ReleaseActCtx(hActCtx); // perf isn't important so we won't bother caching the actctx - } - - return result; -#endif } int UtilMessageBoxVA( @@ -428,9 +245,6 @@ int UtilMessageBoxNonLocalizedVA( // in use. However, outside the CLR (SELF_NO_HOST) we can't assume we have resources and // in CORECLR we can't even necessarily expect that our CLR callbacks have been initialized. // This code path is used for ASSERT dialogs. -#if !defined(SELF_NO_HOST) && !defined(FEATURE_CORECLR) - uType |= GetCLRMBRTLStyle(); -#endif result = MessageBoxImpl(hWnd, formattedMessage, formattedTitle, details, uType); diff --git a/src/utilcode/utsem.cpp b/src/utilcode/utsem.cpp index 087a3aefac..4a76bbdb31 100644 --- a/src/utilcode/utsem.cpp +++ b/src/utilcode/utsem.cpp @@ -22,10 +22,10 @@ Revision History: #include "contract.h" // Consider replacing this with a #ifdef INTEROP_DEBUGGING -#if !defined(SELF_NO_HOST) && defined(_TARGET_X86_) +#if !defined(SELF_NO_HOST) && defined(_TARGET_X86_) && !defined(FEATURE_PAL) // For Interop debugging, the UTSemReadWrite class must inform the debugger // that this thread can't be suspended currently. See vm\util.hpp for the -// implementation of these methods. +// implementation of these methods. void IncCantStopCount(); void DecCantStopCount(); #else |