diff --git a/include/dxc/WinAdapter.h b/include/dxc/WinAdapter.h index d02ad1ac38..7329b35878 100644 --- a/include/dxc/WinAdapter.h +++ b/include/dxc/WinAdapter.h @@ -916,7 +916,7 @@ unsigned int SysStringLen(const BSTR bstrString); // RAII style mechanism for setting/unsetting a locale for the specified Windows // codepage class ScopedLocale { - const char *m_prevLocale; + std::string m_prevLocale; public: explicit ScopedLocale(uint32_t codePage) @@ -925,11 +925,7 @@ class ScopedLocale { "Support for Linux only handles UTF8 code pages"); setlocale(LC_ALL, "en_US.UTF-8"); } - ~ScopedLocale() { - if (m_prevLocale != nullptr) { - setlocale(LC_ALL, m_prevLocale); - } - } + ~ScopedLocale() { setlocale(LC_ALL, m_prevLocale.c_str()); } }; // The t_nBufferLength parameter is part of the published interface, but not @@ -937,13 +933,13 @@ class ScopedLocale { template class CW2AEX { public: CW2AEX(LPCWSTR psz) { - ScopedLocale locale(CP_UTF8); - if (!psz) { m_psz = NULL; return; } + ScopedLocale locale(CP_UTF8); + int len = (wcslen(psz) + 1) * 4; m_psz = new char[len]; std::wcstombs(m_psz, psz, len); @@ -962,13 +958,13 @@ typedef CW2AEX<> CW2A; template class CA2WEX { public: CA2WEX(LPCSTR psz) { - ScopedLocale locale(CP_UTF8); - if (!psz) { m_psz = NULL; return; } + ScopedLocale locale(CP_UTF8); + int len = strlen(psz) + 1; m_psz = new wchar_t[len]; std::mbstowcs(m_psz, psz, len); diff --git a/lib/DxcSupport/Unicode.cpp b/lib/DxcSupport/Unicode.cpp index 1481ae27ff..98523a0f4c 100644 --- a/lib/DxcSupport/Unicode.cpp +++ b/lib/DxcSupport/Unicode.cpp @@ -52,8 +52,7 @@ int MultiByteToWideChar(uint32_t /*CodePage*/, uint32_t /*dwFlags*/, } size_t rv; - const char *prevLocale = setlocale(LC_ALL, nullptr); - setlocale(LC_ALL, "en_US.UTF-8"); + ScopedLocale locale(CP_UTF8); if (lpMultiByteStr[cbMultiByte - 1] != '\0') { char *srcStr = (char *)malloc((cbMultiByte + 1) * sizeof(char)); strncpy(srcStr, lpMultiByteStr, cbMultiByte); @@ -64,9 +63,6 @@ int MultiByteToWideChar(uint32_t /*CodePage*/, uint32_t /*dwFlags*/, rv = mbstowcs(lpWideCharStr, lpMultiByteStr, cchWideChar); } - if (prevLocale) - setlocale(LC_ALL, prevLocale); - if (rv == (size_t)cbMultiByte) return rv; return rv + 1; // mbstowcs excludes the terminating character @@ -108,8 +104,7 @@ int WideCharToMultiByte(uint32_t /*CodePage*/, uint32_t /*dwFlags*/, } size_t rv; - const char *prevLocale = setlocale(LC_ALL, nullptr); - setlocale(LC_ALL, "en_US.UTF-8"); + ScopedLocale locale(CP_UTF8); if (lpWideCharStr[cchWideChar - 1] != L'\0') { wchar_t *srcStr = (wchar_t *)malloc((cchWideChar + 1) * sizeof(wchar_t)); wcsncpy(srcStr, lpWideCharStr, cchWideChar); @@ -120,9 +115,6 @@ int WideCharToMultiByte(uint32_t /*CodePage*/, uint32_t /*dwFlags*/, rv = wcstombs(lpMultiByteStr, lpWideCharStr, cbMultiByte); } - if (prevLocale) - setlocale(LC_ALL, prevLocale); - if (rv == (size_t)cchWideChar) return rv; return rv + 1; // mbstowcs excludes the terminating character