summaryrefslogtreecommitdiff
path: root/src/mscorlib/src/System/Text/Normalization.Windows.cs
blob: b2faf0db68b6c56b5bcdae23d535638f171852c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

namespace System.Text
{
    using System;
    using System.Security;
    using System.Globalization;
    using System.Text;
    using System.Runtime.CompilerServices;
    using System.Runtime.InteropServices;
    using System.Runtime.Versioning;
    using System.Diagnostics;
    using System.Diagnostics.Contracts;

    // This internal class wraps up our normalization behavior

    internal class Normalization
    {
        //
        // Flags that track whether given normalization form was initialized
        //
#if !FEATURE_NORM_IDNA_ONLY
        private static volatile bool NFC;
        private static volatile bool NFD;
        private static volatile bool NFKC;
        private static volatile bool NFKD;
#endif // !FEATURE_NORM_IDNA_ONLY                
        private static volatile bool IDNA;
#if !FEATURE_NORM_IDNA_ONLY        
        private static volatile bool NFCDisallowUnassigned;
        private static volatile bool NFDDisallowUnassigned;
        private static volatile bool NFKCDisallowUnassigned;
        private static volatile bool NFKDDisallowUnassigned;
#endif // !FEATURE_NORM_IDNA_ONLY    
        private static volatile bool IDNADisallowUnassigned;
        private static volatile bool Other;

        // These are error codes we get back from the Normalization DLL
        private const int ERROR_SUCCESS = 0;
        private const int ERROR_NOT_ENOUGH_MEMORY = 8;
        private const int ERROR_INVALID_PARAMETER = 87;
        private const int ERROR_INSUFFICIENT_BUFFER = 122;
        private const int ERROR_NO_UNICODE_TRANSLATION = 1113;

        static private unsafe void InitializeForm(NormalizationForm form, String strDataFile)
        {
            byte* pTables = null;

            // Normalization uses OS on Win8
            if (!Environment.IsWindows8OrAbove)
            {
                if (strDataFile == null)
                {
                    // They were supposed to have a form that we know about!
                    throw new ArgumentException(
                        Environment.GetResourceString("Argument_InvalidNormalizationForm"));
                }

                // Tell the DLL where to find our data
                pTables = GlobalizationAssembly.GetGlobalizationResourceBytePtr(
                   typeof(Normalization).Assembly, strDataFile);
                if (pTables == null)
                {
                    // Unable to load the specified normalizationForm,
                    // tables not loaded from file
                    throw new ArgumentException(
                        Environment.GetResourceString("Argument_InvalidNormalizationForm"));
                }
            }

            nativeNormalizationInitNormalization(form, pTables);
        }

        static private void EnsureInitialized(NormalizationForm form)
        {
            switch ((ExtendedNormalizationForms)form)
            {
#if !FEATURE_NORM_IDNA_ONLY
                case ExtendedNormalizationForms.FormC:
                    if (NFC) return;
                    InitializeForm(form, "normnfc.nlp");
                    NFC = true;
                    break;

                case ExtendedNormalizationForms.FormD:
                    if (NFD) return;
                    InitializeForm(form, "normnfd.nlp");
                    NFD = true;
                    break;

                case ExtendedNormalizationForms.FormKC:
                    if (NFKC) return;
                    InitializeForm(form, "normnfkc.nlp");
                    NFKC = true;
                    break;

                case ExtendedNormalizationForms.FormKD:
                    if (NFKD) return;
                    InitializeForm(form, "normnfkd.nlp");
                    NFKD = true;
                    break;
#endif // !FEATURE_NORM_IDNA_ONLY

                case ExtendedNormalizationForms.FormIdna:
                    if (IDNA) return;
                    InitializeForm(form, "normidna.nlp");
                    IDNA = true;
                    break;

#if !FEATURE_NORM_IDNA_ONLY
                case ExtendedNormalizationForms.FormCDisallowUnassigned:
                    if (NFCDisallowUnassigned) return;
                    InitializeForm(form, "normnfc.nlp");
                    NFCDisallowUnassigned = true;
                    break;

                case ExtendedNormalizationForms.FormDDisallowUnassigned:
                    if (NFDDisallowUnassigned) return;
                    InitializeForm(form, "normnfd.nlp");
                    NFDDisallowUnassigned = true;
                    break;

                case ExtendedNormalizationForms.FormKCDisallowUnassigned:
                    if (NFKCDisallowUnassigned) return;
                    InitializeForm(form, "normnfkc.nlp");
                    NFKCDisallowUnassigned = true;
                    break;

                case ExtendedNormalizationForms.FormKDDisallowUnassigned:
                    if (NFKDDisallowUnassigned) return;
                    InitializeForm(form, "normnfkd.nlp");
                    NFKDDisallowUnassigned = true;
                    break;
#endif // !FEATURE_NORM_IDNA_ONLY

                case ExtendedNormalizationForms.FormIdnaDisallowUnassigned:
                    if (IDNADisallowUnassigned) return;
                    InitializeForm(form, "normidna.nlp");
                    IDNADisallowUnassigned = true;
                    break;

                default:
                    if (Other) return;
                    InitializeForm(form, null);
                    Other = true;
                    break;
            }
        }

