[MWF] Fix unicode string handling from clipboard paste in X11
authorAlexander Köplinger <alex.koeplinger@outlook.com>
Wed, 14 Jan 2015 11:02:37 +0000 (12:02 +0100)
committerAlexander Köplinger <alex.koeplinger@outlook.com>
Wed, 14 Jan 2015 21:31:30 +0000 (22:31 +0100)
commit9c05594fc5a5edc78e4aac893b11acb5b84191e1
tree19c96510942543e52881c237f0125268568e7500
parent7299191d967869fc7b406b212e0ee928a3358e58
[MWF] Fix unicode string handling from clipboard paste in X11

In the TextBoxTest.PasteTest () test case we copy the string "ABCD" to the clipboard.
We then try to paste it again and see if it's the same.

Internally in WinForms, the clipboard data is retrieved via an X11 API that returns
a pointer to the string. In this case, we have a unicode/utf16 string that usually
looks as follows in memory (2 byte per character):

65  'A'
0
-
66  'B'
0
-
67  'C'
0
-
68  'D'
0
-
0   '\0' end of string
0   potential garbage from here on
-
0
0
...

The bug is that we use Marshal.PtrToStringUni (), which reads until the
first null *char* not the first null *byte*.

Imagine if we get the following (happens sometimes):

65  'A'
0
-
66  'B'
0
-
67  'C'
0
-
68  'D'
0
-
0   '\0' end of string
230 <--- garbage, but considered part of a char by PtrToStringUni ()
-
47
56
-
74
43
...

This produces garbage like "ABCD㠯⭊" since PtrToStringUni () reads beyond the original string.

The fix is to use the nitems variable that is returned by the X11 API (it contains the
actual number of bytes in the string) and copy the bytes manually. We already do
the same for the UTF8 case above.

This fixes the TextBoxTest.PasteTest () that intermittently fails on Jenkins.
mcs/class/Managed.Windows.Forms/System.Windows.Forms/XplatUIX11.cs