From 039bc2cfbeac35557eeaeb769a2d715e21f41705 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florin=20Cri=C8=99an?= Date: Tue, 15 Jun 2021 13:08:14 +0300 Subject: [PATCH] fix #7074 Safely handle setlocale `setlocale` returns a pointer to a buffer containing the current locale name. This needs to be copied into a `std::string` or it will be overwritten by the next call. Trying to call `setlocale` with a non-null, invalid pointer can have unpredictable results, such as ``` [ RUN ] StringPrintfTest.Multibyte minkernel\crts\ucrt\src\appcrt\convert\mbstowcs.cpp(246) : Assertion failed: (pwcs == nullptr && sizeInWords == 0) || (pwcs != nullptr && sizeInWords > 0) ``` `setlocale` can also return a `nullptr` if it fails, but we assert against that. --- src/google/protobuf/stubs/stringprintf_unittest.cc | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/google/protobuf/stubs/stringprintf_unittest.cc b/src/google/protobuf/stubs/stringprintf_unittest.cc index 37172a9d9702..a42f9457df41 100644 --- a/src/google/protobuf/stubs/stringprintf_unittest.cc +++ b/src/google/protobuf/stubs/stringprintf_unittest.cc @@ -91,7 +91,9 @@ TEST(StringPrintfTest, Multibyte) { // out of memory while trying to determine destination buffer size. // see b/4194543. - char* old_locale = setlocale(LC_CTYPE, nullptr); + char* old_locale_c = setlocale(LC_CTYPE, nullptr); + ASSERT_TRUE(old_locale_c != nullptr); + std::string old_locale = old_locale_c; // Push locale with multibyte mode setlocale(LC_CTYPE, "en_US.utf8"); @@ -115,15 +117,17 @@ TEST(StringPrintfTest, Multibyte) { EXPECT_TRUE(value.empty() || value == buf); delete[] buf; - setlocale(LC_CTYPE, old_locale); + setlocale(LC_CTYPE, old_locale.c_str()); } TEST(StringPrintfTest, NoMultibyte) { // No multibyte handling, but the string contains funny chars. - char* old_locale = setlocale(LC_CTYPE, nullptr); + char* old_locale_c = setlocale(LC_CTYPE, nullptr); + ASSERT_TRUE(old_locale_c != nullptr); + std::string old_locale = old_locale_c; setlocale(LC_CTYPE, "POSIX"); std::string value = StringPrintf("%.*s", 3, "\375\067s"); - setlocale(LC_CTYPE, old_locale); + setlocale(LC_CTYPE, old_locale.c_str()); EXPECT_EQ("\375\067s", value); }