        internal static bool IsNormalized(String strInput, NormalizationForm normForm)
        {
            Contract.Requires(strInput != null);

            EnsureInitialized(normForm);

            int iError = ERROR_SUCCESS;
            bool result = nativeNormalizationIsNormalizedString(
                                normForm, 
                                ref iError, 
                                strInput, 
                                strInput.Length);

            switch(iError)
            {
                // Success doesn't need to do anything
                case ERROR_SUCCESS:
                    break;

                // Do appropriate stuff for the individual errors:
                case ERROR_INVALID_PARAMETER:
                case ERROR_NO_UNICODE_TRANSLATION:
                    throw new ArgumentException(
                        Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex" ),
                        nameof(strInput));
                case ERROR_NOT_ENOUGH_MEMORY:
                    throw new OutOfMemoryException(
                        Environment.GetResourceString("Arg_OutOfMemoryException"));
                default:
                    throw new InvalidOperationException(
                        Environment.GetResourceString("UnknownError_Num", iError));
            }

            return result;
        }

        internal static String Normalize(String strInput, NormalizationForm normForm)
        {
            Contract.Requires(strInput != null);

            EnsureInitialized(normForm);

            int iError = ERROR_SUCCESS;

            // Guess our buffer size first
            int iLength = nativeNormalizationNormalizeString(normForm, ref iError, strInput, strInput.Length, null, 0);

            // Could have an error (actually it'd be quite hard to have an error here)
            if (iError != ERROR_SUCCESS)
            {
                if (iError == ERROR_INVALID_PARAMETER)
                    throw new ArgumentException(
                        Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex" ),
                        nameof(strInput));

                // We shouldn't really be able to get here..., guessing length is
                // a trivial math function...
                // Can't really be Out of Memory, but just in case:
                if (iError == ERROR_NOT_ENOUGH_MEMORY)
                    throw new OutOfMemoryException(
                        Environment.GetResourceString("Arg_OutOfMemoryException"));

                // Who knows what happened?  Not us!
                throw new InvalidOperationException(
                    Environment.GetResourceString("UnknownError_Num", iError));
            }

            // Don't break for empty strings (only possible for D & KD and not really possible at that)
            if (iLength == 0) return String.Empty;

            // Someplace to stick our buffer
            char[] cBuffer = null;

            for (;;)
            {
                // (re)allocation buffer and normalize string
                cBuffer = new char[iLength];

                iLength = nativeNormalizationNormalizeString(
                                    normForm, 
                                    ref iError,
                                    strInput, 
                                    strInput.Length, 
                                    cBuffer, 
                                    cBuffer.Length);
                
                if (iError == ERROR_SUCCESS)
                    break;

                // Could have an error (actually it'd be quite hard to have an error here)
                switch(iError)
                {
                    // Do appropriate stuff for the individual errors:
                    case ERROR_INSUFFICIENT_BUFFER:
                        Debug.Assert(iLength > cBuffer.Length, "Buffer overflow should have iLength > cBuffer.Length");
                        continue;

                    case ERROR_INVALID_PARAMETER:
                    case ERROR_NO_UNICODE_TRANSLATION:
                        // Illegal code point or order found.  Ie: FFFE or D800 D800, etc.
                        throw new ArgumentException(
                            Environment.GetResourceString("Argument_InvalidCharSequence", iLength ),
                            nameof(strInput));
                    case ERROR_NOT_ENOUGH_MEMORY:
                        throw new OutOfMemoryException(
                            Environment.GetResourceString("Arg_OutOfMemoryException"));

                    default:
                        // We shouldn't get here...
                        throw new InvalidOperationException(
                            Environment.GetResourceString("UnknownError_Num", iError));
                }
            }

            // Copy our buffer into our new string, which will be the appropriate size
            return new String(cBuffer, 0, iLength);
        }

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        unsafe private static extern int nativeNormalizationNormalizeString(
            NormalizationForm normForm, ref int iError,
            String lpSrcString, int cwSrcLength,
            char[] lpDstString, int cwDstLength);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        unsafe private static extern bool nativeNormalizationIsNormalizedString(
            NormalizationForm normForm, ref int iError,
            String lpString, int cwLength);

        [SuppressUnmanagedCodeSecurity]
        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        unsafe private static extern void nativeNormalizationInitNormalization(
            NormalizationForm normForm, byte* pTableData);
    }
}