Fix call to GetSortHandle (#4882)
authorMatt Ellis <matell@microsoft.com>
Tue, 10 May 2016 05:33:20 +0000 (22:33 -0700)
committerJan Kotas <jkotas@microsoft.com>
Tue, 10 May 2016 05:33:20 +0000 (22:33 -0700)
GlobalizationNatvie_GetSortHandle takes a UTF8 encoded string for the
locale name we want to construct a handle to, which is passed to ICU to
open some locale data.

We converted the UTF-16 encoded locale name to UTF8 in managed code, but
neglected to actually ensure the resulting value was null terminated.

Fixes #4784

src/mscorlib/corefx/System/Globalization/CompareInfo.Unix.cs

index 2431e38..bc4623c 100644 (file)
@@ -21,7 +21,7 @@ namespace System.Globalization
         {
             m_name = culture.m_name;
             m_sortName = culture.SortName;
-            m_sortHandle = Interop.GlobalizationInterop.GetSortHandle(System.Text.Encoding.UTF8.GetBytes(m_sortName));
+            m_sortHandle = Interop.GlobalizationInterop.GetSortHandle(GetNullTerminatedUtf8String(m_sortName));
             m_isAsciiEqualityOrdinal = (m_sortName == "en-US" || m_sortName == "");
         }
 
@@ -298,5 +298,19 @@ namespace System.Globalization
             // Unlike the other Ignore options, IgnoreSymbols impacts ASCII characters (e.g. ').
             return (options & CompareOptions.IgnoreSymbols) == 0;
         }
+
+        private static byte[] GetNullTerminatedUtf8String(string s)
+        {
+            int byteLen = System.Text.Encoding.UTF8.GetByteCount(s);
+
+            // Allocate an extra byte (which defaults to 0) as the null terminator.
+            byte[] buffer = new byte[byteLen + 1];
+
+            int bytesWritten = System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, buffer, 0);
+
+            Contract.Assert(bytesWritten == byteLen);
+
+            return buffer;
+        }
     }
 }