This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Add -DL option to trace setlocale calls
[perl5.git] / locale.c
1 /*    locale.c
2  *
3  *    Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
4  *    2002, 2003, 2005, 2006, 2007, 2008 by Larry Wall and others
5  *
6  *    You may distribute under the terms of either the GNU General Public
7  *    License or the Artistic License, as specified in the README file.
8  *
9  */
10
11 /*
12  *      A Elbereth Gilthoniel,
13  *      silivren penna míriel
14  *      o menel aglar elenath!
15  *      Na-chaered palan-díriel
16  *      o galadhremmin ennorath,
17  *      Fanuilos, le linnathon
18  *      nef aear, si nef aearon!
19  *
20  *     [p.238 of _The Lord of the Rings_, II/i: "Many Meetings"]
21  */
22
23 /* utility functions for handling locale-specific stuff like what
24  * character represents the decimal point.
25  *
26  * All C programs have an underlying locale.  Perl generally doesn't pay any
27  * attention to it except within the scope of a 'use locale'.  For most
28  * categories, it accomplishes this by just using different operations if it is
29  * in such scope than if not.  However, various libc functions called by Perl
30  * are affected by the LC_NUMERIC category, so there are macros in perl.h that
31  * are used to toggle between the current locale and the C locale depending on
32  * the desired behavior of those functions at the moment.
33  */
34
35 #include "EXTERN.h"
36 #define PERL_IN_LOCALE_C
37 #include "perl.h"
38
39 #ifdef I_LANGINFO
40 #   include <langinfo.h>
41 #endif
42
43 #include "reentr.h"
44
45 #ifdef USE_LOCALE
46
47 /*
48  * Standardize the locale name from a string returned by 'setlocale', possibly
49  * modifying that string.
50  *
51  * The typical return value of setlocale() is either
52  * (1) "xx_YY" if the first argument of setlocale() is not LC_ALL
53  * (2) "xa_YY xb_YY ..." if the first argument of setlocale() is LC_ALL
54  *     (the space-separated values represent the various sublocales,
55  *      in some unspecified order).  This is not handled by this function.
56  *
57  * In some platforms it has a form like "LC_SOMETHING=Lang_Country.866\n",
58  * which is harmful for further use of the string in setlocale().  This
59  * function removes the trailing new line and everything up through the '='
60  *
61  */
62 STATIC char *
63 S_stdize_locale(pTHX_ char *locs)
64 {
65     const char * const s = strchr(locs, '=');
66     bool okay = TRUE;
67
68     PERL_ARGS_ASSERT_STDIZE_LOCALE;
69
70     if (s) {
71         const char * const t = strchr(s, '.');
72         okay = FALSE;
73         if (t) {
74             const char * const u = strchr(t, '\n');
75             if (u && (u[1] == 0)) {
76                 const STRLEN len = u - s;
77                 Move(s + 1, locs, len, char);
78                 locs[len] = 0;
79                 okay = TRUE;
80             }
81         }
82     }
83
84     if (!okay)
85         Perl_croak(aTHX_ "Can't fix broken locale name \"%s\"", locs);
86
87     return locs;
88 }
89
90 #endif
91
92 void
93 Perl_set_numeric_radix(pTHX)
94 {
95 #ifdef USE_LOCALE_NUMERIC
96     dVAR;
97 # ifdef HAS_LOCALECONV
98     const struct lconv* const lc = localeconv();
99
100     if (lc && lc->decimal_point) {
101         if (lc->decimal_point[0] == '.' && lc->decimal_point[1] == 0) {
102             SvREFCNT_dec(PL_numeric_radix_sv);
103             PL_numeric_radix_sv = NULL;
104         }
105         else {
106             if (PL_numeric_radix_sv)
107                 sv_setpv(PL_numeric_radix_sv, lc->decimal_point);
108             else
109                 PL_numeric_radix_sv = newSVpv(lc->decimal_point, 0);
110             if (! is_ascii_string((U8 *) lc->decimal_point, 0)
111                 && is_utf8_string((U8 *) lc->decimal_point, 0)
112                 && is_cur_LC_category_utf8(LC_NUMERIC))
113             {
114                 SvUTF8_on(PL_numeric_radix_sv);
115             }
116         }
117     }
118     else
119         PL_numeric_radix_sv = NULL;
120
121     DEBUG_L(PerlIO_printf(Perl_debug_log, "Locale radix is %s\n",
122                                           (PL_numeric_radix_sv)
123                                           ? lc->decimal_point
124                                           : "NULL"));
125
126 # endif /* HAS_LOCALECONV */
127 #endif /* USE_LOCALE_NUMERIC */
128 }
129
130 void
131 Perl_new_numeric(pTHX_ const char *newnum)
132 {
133 #ifdef USE_LOCALE_NUMERIC
134
135     /* Called after all libc setlocale() calls affecting LC_NUMERIC, to tell
136      * core Perl this and that 'newnum' is the name of the new locale.
137      * It installs this locale as the current underlying default.
138      *
139      * The default locale and the C locale can be toggled between by use of the
140      * set_numeric_local() and set_numeric_standard() functions, which should
141      * probably not be called directly, but only via macros like
142      * SET_NUMERIC_STANDARD() in perl.h.
143      *
144      * The toggling is necessary mainly so that a non-dot radix decimal point
145      * character can be output, while allowing internal calculations to use a
146      * dot.
147      *
148      * This sets several interpreter-level variables:
149      * PL_numeric_name  The default locale's name: a copy of 'newnum'
150      * PL_numeric_local A boolean indicating if the toggled state is such
151      *                  that the current locale is the default locale
152      * PL_numeric_standard A boolean indicating if the toggled state is such
153      *                  that the current locale is the C locale
154      * Note that both of the last two variables can be true at the same time,
155      * if the underlying locale is C.  (Toggling is a no-op under these
156      * circumstances.)
157      *
158      * Any code changing the locale (outside this file) should use
159      * POSIX::setlocale, which calls this function.  Therefore this function
160      * should be called directly only from this file and from
161      * POSIX::setlocale() */
162
163     char *save_newnum;
164     dVAR;
165
166     if (! newnum) {
167         Safefree(PL_numeric_name);
168         PL_numeric_name = NULL;
169         PL_numeric_standard = TRUE;
170         PL_numeric_local = TRUE;
171         return;
172     }
173
174     save_newnum = stdize_locale(savepv(newnum));
175     if (! PL_numeric_name || strNE(PL_numeric_name, save_newnum)) {
176         Safefree(PL_numeric_name);
177         PL_numeric_name = save_newnum;
178     }
179
180     PL_numeric_standard = ((*save_newnum == 'C' && save_newnum[1] == '\0')
181                             || strEQ(save_newnum, "POSIX"));
182     PL_numeric_local = TRUE;
183     set_numeric_radix();
184
185 #endif /* USE_LOCALE_NUMERIC */
186 }
187
188 void
189 Perl_set_numeric_standard(pTHX)
190 {
191 #ifdef USE_LOCALE_NUMERIC
192     dVAR;
193
194     /* Toggle the LC_NUMERIC locale to C, if not already there.  Probably
195      * should use the macros like SET_NUMERIC_STANDARD() in perl.h instead of
196      * calling this directly. */
197
198     if (! PL_numeric_standard) {
199         setlocale(LC_NUMERIC, "C");
200         PL_numeric_standard = TRUE;
201         PL_numeric_local = FALSE;
202         set_numeric_radix();
203     }
204     DEBUG_L(PerlIO_printf(Perl_debug_log,
205                           "Underlying LC_NUMERIC locale now is C\n"));
206
207 #endif /* USE_LOCALE_NUMERIC */
208 }
209
210 void
211 Perl_set_numeric_local(pTHX)
212 {
213 #ifdef USE_LOCALE_NUMERIC
214     dVAR;
215
216     /* Toggle the LC_NUMERIC locale to the current underlying default, if not
217      * already there.  Probably should use the macros like SET_NUMERIC_LOCAL()
218      * in perl.h instead of calling this directly. */
219
220     if (! PL_numeric_local) {
221         setlocale(LC_NUMERIC, PL_numeric_name);
222         PL_numeric_standard = FALSE;
223         PL_numeric_local = TRUE;
224         set_numeric_radix();
225     }
226     DEBUG_L(PerlIO_printf(Perl_debug_log,
227                           "Underlying LC_NUMERIC locale now is %s\n",
228                           PL_numeric_name));
229
230 #endif /* USE_LOCALE_NUMERIC */
231 }
232
233 /*
234  * Set up for a new ctype locale.
235  */
236 void
237 Perl_new_ctype(pTHX_ const char *newctype)
238 {
239 #ifdef USE_LOCALE_CTYPE
240
241     /* Called after all libc setlocale() calls affecting LC_CTYPE, to tell
242      * core Perl this and that 'newctype' is the name of the new locale.
243      *
244      * This function sets up the folding arrays for all 256 bytes, assuming
245      * that tofold() is tolc() since fold case is not a concept in POSIX,
246      *
247      * Any code changing the locale (outside this file) should use
248      * POSIX::setlocale, which calls this function.  Therefore this function
249      * should be called directly only from this file and from
250      * POSIX::setlocale() */
251
252     dVAR;
253     UV i;
254
255     PERL_ARGS_ASSERT_NEW_CTYPE;
256
257     PL_in_utf8_CTYPE_locale = is_cur_LC_category_utf8(LC_CTYPE);
258
259     /* A UTF-8 locale gets standard rules.  But note that code still has to
260      * handle this specially because of the three problematic code points */
261     if (PL_in_utf8_CTYPE_locale) {
262         Copy(PL_fold_latin1, PL_fold_locale, 256, U8);
263     }
264     else {
265         for (i = 0; i < 256; i++) {
266             if (isUPPER_LC((U8) i))
267                 PL_fold_locale[i] = (U8) toLOWER_LC((U8) i);
268             else if (isLOWER_LC((U8) i))
269                 PL_fold_locale[i] = (U8) toUPPER_LC((U8) i);
270             else
271                 PL_fold_locale[i] = (U8) i;
272         }
273     }
274
275 #endif /* USE_LOCALE_CTYPE */
276     PERL_ARGS_ASSERT_NEW_CTYPE;
277     PERL_UNUSED_ARG(newctype);
278     PERL_UNUSED_CONTEXT;
279 }
280
281 void
282 Perl_new_collate(pTHX_ const char *newcoll)
283 {
284 #ifdef USE_LOCALE_COLLATE
285
286     /* Called after all libc setlocale() calls affecting LC_COLLATE, to tell
287      * core Perl this and that 'newcoll' is the name of the new locale.
288      *
289      * Any code changing the locale (outside this file) should use
290      * POSIX::setlocale, which calls this function.  Therefore this function
291      * should be called directly only from this file and from
292      * POSIX::setlocale() */
293
294     dVAR;
295
296     if (! newcoll) {
297         if (PL_collation_name) {
298             ++PL_collation_ix;
299             Safefree(PL_collation_name);
300             PL_collation_name = NULL;
301         }
302         PL_collation_standard = TRUE;
303         PL_collxfrm_base = 0;
304         PL_collxfrm_mult = 2;
305         return;
306     }
307
308     if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
309         ++PL_collation_ix;
310         Safefree(PL_collation_name);
311         PL_collation_name = stdize_locale(savepv(newcoll));
312         PL_collation_standard = ((*newcoll == 'C' && newcoll[1] == '\0')
313                                  || strEQ(newcoll, "POSIX"));
314
315         {
316           /*  2: at most so many chars ('a', 'b'). */
317           /* 50: surely no system expands a char more. */
318 #define XFRMBUFSIZE  (2 * 50)
319           char xbuf[XFRMBUFSIZE];
320           const Size_t fa = strxfrm(xbuf, "a",  XFRMBUFSIZE);
321           const Size_t fb = strxfrm(xbuf, "ab", XFRMBUFSIZE);
322           const SSize_t mult = fb - fa;
323           if (mult < 1 && !(fa == 0 && fb == 0))
324               Perl_croak(aTHX_ "panic: strxfrm() gets absurd - a => %"UVuf", ab => %"UVuf,
325                          (UV) fa, (UV) fb);
326           PL_collxfrm_base = (fa > (Size_t)mult) ? (fa - mult) : 0;
327           PL_collxfrm_mult = mult;
328         }
329     }
330
331 #endif /* USE_LOCALE_COLLATE */
332 }
333
334 /*
335  * Initialize locale awareness.
336  */
337 int
338 Perl_init_i18nl10n(pTHX_ int printwarn)
339 {
340     int ok = 1;
341     /* returns
342      *    1 = set ok or not applicable,
343      *    0 = fallback to C locale,
344      *   -1 = fallback to C locale failed
345      */
346
347 #if defined(USE_LOCALE)
348     dVAR;
349
350 #ifdef USE_LOCALE_CTYPE
351     char *curctype   = NULL;
352 #endif /* USE_LOCALE_CTYPE */
353 #ifdef USE_LOCALE_COLLATE
354     char *curcoll    = NULL;
355 #endif /* USE_LOCALE_COLLATE */
356 #ifdef USE_LOCALE_NUMERIC
357     char *curnum     = NULL;
358 #endif /* USE_LOCALE_NUMERIC */
359 #ifdef __GLIBC__
360     char * const language   = PerlEnv_getenv("LANGUAGE");
361 #endif
362     /* NULL uses the existing already set up locale */
363     const char * const setlocale_init = (PerlEnv_getenv("PERL_SKIP_LOCALE_INIT"))
364                                         ? NULL
365                                         : "";
366     char * const lc_all     = PerlEnv_getenv("LC_ALL");
367     char * const lang       = PerlEnv_getenv("LANG");
368     bool setlocale_failure = FALSE;
369
370 #ifdef LOCALE_ENVIRON_REQUIRED
371
372     /*
373      * Ultrix setlocale(..., "") fails if there are no environment
374      * variables from which to get a locale name.
375      */
376
377     bool done = FALSE;
378
379 #   ifdef LC_ALL
380     if (lang) {
381         if (setlocale(LC_ALL, setlocale_init))
382             done = TRUE;
383         else
384             setlocale_failure = TRUE;
385     }
386     if (!setlocale_failure) {
387 #       ifdef USE_LOCALE_CTYPE
388         Safefree(curctype);
389         if (! (curctype =
390                setlocale(LC_CTYPE,
391                          (!done && (lang || PerlEnv_getenv("LC_CTYPE")))
392                                     ? setlocale_init : NULL)))
393             setlocale_failure = TRUE;
394         else
395             curctype = savepv(curctype);
396 #       endif /* USE_LOCALE_CTYPE */
397 #       ifdef USE_LOCALE_COLLATE
398         Safefree(curcoll);
399         if (! (curcoll =
400                setlocale(LC_COLLATE,
401                          (!done && (lang || PerlEnv_getenv("LC_COLLATE")))
402                                    ? setlocale_init : NULL)))
403             setlocale_failure = TRUE;
404         else
405             curcoll = savepv(curcoll);
406 #       endif /* USE_LOCALE_COLLATE */
407 #       ifdef USE_LOCALE_NUMERIC
408         Safefree(curnum);
409         if (! (curnum =
410                setlocale(LC_NUMERIC,
411                          (!done && (lang || PerlEnv_getenv("LC_NUMERIC")))
412                                   ? setlocale_init : NULL)))
413             setlocale_failure = TRUE;
414         else
415             curnum = savepv(curnum);
416 #       endif /* USE_LOCALE_NUMERIC */
417     }
418
419 #   endif /* LC_ALL */
420
421 #endif /* !LOCALE_ENVIRON_REQUIRED */
422
423 #ifdef LC_ALL
424     if (! setlocale(LC_ALL, setlocale_init))
425         setlocale_failure = TRUE;
426 #endif /* LC_ALL */
427
428     if (!setlocale_failure) {
429 #ifdef USE_LOCALE_CTYPE
430         Safefree(curctype);
431         if (! (curctype = setlocale(LC_CTYPE, setlocale_init)))
432             setlocale_failure = TRUE;
433         else
434             curctype = savepv(curctype);
435 #endif /* USE_LOCALE_CTYPE */
436 #ifdef USE_LOCALE_COLLATE
437         Safefree(curcoll);
438         if (! (curcoll = setlocale(LC_COLLATE, setlocale_init)))
439             setlocale_failure = TRUE;
440         else
441             curcoll = savepv(curcoll);
442 #endif /* USE_LOCALE_COLLATE */
443 #ifdef USE_LOCALE_NUMERIC
444         Safefree(curnum);
445         if (! (curnum = setlocale(LC_NUMERIC, setlocale_init)))
446             setlocale_failure = TRUE;
447         else
448             curnum = savepv(curnum);
449 #endif /* USE_LOCALE_NUMERIC */
450     }
451
452     if (setlocale_failure) {
453         char *p;
454         const bool locwarn = (printwarn > 1 ||
455                         (printwarn &&
456                          (!(p = PerlEnv_getenv("PERL_BADLANG")) || atoi(p))));
457
458         if (locwarn) {
459 #ifdef LC_ALL
460
461             PerlIO_printf(Perl_error_log,
462                "perl: warning: Setting locale failed.\n");
463
464 #else /* !LC_ALL */
465
466             PerlIO_printf(Perl_error_log,
467                "perl: warning: Setting locale failed for the categories:\n\t");
468 #ifdef USE_LOCALE_CTYPE
469             if (! curctype)
470                 PerlIO_printf(Perl_error_log, "LC_CTYPE ");
471 #endif /* USE_LOCALE_CTYPE */
472 #ifdef USE_LOCALE_COLLATE
473             if (! curcoll)
474                 PerlIO_printf(Perl_error_log, "LC_COLLATE ");
475 #endif /* USE_LOCALE_COLLATE */
476 #ifdef USE_LOCALE_NUMERIC
477             if (! curnum)
478                 PerlIO_printf(Perl_error_log, "LC_NUMERIC ");
479 #endif /* USE_LOCALE_NUMERIC */
480             PerlIO_printf(Perl_error_log, "\n");
481
482 #endif /* LC_ALL */
483
484             PerlIO_printf(Perl_error_log,
485                 "perl: warning: Please check that your locale settings:\n");
486
487 #ifdef __GLIBC__
488             PerlIO_printf(Perl_error_log,
489                           "\tLANGUAGE = %c%s%c,\n",
490                           language ? '"' : '(',
491                           language ? language : "unset",
492                           language ? '"' : ')');
493 #endif
494
495             PerlIO_printf(Perl_error_log,
496                           "\tLC_ALL = %c%s%c,\n",
497                           lc_all ? '"' : '(',
498                           lc_all ? lc_all : "unset",
499                           lc_all ? '"' : ')');
500
501 #if defined(USE_ENVIRON_ARRAY)
502             {
503               char **e;
504               for (e = environ; *e; e++) {
505                   if (strnEQ(*e, "LC_", 3)
506                         && strnNE(*e, "LC_ALL=", 7)
507                         && (p = strchr(*e, '=')))
508                       PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
509                                     (int)(p - *e), *e, p + 1);
510               }
511             }
512 #else
513             PerlIO_printf(Perl_error_log,
514                           "\t(possibly more locale environment variables)\n");
515 #endif
516
517             PerlIO_printf(Perl_error_log,
518                           "\tLANG = %c%s%c\n",
519                           lang ? '"' : '(',
520                           lang ? lang : "unset",
521                           lang ? '"' : ')');
522
523             PerlIO_printf(Perl_error_log,
524                           "    are supported and installed on your system.\n");
525         }
526
527 #ifdef LC_ALL
528
529         if (setlocale(LC_ALL, "C")) {
530             if (locwarn)
531                 PerlIO_printf(Perl_error_log,
532       "perl: warning: Falling back to the standard locale (\"C\").\n");
533             ok = 0;
534         }
535         else {
536             if (locwarn)
537                 PerlIO_printf(Perl_error_log,
538       "perl: warning: Failed to fall back to the standard locale (\"C\").\n");
539             ok = -1;
540         }
541
542 #else /* ! LC_ALL */
543
544         if (0
545 #ifdef USE_LOCALE_CTYPE
546             || !(curctype || setlocale(LC_CTYPE, "C"))
547 #endif /* USE_LOCALE_CTYPE */
548 #ifdef USE_LOCALE_COLLATE
549             || !(curcoll || setlocale(LC_COLLATE, "C"))
550 #endif /* USE_LOCALE_COLLATE */
551 #ifdef USE_LOCALE_NUMERIC
552             || !(curnum || setlocale(LC_NUMERIC, "C"))
553 #endif /* USE_LOCALE_NUMERIC */
554             )
555         {
556             if (locwarn)
557                 PerlIO_printf(Perl_error_log,
558       "perl: warning: Cannot fall back to the standard locale (\"C\").\n");
559             ok = -1;
560         }
561
562 #endif /* ! LC_ALL */
563
564 #ifdef USE_LOCALE_CTYPE
565         Safefree(curctype);
566         curctype = savepv(setlocale(LC_CTYPE, NULL));
567 #endif /* USE_LOCALE_CTYPE */
568 #ifdef USE_LOCALE_COLLATE
569         Safefree(curcoll);
570         curcoll = savepv(setlocale(LC_COLLATE, NULL));
571 #endif /* USE_LOCALE_COLLATE */
572 #ifdef USE_LOCALE_NUMERIC
573         Safefree(curnum);
574         curnum = savepv(setlocale(LC_NUMERIC, NULL));
575 #endif /* USE_LOCALE_NUMERIC */
576     }
577     else {
578
579 #ifdef USE_LOCALE_CTYPE
580     new_ctype(curctype);
581 #endif /* USE_LOCALE_CTYPE */
582
583 #ifdef USE_LOCALE_COLLATE
584     new_collate(curcoll);
585 #endif /* USE_LOCALE_COLLATE */
586
587 #ifdef USE_LOCALE_NUMERIC
588     new_numeric(curnum);
589 #endif /* USE_LOCALE_NUMERIC */
590
591     }
592
593 #if defined(USE_PERLIO) && defined(USE_LOCALE_CTYPE)
594     {
595       /* Set PL_utf8locale to TRUE if using PerlIO _and_
596          the current LC_CTYPE locale is UTF-8.
597          If PL_utf8locale and PL_unicode (set by -C or by $ENV{PERL_UNICODE})
598          are true, perl.c:S_parse_body() will turn on the PerlIO :utf8 layer
599          on STDIN, STDOUT, STDERR, _and_ the default open discipline.
600       */
601         PL_utf8locale = is_cur_LC_category_utf8(LC_CTYPE);
602     }
603     /* Set PL_unicode to $ENV{PERL_UNICODE} if using PerlIO.
604        This is an alternative to using the -C command line switch
605        (the -C if present will override this). */
606     {
607          const char *p = PerlEnv_getenv("PERL_UNICODE");
608          PL_unicode = p ? parse_unicode_opts(&p) : 0;
609          if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
610              PL_utf8cache = -1;
611     }
612 #endif
613
614 #ifdef USE_LOCALE_CTYPE
615     Safefree(curctype);
616 #endif /* USE_LOCALE_CTYPE */
617 #ifdef USE_LOCALE_COLLATE
618     Safefree(curcoll);
619 #endif /* USE_LOCALE_COLLATE */
620 #ifdef USE_LOCALE_NUMERIC
621     Safefree(curnum);
622 #endif /* USE_LOCALE_NUMERIC */
623
624 #endif /* USE_LOCALE */
625
626     return ok;
627 }
628
629 #ifdef USE_LOCALE_COLLATE
630
631 /*
632  * mem_collxfrm() is a bit like strxfrm() but with two important
633  * differences. First, it handles embedded NULs. Second, it allocates
634  * a bit more memory than needed for the transformed data itself.
635  * The real transformed data begins at offset sizeof(collationix).
636  * Please see sv_collxfrm() to see how this is used.
637  */
638
639 char *
640 Perl_mem_collxfrm(pTHX_ const char *s, STRLEN len, STRLEN *xlen)
641 {
642     dVAR;
643     char *xbuf;
644     STRLEN xAlloc, xin, xout; /* xalloc is a reserved word in VC */
645
646     PERL_ARGS_ASSERT_MEM_COLLXFRM;
647
648     /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
649     /* the +1 is for the terminating NUL. */
650
651     xAlloc = sizeof(PL_collation_ix) + PL_collxfrm_base + (PL_collxfrm_mult * len) + 1;
652     Newx(xbuf, xAlloc, char);
653     if (! xbuf)
654         goto bad;
655
656     *(U32*)xbuf = PL_collation_ix;
657     xout = sizeof(PL_collation_ix);
658     for (xin = 0; xin < len; ) {
659         Size_t xused;
660
661         for (;;) {
662             xused = strxfrm(xbuf + xout, s + xin, xAlloc - xout);
663             if (xused >= PERL_INT_MAX)
664                 goto bad;
665             if ((STRLEN)xused < xAlloc - xout)
666                 break;
667             xAlloc = (2 * xAlloc) + 1;
668             Renew(xbuf, xAlloc, char);
669             if (! xbuf)
670                 goto bad;
671         }
672
673         xin += strlen(s + xin) + 1;
674         xout += xused;
675
676         /* Embedded NULs are understood but silently skipped
677          * because they make no sense in locale collation. */
678     }
679
680     xbuf[xout] = '\0';
681     *xlen = xout - sizeof(PL_collation_ix);
682     return xbuf;
683
684   bad:
685     Safefree(xbuf);
686     *xlen = 0;
687     return NULL;
688 }
689
690 #endif /* USE_LOCALE_COLLATE */
691
692 #ifdef USE_LOCALE
693
694 STATIC bool
695 S_is_cur_LC_category_utf8(pTHX_ int category)
696 {
697     /* Returns TRUE if the current locale for 'category' is UTF-8; FALSE
698      * otherwise. 'category' may not be LC_ALL.  If the platform doesn't have
699      * nl_langinfo(), nor MB_CUR_MAX, this employs a heuristic, which hence
700      * could give the wrong result.  It errs on the side of not being a UTF-8
701      * locale. */
702
703     char *save_input_locale = NULL;
704     STRLEN final_pos;
705
706 #ifdef LC_ALL
707     assert(category != LC_ALL);
708 #endif
709
710     /* First dispose of the trivial cases */
711     save_input_locale = setlocale(category, NULL);
712     if (! save_input_locale) {
713         DEBUG_L(PerlIO_printf(Perl_debug_log,
714                               "Could not find current locale for category %d\n",
715                               category));
716         return FALSE;   /* XXX maybe should croak */
717     }
718     save_input_locale = stdize_locale(savepv(save_input_locale));
719     if ((*save_input_locale == 'C' && save_input_locale[1] == '\0')
720         || strEQ(save_input_locale, "POSIX"))
721     {
722         DEBUG_L(PerlIO_printf(Perl_debug_log,
723                               "Current locale for category %d is %s\n",
724                               category, save_input_locale));
725         Safefree(save_input_locale);
726         return FALSE;
727     }
728
729 #if defined(USE_LOCALE_CTYPE)    \
730     && (defined(MB_CUR_MAX) || (defined(HAS_NL_LANGINFO) && defined(CODESET)))
731
732     { /* Next try nl_langinfo or MB_CUR_MAX if available */
733
734         char *save_ctype_locale = NULL;
735         bool is_utf8;
736
737         if (category != LC_CTYPE) { /* These work only on LC_CTYPE */
738
739             /* Get the current LC_CTYPE locale */
740             save_ctype_locale = stdize_locale(savepv(setlocale(LC_CTYPE, NULL)));
741             if (! save_ctype_locale) {
742                 DEBUG_L(PerlIO_printf(Perl_debug_log,
743                                "Could not find current locale for LC_CTYPE\n"));
744                 goto cant_use_nllanginfo;
745             }
746
747             /* If LC_CTYPE and the desired category use the same locale, this
748              * means that finding the value for LC_CTYPE is the same as finding
749              * the value for the desired category.  Otherwise, switch LC_CTYPE
750              * to the desired category's locale */
751             if (strEQ(save_ctype_locale, save_input_locale)) {
752                 Safefree(save_ctype_locale);
753                 save_ctype_locale = NULL;
754             }
755             else if (! setlocale(LC_CTYPE, save_input_locale)) {
756                 DEBUG_L(PerlIO_printf(Perl_debug_log,
757                                     "Could not change LC_CTYPE locale to %s\n",
758                                     save_input_locale));
759                 Safefree(save_ctype_locale);
760                 goto cant_use_nllanginfo;
761             }
762         }
763
764         DEBUG_L(PerlIO_printf(Perl_debug_log, "Current LC_CTYPE locale=%s\n",
765                                               save_input_locale));
766
767         /* Here the current LC_CTYPE is set to the locale of the category whose
768          * information is desired.  This means that nl_langinfo() and MB_CUR_MAX
769          * should give the correct results */
770
771 #   if defined(HAS_NL_LANGINFO) && defined(CODESET)
772         {
773             char *codeset = savepv(nl_langinfo(CODESET));
774             if (codeset && strNE(codeset, "")) {
775
776                 /* If we switched LC_CTYPE, switch back */
777                 if (save_ctype_locale) {
778                     setlocale(LC_CTYPE, save_ctype_locale);
779                     Safefree(save_ctype_locale);
780                 }
781
782                 is_utf8 = foldEQ(codeset, STR_WITH_LEN("UTF-8"))
783                         || foldEQ(codeset, STR_WITH_LEN("UTF8"));
784
785                 DEBUG_L(PerlIO_printf(Perl_debug_log,
786                        "\tnllanginfo returned CODESET '%s'; ?UTF8 locale=%d\n",
787                                                      codeset,         is_utf8));
788                 Safefree(codeset);
789                 Safefree(save_input_locale);
790                 return is_utf8;
791             }
792         }
793
794 #   endif
795 #   ifdef MB_CUR_MAX
796
797         /* Here, either we don't have nl_langinfo, or it didn't return a
798          * codeset.  Try MB_CUR_MAX */
799
800         /* Standard UTF-8 needs at least 4 bytes to represent the maximum
801          * Unicode code point.  Since UTF-8 is the only non-single byte
802          * encoding we handle, we just say any such encoding is UTF-8, and if
803          * turns out to be wrong, other things will fail */
804         is_utf8 = MB_CUR_MAX >= 4;
805
806         DEBUG_L(PerlIO_printf(Perl_debug_log,
807                               "\tMB_CUR_MAX=%d; ?UTF8 locale=%d\n",
808                                    (int) MB_CUR_MAX,      is_utf8));
809
810         Safefree(save_input_locale);
811
812 #       ifdef HAS_MBTOWC
813
814         /* ... But, most system that have MB_CUR_MAX will also have mbtowc(),
815          * since they are both in the C99 standard.  We can feed a known byte
816          * string to the latter function, and check that it gives the expected
817          * result */
818         if (is_utf8) {
819             wchar_t wc;
820             (void) mbtowc(&wc, NULL, 0);    /* Reset any shift state */
821             errno = 0;
822             if (mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8))
823                                                         != strlen(HYPHEN_UTF8)
824                 || wc != (wchar_t) 0x2010)
825             {
826                 is_utf8 = FALSE;
827                 DEBUG_L(PerlIO_printf(Perl_debug_log, "\thyphen=U+%x\n", wc));
828                 DEBUG_L(PerlIO_printf(Perl_debug_log,
829                         "\treturn from mbtowc=%d; errno=%d; ?UTF8 locale=0\n",
830                         mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8)), errno));
831             }
832         }
833 #       endif
834
835         /* If we switched LC_CTYPE, switch back */
836         if (save_ctype_locale) {
837             setlocale(LC_CTYPE, save_ctype_locale);
838             Safefree(save_ctype_locale);
839         }
840
841         return is_utf8;
842 #   endif
843     }
844
845   cant_use_nllanginfo:
846
847 #endif /* HAS_NL_LANGINFO etc */
848
849     /* nl_langinfo not available or failed somehow.  Look at the locale name to
850      * see if it matches qr/UTF -? 8 /ix  */
851
852     final_pos = strlen(save_input_locale) - 1;
853     if (final_pos >= 3) {
854         char *name = save_input_locale;
855
856         /* Find next 'U' or 'u' and look from there */
857         while ((name += strcspn(name, "Uu") + 1)
858                                             <= save_input_locale + final_pos - 2)
859         {
860             if (toFOLD(*(name)) != 't'
861                 || toFOLD(*(name + 1)) != 'f')
862             {
863                 continue;
864             }
865             name += 2;
866             if (*(name) == '-') {
867                 if ((name > save_input_locale + final_pos - 1)) {
868                     break;
869                 }
870                 name++;
871             }
872             if (*(name) == '8') {
873                 Safefree(save_input_locale);
874                 DEBUG_L(PerlIO_printf(Perl_debug_log,
875                                       "Locale %s ends with UTF-8 in name\n",
876                                       save_input_locale));
877                 return TRUE;
878             }
879         }
880         DEBUG_L(PerlIO_printf(Perl_debug_log,
881                               "Locale %s doesn't end with UTF-8 in name\n",
882                                 save_input_locale));
883     }
884
885 #ifdef WIN32
886     /* http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756.aspx */
887     if (final_pos >= 4
888         && *(save_input_locale + final_pos - 0) == '1'
889         && *(save_input_locale + final_pos - 1) == '0'
890         && *(save_input_locale + final_pos - 2) == '0'
891         && *(save_input_locale + final_pos - 3) == '5'
892         && *(save_input_locale + final_pos - 4) == '6')
893     {
894         Safefree(save_input_locale);
895         DEBUG_L(PerlIO_printf(Perl_debug_log,
896                         "Locale %s ends with 10056 in name, is UTF-8 locale\n",
897                         save_input_locale));
898         return TRUE;
899     }
900 #endif
901
902     /* Other common encodings are the ISO 8859 series, which aren't UTF-8 */
903     if (instr(save_input_locale, "8859")) {
904         Safefree(save_input_locale);
905         DEBUG_L(PerlIO_printf(Perl_debug_log,
906                              "Locale %s has 8859 in name, not UTF-8 locale\n",
907                              save_input_locale));
908         return FALSE;
909     }
910
911 #ifdef HAS_LOCALECONV
912
913 #   ifdef USE_LOCALE_MONETARY
914
915     /* Here, there is nothing in the locale name to indicate whether the locale
916      * is UTF-8 or not.  This "name", the return of setlocale(), is actually
917      * defined to be opaque, so we can't really rely on the absence of various
918      * substrings in the name to indicate its UTF-8ness.  Look at the locale's
919      * currency symbol.  Often that will be in the native script, and if the
920      * symbol isn't in UTF-8, we know that the locale isn't.  If it is
921      * non-ASCII UTF-8, we infer that the locale is too.
922      * To do this, like above for LC_CTYPE, we first set LC_MONETARY to the
923      * locale of the desired category, if it isn't that locale already */
924
925     {
926         char *save_monetary_locale = NULL;
927         bool illegal_utf8 = FALSE;
928         bool only_ascii = FALSE;
929         const struct lconv* const lc = localeconv();
930
931         if (category != LC_MONETARY) {
932
933             save_monetary_locale = stdize_locale(savepv(setlocale(LC_MONETARY,
934                                                                   NULL)));
935             if (! save_monetary_locale) {
936                 DEBUG_L(PerlIO_printf(Perl_debug_log,
937                             "Could not find current locale for LC_MONETARY\n"));
938                 goto cant_use_monetary;
939             }
940
941             if (strNE(save_monetary_locale, save_input_locale)) {
942                 if (! setlocale(LC_MONETARY, save_input_locale)) {
943                     DEBUG_L(PerlIO_printf(Perl_debug_log,
944                                 "Could not change LC_MONETARY locale to %s\n",
945                                                             save_input_locale));
946                     Safefree(save_monetary_locale);
947                     goto cant_use_monetary;
948                 }
949             }
950         }
951
952         /* Here the current LC_MONETARY is set to the locale of the category
953          * whose information is desired. */
954
955         if (lc && lc->currency_symbol) {
956             if (! is_utf8_string((U8 *) lc->currency_symbol, 0)) {
957                 DEBUG_L(PerlIO_printf(Perl_debug_log,
958                             "Currency symbol for %s is not legal UTF-8\n",
959                                         save_input_locale));
960                 illegal_utf8 = TRUE;
961             }
962             else if (is_ascii_string((U8 *) lc->currency_symbol, 0)) {
963                 DEBUG_L(PerlIO_printf(Perl_debug_log, "Currency symbol for %s contains only ASCII; can't use for determining if UTF-8 locale\n", save_input_locale));
964                 only_ascii = TRUE;
965             }
966         }
967
968         /* If we changed it, restore LC_MONETARY to its original locale */
969         if (save_monetary_locale) {
970             setlocale(LC_MONETARY, save_monetary_locale);
971             Safefree(save_monetary_locale);
972         }
973
974         Safefree(save_input_locale);
975
976         /* It isn't a UTF-8 locale if the symbol is not legal UTF-8; otherwise
977          * assume the locale is UTF-8 if and only if the symbol is non-ascii
978          * UTF-8.  (We can't really tell if the locale is UTF-8 or not if the
979          * symbol is just a '$', so we err on the side of it not being UTF-8)
980          * */
981         DEBUG_L(PerlIO_printf(Perl_debug_log, "\tis_utf8=%d\n", (illegal_utf8)
982                                                                ? FALSE
983                                                                : ! only_ascii));
984         return (illegal_utf8)
985                 ? FALSE
986                 : ! only_ascii;
987
988     }
989   cant_use_monetary:
990
991 #   endif /* USE_LOCALE_MONETARY */
992 #endif /* HAS_LOCALECONV */
993
994 #if 0 && defined(HAS_STRERROR) && defined(USE_LOCALE_MESSAGES)
995
996 /* This code is ifdefd out because it was found to not be necessary in testing
997  * on our dromedary test machine, which has over 700 locales.  There, looking
998  * at just the currency symbol gave essentially the same results as doing this
999  * extra work.  Executing this also caused segfaults in miniperl.  I left it in
1000  * so as to avoid rewriting it if real-world experience indicates that
1001  * dromedary is an outlier.  Essentially, instead of returning abpve if we
1002  * haven't found illegal utf8, we continue on and examine all the strerror()
1003  * messages on the platform for utf8ness.  If all are ASCII, we still don't
1004  * know the answer; but otherwise we have a pretty good indication of the
1005  * utf8ness.  The reason this doesn't necessarily help much is that the
1006  * messages may not have been translated into the locale.  The currency symbol
1007  * is much more likely to have been translated.  The code below would need to
1008  * be altered somewhat to just be a continuation of testing the currency
1009  * symbol. */
1010         int e;
1011         unsigned int failures = 0, non_ascii = 0;
1012         char *save_messages_locale = NULL;
1013
1014         /* Like above for LC_CTYPE, we set LC_MESSAGES to the locale of the
1015          * desired category, if it isn't that locale already */
1016
1017         if (category != LC_MESSAGES) {
1018
1019             save_messages_locale = stdize_locale(savepv(setlocale(LC_MESSAGES,
1020                                                                   NULL)));
1021             if (! save_messages_locale) {
1022                 goto cant_use_messages;
1023             }
1024
1025             if (strEQ(save_messages_locale, save_input_locale)) {
1026                 Safefree(save_input_locale);
1027             }
1028             else if (! setlocale(LC_MESSAGES, save_input_locale)) {
1029                 Safefree(save_messages_locale);
1030                 goto cant_use_messages;
1031             }
1032         }
1033
1034         /* Here the current LC_MESSAGES is set to the locale of the category
1035          * whose information is desired.  Look through all the messages */
1036
1037         for (e = 0;
1038 #ifdef HAS_SYS_ERRLIST
1039              e <= sys_nerr
1040 #endif
1041              ; e++)
1042         {
1043             const U8* const errmsg = (U8 *) Strerror(e) ;
1044             if (!errmsg)
1045                 break;
1046             if (! is_utf8_string(errmsg, 0)) {
1047                 failures++;
1048                 break;
1049             }
1050             else if (! is_ascii_string(errmsg, 0)) {
1051                 non_ascii++;
1052             }
1053         }
1054
1055         /* And, if we changed it, restore LC_MESSAGES to its original locale */
1056         if (save_messages_locale) {
1057             setlocale(LC_MESSAGES, save_messages_locale);
1058             Safefree(save_messages_locale);
1059         }
1060
1061         /* Any non-UTF-8 message means not a UTF-8 locale; if all are valid,
1062          * any non-ascii means it is one; otherwise we assume it isn't */
1063         return (failures) ? FALSE : non_ascii;
1064
1065     }
1066   cant_use_messages:
1067
1068 #endif
1069
1070     DEBUG_L(PerlIO_printf(Perl_debug_log,
1071                           "Assuming locale %s is not a UTF-8 locale\n",
1072                                     save_input_locale));
1073     Safefree(save_input_locale);
1074     return FALSE;
1075 }
1076
1077 #endif
1078
1079 /*
1080  * Local variables:
1081  * c-indentation-style: bsd
1082  * c-basic-offset: 4
1083  * indent-tabs-mode: nil
1084  * End:
1085  *
1086  * ex: set ts=8 sts=4 sw=4 et:
1087  */