Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix MultiByte <-> WideChar conversion return value on linux #6725

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions lib/DxcSupport/Unicode.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ 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");
if (lpMultiByteStr[cbMultiByte - 1] != '\0') {
const bool bIsNullTerminated = lpMultiByteStr[cbMultiByte - 1] == '\0';
if (!bIsNullTerminated) {
char *srcStr = (char *)malloc((cbMultiByte + 1) * sizeof(char));
strncpy(srcStr, lpMultiByteStr, cbMultiByte);
srcStr[cbMultiByte] = '\0';
Expand All @@ -67,9 +68,9 @@ int MultiByteToWideChar(uint32_t /*CodePage*/, uint32_t /*dwFlags*/,
if (prevLocale)
setlocale(LC_ALL, prevLocale);

if (rv == (size_t)cbMultiByte)
return rv;
return rv + 1; // mbstowcs excludes the terminating character
if (bIsNullTerminated)
return rv + 1; // mbstowcs excludes the terminating character
return rv;
}

// WideCharToMultiByte is a Windows-specific method.
Expand Down Expand Up @@ -110,7 +111,8 @@ 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");
if (lpWideCharStr[cchWideChar - 1] != L'\0') {
const bool bIsNullTerminated = lpWideCharStr[cchWideChar - 1] == L'\0';
if (!bIsNullTerminated) {
wchar_t *srcStr = (wchar_t *)malloc((cchWideChar + 1) * sizeof(wchar_t));
wcsncpy(srcStr, lpWideCharStr, cchWideChar);
srcStr[cchWideChar] = L'\0';
Expand All @@ -123,9 +125,9 @@ int WideCharToMultiByte(uint32_t /*CodePage*/, uint32_t /*dwFlags*/,
if (prevLocale)
setlocale(LC_ALL, prevLocale);

if (rv == (size_t)cchWideChar)
return rv;
return rv + 1; // mbstowcs excludes the terminating character
if (bIsNullTerminated)
return rv + 1; // mbstowcs excludes the terminating character
return rv;
}
#endif // _WIN32

Expand Down
Loading