Debian Codegraph @

pypy/module/_codecs/locale_codec.c

raw symbols SCIP
1 /* From CPython 3.2.3's fileutils.c, and _Py_normalize_encoding from
2 unicodeobject.c
3 */
4 /*
5 #include "Python.h"
6 */
7 #include <ctype.h>
8 #include <stdlib.h>
9 #include <stdio.h>
10 #include <string.h>
11 #include <wchar.h>
12 #ifdef _MSC_VER
13 #define MS_WINDOWS
14 #endif
15 #define PyMem_Malloc malloc
16 #define PyMem_Free free
17 /* C99 but recent Windows has it */
18 #define HAVE_MBRTOWC 1
19
20 #ifdef MS_WINDOWS
21 # include <windows.h>
22 #else
23 #include <locale.h>
24 #define HAVE_LANGINFO_H
25 #endif
26
27 #ifdef HAVE_LANGINFO_H
28 #include <locale.h>
29 #include <langinfo.h>
30 #endif
31 #include "locale_codec.h"
32
33 #if 0 && defined(__APPLE__)
34 extern wchar_t* _Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size);
35 #endif
36
37 #if !defined(__APPLE__) && !defined(MS_WINDOWS)
38 extern int _pypy_normalize_encoding(const char *, char *, size_t);
39
40 /* Workaround FreeBSD and OpenIndiana locale encoding issue with the C locale.
41 On these operating systems, nl_langinfo(CODESET) announces an alias of the
42 ASCII encoding, whereas mbstowcs() and wcstombs() functions use the
43 ISO-8859-1 encoding. The problem is that os.fsencode() and os.fsdecode() use
44 locale.getpreferredencoding() codec. For example, if command line arguments
45 are decoded by mbstowcs() and encoded back by os.fsencode(), we get a
46 UnicodeEncodeError instead of retrieving the original byte string.
47
48 The workaround is enabled if setlocale(LC_CTYPE, NULL) returns "C",
49 nl_langinfo(CODESET) announces "ascii" (or an alias to ASCII), and at least
50 one byte in range 0x80-0xff can be decoded from the locale encoding. The
51 workaround is also enabled on error, for example if getting the locale
52 failed.
53
54 Values of locale_is_ascii:
55
56 1: the workaround is used: _Py_wchar2char() uses
57 encode_ascii_surrogateescape() and _Py_char2wchar() uses
58 decode_ascii_surrogateescape()
59 0: the workaround is not used: _Py_wchar2char() uses wcstombs() and
60 _Py_char2wchar() uses mbstowcs()
61 -1: unknown, need to call check_force_ascii() to get the value
62 */
63 static int force_ascii = -1;
64
65 static int
66 _pypy_check_force_ascii(void)
67 {
68 char *loc;
69 #if defined(HAVE_LANGINFO_H) && defined(CODESET)
70 char *codeset, **alias;
71 char encoding[100];
72 int is_ascii;
73 unsigned int i;
74 char* ascii_aliases[] = {
75 "ascii",
76 "646",
77 "ansi-x3.4-1968",
78 "ansi-x3-4-1968",
79 "ansi-x3.4-1986",
80 "cp367",
81 "csascii",
82 "ibm367",
83 "iso646-us",
84 "iso-646.irv-1991",
85 "iso-ir-6",
86 "us",
87 "us-ascii",
88 NULL
89 };
90 #endif
91
92 setlocale(LC_CTYPE, "");
93 loc = setlocale(LC_CTYPE, NULL);
94 if (loc == NULL)
95 goto error;
96 if (strcmp(loc, "C") != 0) {
97 /* the LC_CTYPE locale is different than C */
98 return 0;
99 }
100
101 #if defined(HAVE_LANGINFO_H) && defined(CODESET)
102 codeset = nl_langinfo(CODESET);
103 if (!codeset || codeset[0] == '\0') {
104 /* CODESET is not set or empty */
105 goto error;
106 }
107 if (!_pypy_normalize_encoding(codeset, encoding, sizeof(encoding)))
108 goto error;
109
110 is_ascii = 0;
111 for (alias=ascii_aliases; *alias != NULL; alias++) {
112 if (strcmp(encoding, *alias) == 0) {
113 is_ascii = 1;
114 break;
115 }
116 }
117 if (!is_ascii) {
118 /* nl_langinfo(CODESET) is not "ascii" or an alias of ASCII */
119 return 0;
120 }
121
122 for (i=0x80; i<0xff; i++) {
123 unsigned char ch;
124 wchar_t wch;
125 size_t res;
126
127 ch = (unsigned char)i;
128 res = mbstowcs(&wch, (char*)&ch, 1);
129 if (res != (size_t)-1) {
130 /* decoding a non-ASCII character from the locale encoding succeed:
131 the locale encoding is not ASCII, force ASCII */
132 return 1;
133 }
134 }
135 /* None of the bytes in the range 0x80-0xff can be decoded from the locale
136 encoding: the locale encoding is really ASCII */
137 return 0;
138 #else
139 /* nl_langinfo(CODESET) is not available: always force ASCII */
140 return 1;
141 #endif
142
143 error:
144 /* if an error occured, force the ASCII encoding */
145 return 1;
146 }
147
148 static char*
149 _pypy_encode_ascii_surrogateescape(const wchar_t *text, size_t *error_pos)
150 {
151 char *result = NULL, *out;
152 size_t len, i;
153 wchar_t ch;
154
155 if (error_pos != NULL)
156 *error_pos = (size_t)-1;
157
158 len = wcslen(text);
159
160 result = PyMem_Malloc(len + 1); /* +1 for NUL byte */
161 if (result == NULL)
162 return NULL;
163
164 out = result;
165 for (i=0; i<len; i++) {
166 ch = text[i];
167
168 if (ch <= 0x7f) {
169 /* ASCII character */
170 *out++ = (char)ch;
171 }
172 else if (0xdc80 <= ch && ch <= 0xdcff) {
173 /* UTF-8b surrogate */
174 *out++ = (char)(ch - 0xdc00);
175 }
176 else {
177 if (error_pos != NULL)
178 *error_pos = i;
179 PyMem_Free(result);
180 return NULL;
181 }
182 }
183 *out = '\0';
184 return result;
185 }
186 #endif /* !defined(__APPLE__) && !defined(MS_WINDOWS) */
187
188 #if !defined(__APPLE__) && (!defined(MS_WINDOWS) || !defined(HAVE_MBRTOWC))
189 static wchar_t*
190 _pypy_decode_ascii_surrogateescape(const char *arg, size_t *size)
191 {
192 wchar_t *res;
193 unsigned char *in;
194 wchar_t *out;
195
196 res = PyMem_Malloc((strlen(arg)+1)*sizeof(wchar_t));
197 if (!res)
198 return NULL;
199
200 in = (unsigned char*)arg;
201 out = res;
202 while(*in)
203 if(*in < 128)
204 *out++ = *in++;
205 else
206 *out++ = 0xdc00 + *in++;
207 *out = 0;
208 if (size != NULL)
209 *size = out - res;
210 return res;
211 }
212 #endif
213
214
215 /* Decode a byte string from the locale encoding with the
216 surrogateescape error handler (undecodable bytes are decoded as characters
217 in range U+DC80..U+DCFF). If a byte sequence can be decoded as a surrogate
218 character, escape the bytes using the surrogateescape error handler instead
219 of decoding them.
220
221 Use _Py_wchar2char() to encode the character string back to a byte string.
222
223 Return a pointer to a newly allocated wide character string (use
224 PyMem_Free() to free the memory) and write the number of written wide
225 characters excluding the null character into *size if size is not NULL, or
226 NULL on error (conversion or memory allocation error).
227
228 Conversion errors should never happen, unless there is a bug in the C
229 library. */
230 wchar_t*
231 pypy_char2wchar(const char* arg, size_t *size)
232 {
233 wchar_t *res;
234 size_t argsize;
235 size_t count;
236 unsigned char *in;
237 wchar_t *out;
238 #ifdef HAVE_MBRTOWC
239 mbstate_t mbs;
240 #endif
241
242 #if !defined(__APPLE__) && !defined(MS_WINDOWS)
243 /*#ifndef MS_WINDOWS*/
244 if (force_ascii == -1)
245 force_ascii = _pypy_check_force_ascii();
246
247 if (force_ascii) {
248 /* force ASCII encoding to workaround mbstowcs() issue */
249 res = _pypy_decode_ascii_surrogateescape(arg, size);
250 if (res == NULL)
251 goto oom;
252 return res;
253 }
254 #endif
255
256 #ifdef HAVE_BROKEN_MBSTOWCS
257 /* Some platforms have a broken implementation of
258 * mbstowcs which does not count the characters that
259 * would result from conversion. Use an upper bound.
260 */
261 argsize = strlen(arg);
262 #else
263 argsize = mbstowcs(NULL, arg, 0);
264 #endif
265 if (argsize != (size_t)-1) {
266 res = (wchar_t *)PyMem_Malloc((argsize+1)*sizeof(wchar_t));
267 if (!res)
268 goto oom;
269 count = mbstowcs(res, arg, argsize+1);
270 if (count != (size_t)-1) {
271 wchar_t *tmp;
272 /* Only use the result if it contains no
273 surrogate characters. */
274 for (tmp = res; *tmp != 0 &&
275 (*tmp < 0xd800 || *tmp > 0xdfff); tmp++)
276 ;
277 if (*tmp == 0) {
278 if (size != NULL)
279 *size = count;
280 return res;
281 }
282 }
283 PyMem_Free(res);
284 }
285 /* Conversion failed. Fall back to escaping with surrogateescape. */
286 #ifdef HAVE_MBRTOWC
287 /* Try conversion with mbrtwoc (C99), and escape non-decodable bytes. */
288
289 /* Overallocate; as multi-byte characters are in the argument, the
290 actual output could use less memory. */
291 argsize = strlen(arg) + 1;
292 res = (wchar_t*)PyMem_Malloc(argsize*sizeof(wchar_t));
293 if (!res)
294 goto oom;
295 in = (unsigned char*)arg;
296 out = res;
297 memset(&mbs, 0, sizeof mbs);
298 while (argsize) {
299 size_t converted = mbrtowc(out, (char *)in, argsize, &mbs);
300 if (converted == 0) {
301 /* Reached end of string; null char stored. */
302 break;
303 }
304 if (converted == (size_t)-2) {
305 /* Incomplete character. This should never happen,
306 since we provide everything that we have -
307 unless there is a bug in the C library, or I
308 misunderstood how mbrtowc works. */
309 fprintf(stderr, "unexpected mbrtowc result -2\n");
310 PyMem_Free(res);
311 return NULL;
312 }
313 if (converted == (size_t)-1) {
314 /* Conversion error. Escape as UTF-8b, and start over
315 in the initial shift state. */
316 *out++ = 0xdc00 + *in++;
317 argsize--;
318 memset(&mbs, 0, sizeof mbs);
319 continue;
320 }
321 if ((*out >= 0xd800 && *out <= 0xdfff) || *out > 0x10ffff) {
322 /* bpo-35883: glibc mbstowcs() can return values above 0x10ffff */
323 /* Surrogate character. Escape the original
324 byte sequence with surrogateescape. */
325 argsize -= converted;
326 while (converted--)
327 *out++ = 0xdc00 + *in++;
328 continue;
329 }
330 /* successfully converted some bytes */
331 in += converted;
332 argsize -= converted;
333 out++;
334 }
335 if (size != NULL)
336 *size = out - res;
337 #else /* HAVE_MBRTOWC */
338 /* Cannot use C locale for escaping; manually escape as if charset
339 is ASCII (i.e. escape all bytes > 128. This will still roundtrip
340 correctly in the locale's charset, which must be an ASCII superset. */
341 res = _pypy_decode_ascii_surrogateescape(arg, size);
342 if (res == NULL)
343 goto oom;
344 #endif /* HAVE_MBRTOWC */
345 return res;
346 oom:
347 fprintf(stderr, "out of memory\n");
348 return NULL;
349 }
350
351 /* Decode a byte string from the locale encoding with the
352 strict error handler: in other words fail to decode.
353
354 Use pypy_wchar2char_strict() to encode the character string back to a byte
355 string.
356
357 Return a pointer to a newly allocated wide character string (use
358 PyMem_Free() to free the memory) and write the number of written wide
359 characters excluding the null character into *size if size is not NULL, or
360 NULL on error (conversion or memory allocation error).
361
362 */
363 wchar_t*
364 pypy_char2wchar_strict(const char* arg, size_t *size)
365 {
366 wchar_t *res;
367 size_t argsize;
368 size_t count;
369 unsigned char *in;
370 wchar_t *out;
371 #ifdef HAVE_MBRTOWC
372 mbstate_t mbs;
373 #endif
374
375 #if !defined(__APPLE__) && !defined(MS_WINDOWS)
376 /*#ifndef MS_WINDOWS*/
377 if (force_ascii == -1)
378 force_ascii = _pypy_check_force_ascii();
379
380 if (force_ascii) {
381 /* force ASCII encoding to workaround mbstowcs() issue */
382 res = _pypy_decode_ascii_surrogateescape(arg, size);
383 if (res == NULL)
384 goto oom;
385 return res;
386 }
387 #endif
388
389 #ifdef HAVE_BROKEN_MBSTOWCS
390 /* Some platforms have a broken implementation of
391 * mbstowcs which does not count the characters that
392 * would result from conversion. Use an upper bound.
393 */
394 argsize = strlen(arg);
395 #else
396 argsize = mbstowcs(NULL, arg, 0);
397 #endif
398 if (argsize == (size_t)-1) {
399 return NULL;
400 }
401 res = (wchar_t *)PyMem_Malloc((argsize+1)*sizeof(wchar_t));
402 if (!res)
403 goto oom;
404 count = mbstowcs(res, arg, argsize+1);
405 if (count == (size_t)-1) {
406 return NULL;
407 PyMem_Free(res);
408 }
409 size[0] = count;
410 return res;
411 oom:
412 fprintf(stderr, "out of memory\n");
413 return NULL;
414 }
415
416 /* Encode a (wide) character string to the locale encoding with the
417 surrogateescape error handler (characters in range U+DC80..U+DCFF are
418 converted to bytes 0x80..0xFF).
419
420 This function is the reverse of _Py_char2wchar().
421
422 Return a pointer to a newly allocated byte string (use PyMem_Free() to free
423 the memory), or NULL on conversion or memory allocation error.
424
425 If error_pos is not NULL: *error_pos is the index of the invalid character
426 on conversion error, or (size_t)-1 otherwise. */
427 char*
428 pypy_wchar2char(const wchar_t *text, size_t *error_pos)
429 {
430 const size_t len = wcslen(text);
431 char *result = NULL, *bytes = NULL;
432 size_t i, size, converted;
433 wchar_t c, buf[2];
434
435 #if !defined(__APPLE__) && !defined(MS_WINDOWS)
436 /*#ifndef MS_WINDOWS*/
437 if (force_ascii == -1)
438 force_ascii = _pypy_check_force_ascii();
439
440 if (force_ascii)
441 return _pypy_encode_ascii_surrogateescape(text, error_pos);
442 #endif
443
444 /* The function works in two steps:
445 1. compute the length of the output buffer in bytes (size)
446 2. outputs the bytes */
447 size = 0;
448 buf[1] = 0;
449 while (1) {
450 for (i=0; i < len; i++) {
451 c = text[i];
452 if (c >= 0xdc80 && c <= 0xdcff) {
453 /* UTF-8b surrogate */
454 if (bytes != NULL) {
455 *bytes++ = c - 0xdc00;
456 size--;
457 }
458 else
459 size++;
460 continue;
461 }
462 else {
463 buf[0] = c;
464 if (bytes != NULL)
465 converted = wcstombs(bytes, buf, size);
466 else
467 converted = wcstombs(NULL, buf, 0);
468 if (converted == (size_t)-1) {
469 if (result != NULL)
470 PyMem_Free(result);
471 if (error_pos != NULL)
472 *error_pos = i;
473 return NULL;
474 }
475 if (bytes != NULL) {
476 bytes += converted;
477 size -= converted;
478 }
479 else
480 size += converted;
481 }
482 }
483 if (result != NULL) {
484 *bytes = '\0';
485 break;
486 }
487
488 size += 1; /* nul byte at the end */
489 result = PyMem_Malloc(size);
490 if (result == NULL) {
491 if (error_pos != NULL)
492 *error_pos = (size_t)-1;
493 return NULL;
494 }
495 bytes = result;
496 }
497 return result;
498 }
499
500 /* Encode a (wide) character string to the locale encoding with the
501 strict error handler.
502
503 This function is the reverse of pypy_char2wchar_strict().
504
505 Return a pointer to a newly allocated byte string (use PyMem_Free() to free
506 the memory), or NULL on conversion or memory allocation error.
507
508 If error_pos is not NULL: *error_pos is the index of the invalid character
509 on conversion error, or (size_t)-1 otherwise. */
510 char*
511 pypy_wchar2char_strict(const wchar_t *wstr, size_t *error_pos)
512 {
513 size_t len, len2;
514 char *result = NULL;
515
516 #if !defined(__APPLE__) && !defined(MS_WINDOWS)
517 /*#ifndef MS_WINDOWS*/
518 if (force_ascii == -1)
519 force_ascii = _pypy_check_force_ascii();
520
521 if (force_ascii)
522 return _pypy_encode_ascii_surrogateescape(wstr, error_pos);
523 #endif
524 len = wcstombs(NULL, wstr, 0);
525 if (len == (size_t)-1) {
526 error_pos[0] = (size_t)-1;
527 return NULL;
528 }
529 result = PyMem_Malloc(len + 1);
530 len2 = wcstombs(result, wstr, len+1);
531 if (len2 == (size_t)-1 || len2 > len) {
532 error_pos[0] = (size_t)-1;
533 PyMem_Free(result);
534 return NULL;
535 }
536 return result;
537 }
538
539 void
540 pypy_char2wchar_free(wchar_t *text)
541 {
542 PyMem_Free(text);
543 }
544
545 void
546 pypy_wchar2char_free(char *bytes)
547 {
548 PyMem_Free(bytes);
549 }
550
551 #define Py_ISUPPER isupper
552 #define Py_TOLOWER tolower
553
554 /* Convert encoding to lower case and replace '_' with '-' in order to
555 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
556 1 on success. */
557 int
558 _pypy_normalize_encoding(const char *encoding,
559 char *lower,
560 size_t lower_len)
561 {
562 const char *e;
563 char *l;
564 char *l_end;
565
566 e = encoding;
567 l = lower;
568 l_end = &lower[lower_len - 1];
569 while (*e) {
570 if (l == l_end)
571 return 0;
572 if (Py_ISUPPER(*e)) {
573 *l++ = Py_TOLOWER(*e++);
574 }
575 else if (*e == '_') {
576 *l++ = '-';
577 e++;
578 }
579 else {
580 *l++ = *e++;
581 }
582 }
583 *l = '\0';
584 return 1;
585 }