This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
note for detecting crypt() on Cygwin
[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.  And, LC_MESSAGES is
33  * switched to the C locale for outputting the message unless within the scope
34  * of 'use locale'.
35  */
36
37 #include "EXTERN.h"
38 #define PERL_IN_LOCALE_C
39 #include "perl.h"
40
41 #ifdef I_LANGINFO
42 #   include <langinfo.h>
43 #endif
44
45 #include "reentr.h"
46
47 #ifdef USE_LOCALE
48
49 /*
50  * Standardize the locale name from a string returned by 'setlocale', possibly
51  * modifying that string.
52  *
53  * The typical return value of setlocale() is either
54  * (1) "xx_YY" if the first argument of setlocale() is not LC_ALL
55  * (2) "xa_YY xb_YY ..." if the first argument of setlocale() is LC_ALL
56  *     (the space-separated values represent the various sublocales,
57  *      in some unspecified order).  This is not handled by this function.
58  *
59  * In some platforms it has a form like "LC_SOMETHING=Lang_Country.866\n",
60  * which is harmful for further use of the string in setlocale().  This
61  * function removes the trailing new line and everything up through the '='
62  *
63  */
64 STATIC char *
65 S_stdize_locale(pTHX_ char *locs)
66 {
67     const char * const s = strchr(locs, '=');
68     bool okay = TRUE;
69
70     PERL_ARGS_ASSERT_STDIZE_LOCALE;
71
72     if (s) {
73         const char * const t = strchr(s, '.');
74         okay = FALSE;
75         if (t) {
76             const char * const u = strchr(t, '\n');
77             if (u && (u[1] == 0)) {
78                 const STRLEN len = u - s;
79                 Move(s + 1, locs, len, char);
80                 locs[len] = 0;
81                 okay = TRUE;
82             }
83         }
84     }
85
86     if (!okay)
87         Perl_croak(aTHX_ "Can't fix broken locale name \"%s\"", locs);
88
89     return locs;
90 }
91
92 #endif
93
94 void
95 Perl_set_numeric_radix(pTHX)
96 {
97 #ifdef USE_LOCALE_NUMERIC
98 # ifdef HAS_LOCALECONV
99     const struct lconv* const lc = localeconv();
100
101     if (lc && lc->decimal_point) {
102         if (lc->decimal_point[0] == '.' && lc->decimal_point[1] == 0) {
103             SvREFCNT_dec(PL_numeric_radix_sv);
104             PL_numeric_radix_sv = NULL;
105         }
106         else {
107             if (PL_numeric_radix_sv)
108                 sv_setpv(PL_numeric_radix_sv, lc->decimal_point);
109             else
110                 PL_numeric_radix_sv = newSVpv(lc->decimal_point, 0);
111             if (! is_invariant_string((U8 *) lc->decimal_point, 0)
112                 && is_utf8_string((U8 *) lc->decimal_point, 0)
113                 && _is_cur_LC_category_utf8(LC_NUMERIC))
114             {
115                 SvUTF8_on(PL_numeric_radix_sv);
116             }
117         }
118     }
119     else
120         PL_numeric_radix_sv = NULL;
121
122     DEBUG_L(PerlIO_printf(Perl_debug_log, "Locale radix is %s, ?UTF-8=%d\n",
123                                           (PL_numeric_radix_sv)
124                                            ? SvPVX(PL_numeric_radix_sv)
125                                            : "NULL",
126                                           (PL_numeric_radix_sv)
127                                            ? cBOOL(SvUTF8(PL_numeric_radix_sv))
128                                            : 0));
129
130 # endif /* HAS_LOCALECONV */
131 #endif /* USE_LOCALE_NUMERIC */
132 }
133
134 /* Is the C string input 'name' "C" or "POSIX"?  If so, and 'name' is the
135  * return of setlocale(), then this is extremely likely to be the C or POSIX
136  * locale.  However, the output of setlocale() is documented to be opaque, but
137  * the odds are extremely small that it would return these two strings for some
138  * other locale.  Note that VMS in these two locales includes many non-ASCII
139  * characters as controls and punctuation (below are hex bytes):
140  *   cntrl:  00-1F 7F 84-97 9B-9F
141  *   punct:  21-2F 3A-40 5B-60 7B-7E A1-A3 A5 A7-AB B0-B3 B5-B7 B9-BD BF-CF D1-DD DF-EF F1-FD
142  * Oddly, none there are listed as alphas, though some represent alphabetics
143  * http://www.nntp.perl.org/group/perl.perl5.porters/2013/02/msg198753.html */
144 #define isNAME_C_OR_POSIX(name) ((name) != NULL                                 \
145                                   && ((*(name) == 'C' && (*(name + 1)) == '\0') \
146                                        || strEQ((name), "POSIX")))
147
148 void
149 Perl_new_numeric(pTHX_ const char *newnum)
150 {
151 #ifdef USE_LOCALE_NUMERIC
152
153     /* Called after all libc setlocale() calls affecting LC_NUMERIC, to tell
154      * core Perl this and that 'newnum' is the name of the new locale.
155      * It installs this locale as the current underlying default.
156      *
157      * The default locale and the C locale can be toggled between by use of the
158      * set_numeric_local() and set_numeric_standard() functions, which should
159      * probably not be called directly, but only via macros like
160      * SET_NUMERIC_STANDARD() in perl.h.
161      *
162      * The toggling is necessary mainly so that a non-dot radix decimal point
163      * character can be output, while allowing internal calculations to use a
164      * dot.
165      *
166      * This sets several interpreter-level variables:
167      * PL_numeric_name  The underlying locale's name: a copy of 'newnum'
168      * PL_numeric_local A boolean indicating if the toggled state is such
169      *                  that the current locale is the program's underlying
170      *                  locale
171      * PL_numeric_standard An int indicating if the toggled state is such
172      *                  that the current locale is the C locale.  If non-zero,
173      *                  it is in C; if > 1, it means it may not be toggled away
174      *                  from C.
175      * Note that both of the last two variables can be true at the same time,
176      * if the underlying locale is C.  (Toggling is a no-op under these
177      * circumstances.)
178      *
179      * Any code changing the locale (outside this file) should use
180      * POSIX::setlocale, which calls this function.  Therefore this function
181      * should be called directly only from this file and from
182      * POSIX::setlocale() */
183
184     char *save_newnum;
185
186     if (! newnum) {
187         Safefree(PL_numeric_name);
188         PL_numeric_name = NULL;
189         PL_numeric_standard = TRUE;
190         PL_numeric_local = TRUE;
191         return;
192     }
193
194     save_newnum = stdize_locale(savepv(newnum));
195
196     PL_numeric_standard = isNAME_C_OR_POSIX(save_newnum);
197     PL_numeric_local = TRUE;
198
199     if (! PL_numeric_name || strNE(PL_numeric_name, save_newnum)) {
200         Safefree(PL_numeric_name);
201         PL_numeric_name = save_newnum;
202     }
203     else {
204         Safefree(save_newnum);
205     }
206
207     /* Keep LC_NUMERIC in the C locale.  This is for XS modules, so they don't
208      * have to worry about the radix being a non-dot.  (Core operations that
209      * need the underlying locale change to it temporarily). */
210     set_numeric_standard();
211
212     set_numeric_radix();
213
214 #else
215     PERL_UNUSED_ARG(newnum);
216 #endif /* USE_LOCALE_NUMERIC */
217 }
218
219 void
220 Perl_set_numeric_standard(pTHX)
221 {
222 #ifdef USE_LOCALE_NUMERIC
223     /* Toggle the LC_NUMERIC locale to C.  Most code should use the macros like
224      * SET_NUMERIC_STANDARD() in perl.h instead of calling this directly.  The
225      * macro avoids calling this routine if toggling isn't necessary according
226      * to our records (which could be wrong if some XS code has changed the
227      * locale behind our back) */
228
229     setlocale(LC_NUMERIC, "C");
230     PL_numeric_standard = TRUE;
231     PL_numeric_local = isNAME_C_OR_POSIX(PL_numeric_name);
232     set_numeric_radix();
233     DEBUG_L(PerlIO_printf(Perl_debug_log,
234                           "Underlying LC_NUMERIC locale now is C\n"));
235
236 #endif /* USE_LOCALE_NUMERIC */
237 }
238
239 void
240 Perl_set_numeric_local(pTHX)
241 {
242 #ifdef USE_LOCALE_NUMERIC
243     /* Toggle the LC_NUMERIC locale to the current underlying default.  Most
244      * code should use the macros like SET_NUMERIC_LOCAL() in perl.h instead of
245      * calling this directly.  The macro avoids calling this routine if
246      * toggling isn't necessary according to our records (which could be wrong
247      * if some XS code has changed the locale behind our back) */
248
249     setlocale(LC_NUMERIC, PL_numeric_name);
250     PL_numeric_standard = isNAME_C_OR_POSIX(PL_numeric_name);
251     PL_numeric_local = TRUE;
252     set_numeric_radix();
253     DEBUG_L(PerlIO_printf(Perl_debug_log,
254                           "Underlying LC_NUMERIC locale now is %s\n",
255                           PL_numeric_name));
256
257 #endif /* USE_LOCALE_NUMERIC */
258 }
259
260 /*
261  * Set up for a new ctype locale.
262  */
263 void
264 Perl_new_ctype(pTHX_ const char *newctype)
265 {
266 #ifdef USE_LOCALE_CTYPE
267
268     /* Called after all libc setlocale() calls affecting LC_CTYPE, to tell
269      * core Perl this and that 'newctype' is the name of the new locale.
270      *
271      * This function sets up the folding arrays for all 256 bytes, assuming
272      * that tofold() is tolc() since fold case is not a concept in POSIX,
273      *
274      * Any code changing the locale (outside this file) should use
275      * POSIX::setlocale, which calls this function.  Therefore this function
276      * should be called directly only from this file and from
277      * POSIX::setlocale() */
278
279     dVAR;
280     UV i;
281
282     PERL_ARGS_ASSERT_NEW_CTYPE;
283
284     /* We will replace any bad locale warning with 1) nothing if the new one is
285      * ok; or 2) a new warning for the bad new locale */
286     if (PL_warn_locale) {
287         SvREFCNT_dec_NN(PL_warn_locale);
288         PL_warn_locale = NULL;
289     }
290
291     PL_in_utf8_CTYPE_locale = _is_cur_LC_category_utf8(LC_CTYPE);
292
293     /* A UTF-8 locale gets standard rules.  But note that code still has to
294      * handle this specially because of the three problematic code points */
295     if (PL_in_utf8_CTYPE_locale) {
296         Copy(PL_fold_latin1, PL_fold_locale, 256, U8);
297     }
298     else {
299         /* Assume enough space for every character being bad.  4 spaces each
300          * for the 94 printable characters that are output like "'x' "; and 5
301          * spaces each for "'\\' ", "'\t' ", and "'\n' "; plus a terminating
302          * NUL */
303         char bad_chars_list[ (94 * 4) + (3 * 5) + 1 ];
304
305         bool check_for_problems = ckWARN_d(WARN_LOCALE); /* No warnings means
306                                                             no check */
307         bool multi_byte_locale = FALSE;     /* Assume is a single-byte locale
308                                                to start */
309         unsigned int bad_count = 0;         /* Count of bad characters */
310
311         for (i = 0; i < 256; i++) {
312             if (isUPPER_LC((U8) i))
313                 PL_fold_locale[i] = (U8) toLOWER_LC((U8) i);
314             else if (isLOWER_LC((U8) i))
315                 PL_fold_locale[i] = (U8) toUPPER_LC((U8) i);
316             else
317                 PL_fold_locale[i] = (U8) i;
318
319             /* If checking for locale problems, see if the native ASCII-range
320              * printables plus \n and \t are in their expected categories in
321              * the new locale.  If not, this could mean big trouble, upending
322              * Perl's and most programs' assumptions, like having a
323              * metacharacter with special meaning become a \w.  Fortunately,
324              * it's very rare to find locales that aren't supersets of ASCII
325              * nowadays.  It isn't a problem for most controls to be changed
326              * into something else; we check only \n and \t, though perhaps \r
327              * could be an issue as well. */
328             if (check_for_problems
329                 && (isGRAPH_A(i) || isBLANK_A(i) || i == '\n'))
330             {
331                 if ((isALPHANUMERIC_A(i) && ! isALPHANUMERIC_LC(i))
332                      || (isPUNCT_A(i) && ! isPUNCT_LC(i))
333                      || (isBLANK_A(i) && ! isBLANK_LC(i))
334                      || (i == '\n' && ! isCNTRL_LC(i)))
335                 {
336                     if (bad_count) {    /* Separate multiple entries with a
337                                            blank */
338                         bad_chars_list[bad_count++] = ' ';
339                     }
340                     bad_chars_list[bad_count++] = '\'';
341                     if (isPRINT_A(i)) {
342                         bad_chars_list[bad_count++] = (char) i;
343                     }
344                     else {
345                         bad_chars_list[bad_count++] = '\\';
346                         if (i == '\n') {
347                             bad_chars_list[bad_count++] = 'n';
348                         }
349                         else {
350                             assert(i == '\t');
351                             bad_chars_list[bad_count++] = 't';
352                         }
353                     }
354                     bad_chars_list[bad_count++] = '\'';
355                     bad_chars_list[bad_count] = '\0';
356                 }
357             }
358         }
359
360 #ifdef MB_CUR_MAX
361         /* We only handle single-byte locales (outside of UTF-8 ones; so if
362          * this locale requires than one byte, there are going to be
363          * problems. */
364         if (check_for_problems && MB_CUR_MAX > 1
365
366                /* Some platforms return MB_CUR_MAX > 1 for even the "C"
367                 * locale.  Just assume that the implementation for them (plus
368                 * for POSIX) is correct and the > 1 value is spurious.  (Since
369                 * these are specially handled to never be considered UTF-8
370                 * locales, as long as this is the only problem, everything
371                 * should work fine */
372             && strNE(newctype, "C") && strNE(newctype, "POSIX"))
373         {
374             multi_byte_locale = TRUE;
375         }
376 #endif
377
378         if (bad_count || multi_byte_locale) {
379             PL_warn_locale = Perl_newSVpvf(aTHX_
380                              "Locale '%s' may not work well.%s%s%s\n",
381                              newctype,
382                              (multi_byte_locale)
383                               ? "  Some characters in it are not recognized by"
384                                 " Perl."
385                               : "",
386                              (bad_count)
387                               ? "\nThe following characters (and maybe others)"
388                                 " may not have the same meaning as the Perl"
389                                 " program expects:\n"
390                               : "",
391                              (bad_count)
392                               ? bad_chars_list
393                               : ""
394                             );
395             /* If we are actually in the scope of the locale, output the
396              * message now.  Otherwise we save it to be output at the first
397              * operation using this locale, if that actually happens.  Most
398              * programs don't use locales, so they are immune to bad ones */
399             if (IN_LC(LC_CTYPE)) {
400
401                 /* We have to save 'newctype' because the setlocale() just
402                  * below may destroy it.  The next setlocale() further down
403                  * should restore it properly so that the intermediate change
404                  * here is transparent to this function's caller */
405                 const char * const badlocale = savepv(newctype);
406
407                 setlocale(LC_CTYPE, "C");
408
409                 /* The '0' below suppresses a bogus gcc compiler warning */
410                 Perl_warner(aTHX_ packWARN(WARN_LOCALE), SvPVX(PL_warn_locale), 0);
411                 setlocale(LC_CTYPE, badlocale);
412                 Safefree(badlocale);
413                 SvREFCNT_dec_NN(PL_warn_locale);
414                 PL_warn_locale = NULL;
415             }
416         }
417     }
418
419 #endif /* USE_LOCALE_CTYPE */
420     PERL_ARGS_ASSERT_NEW_CTYPE;
421     PERL_UNUSED_ARG(newctype);
422     PERL_UNUSED_CONTEXT;
423 }
424
425 void
426 Perl__warn_problematic_locale()
427 {
428
429 #ifdef USE_LOCALE_CTYPE
430
431     dTHX;
432
433     /* Internal-to-core function that outputs the message in PL_warn_locale,
434      * and then NULLS it.  Should be called only through the macro
435      * _CHECK_AND_WARN_PROBLEMATIC_LOCALE */
436
437     if (PL_warn_locale) {
438         /*GCC_DIAG_IGNORE(-Wformat-security);   Didn't work */
439         Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
440                              SvPVX(PL_warn_locale),
441                              0 /* dummy to avoid compiler warning */ );
442         /* GCC_DIAG_RESTORE; */
443         SvREFCNT_dec_NN(PL_warn_locale);
444         PL_warn_locale = NULL;
445     }
446
447 #endif
448
449 }
450
451 void
452 Perl_new_collate(pTHX_ const char *newcoll)
453 {
454 #ifdef USE_LOCALE_COLLATE
455
456     /* Called after all libc setlocale() calls affecting LC_COLLATE, to tell
457      * core Perl this and that 'newcoll' is the name of the new locale.
458      *
459      * Any code changing the locale (outside this file) should use
460      * POSIX::setlocale, which calls this function.  Therefore this function
461      * should be called directly only from this file and from
462      * POSIX::setlocale() */
463
464     if (! newcoll) {
465         if (PL_collation_name) {
466             ++PL_collation_ix;
467             Safefree(PL_collation_name);
468             PL_collation_name = NULL;
469         }
470         PL_collation_standard = TRUE;
471         PL_collxfrm_base = 0;
472         PL_collxfrm_mult = 2;
473         return;
474     }
475
476     if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
477         ++PL_collation_ix;
478         Safefree(PL_collation_name);
479         PL_collation_name = stdize_locale(savepv(newcoll));
480         PL_collation_standard = isNAME_C_OR_POSIX(newcoll);
481
482         {
483           /*  2: at most so many chars ('a', 'b'). */
484           /* 50: surely no system expands a char more. */
485 #define XFRMBUFSIZE  (2 * 50)
486           char xbuf[XFRMBUFSIZE];
487           const Size_t fa = strxfrm(xbuf, "a",  XFRMBUFSIZE);
488           const Size_t fb = strxfrm(xbuf, "ab", XFRMBUFSIZE);
489           const SSize_t mult = fb - fa;
490           if (mult < 1 && !(fa == 0 && fb == 0))
491               Perl_croak(aTHX_ "panic: strxfrm() gets absurd - a => %"UVuf", ab => %"UVuf,
492                          (UV) fa, (UV) fb);
493           PL_collxfrm_base = (fa > (Size_t)mult) ? (fa - mult) : 0;
494           PL_collxfrm_mult = mult;
495         }
496     }
497
498 #else
499     PERL_UNUSED_ARG(newcoll);
500 #endif /* USE_LOCALE_COLLATE */
501 }
502
503 #ifdef WIN32
504
505 char *
506 Perl_my_setlocale(pTHX_ int category, const char* locale)
507 {
508     /* This, for Windows, emulates POSIX setlocale() behavior.  There is no
509      * difference unless the input locale is "", which means on Windows to get
510      * the machine default, which is set via the computer's "Regional and
511      * Language Options" (or its current equivalent).  In POSIX, it instead
512      * means to find the locale from the user's environment.  This routine
513      * looks in the environment, and, if anything is found, uses that instead
514      * of going to the machine default.  If there is no environment override,
515      * the machine default is used, as normal, by calling the real setlocale()
516      * with "".  The POSIX behavior is to use the LC_ALL variable if set;
517      * otherwise to use the particular category's variable if set; otherwise to
518      * use the LANG variable. */
519
520     bool override_LC_ALL = FALSE;
521     char * result;
522
523     if (locale && strEQ(locale, "")) {
524 #   ifdef LC_ALL
525         locale = PerlEnv_getenv("LC_ALL");
526         if (! locale) {
527 #endif
528             switch (category) {
529 #   ifdef LC_ALL
530                 case LC_ALL:
531                     override_LC_ALL = TRUE;
532                     break;  /* We already know its variable isn't set */
533 #   endif
534 #   ifdef USE_LOCALE_TIME
535                 case LC_TIME:
536                     locale = PerlEnv_getenv("LC_TIME");
537                     break;
538 #   endif
539 #   ifdef USE_LOCALE_CTYPE
540                 case LC_CTYPE:
541                     locale = PerlEnv_getenv("LC_CTYPE");
542                     break;
543 #   endif
544 #   ifdef USE_LOCALE_COLLATE
545                 case LC_COLLATE:
546                     locale = PerlEnv_getenv("LC_COLLATE");
547                     break;
548 #   endif
549 #   ifdef USE_LOCALE_MONETARY
550                 case LC_MONETARY:
551                     locale = PerlEnv_getenv("LC_MONETARY");
552                     break;
553 #   endif
554 #   ifdef USE_LOCALE_NUMERIC
555                 case LC_NUMERIC:
556                     locale = PerlEnv_getenv("LC_NUMERIC");
557                     break;
558 #   endif
559 #   ifdef USE_LOCALE_MESSAGES
560                 case LC_MESSAGES:
561                     locale = PerlEnv_getenv("LC_MESSAGES");
562                     break;
563 #   endif
564                 default:
565                     /* This is a category, like PAPER_SIZE that we don't
566                      * know about; and so can't provide a wrapper. */
567                     break;
568             }
569             if (! locale) {
570                 locale = PerlEnv_getenv("LANG");
571                 if (! locale) {
572                     locale = "";
573                 }
574             }
575 #   ifdef LC_ALL
576         }
577 #   endif
578     }
579
580     result = setlocale(category, locale);
581     DEBUG_L(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n", __FILE__, __LINE__,
582                             _setlocale_debug_string(category, locale, result)));
583
584     if (! override_LC_ALL)  {
585         return result;
586     }
587
588     /* Here the input category was LC_ALL, and we have set it to what is in the
589      * LANG variable or the system default if there is no LANG.  But these have
590      * lower priority than the other LC_foo variables, so override it for each
591      * one that is set.  (If they are set to "", it means to use the same thing
592      * we just set LC_ALL to, so can skip) */
593 #   ifdef USE_LOCALE_TIME
594     result = PerlEnv_getenv("LC_TIME");
595     if (result && strNE(result, "")) {
596         setlocale(LC_TIME, result);
597         DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
598                     __FILE__, __LINE__,
599                     _setlocale_debug_string(LC_TIME, result, "not captured")));
600     }
601 #   endif
602 #   ifdef USE_LOCALE_CTYPE
603     result = PerlEnv_getenv("LC_CTYPE");
604     if (result && strNE(result, "")) {
605         setlocale(LC_CTYPE, result);
606         DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
607                     __FILE__, __LINE__,
608                     _setlocale_debug_string(LC_CTYPE, result, "not captured")));
609     }
610 #   endif
611 #   ifdef USE_LOCALE_COLLATE
612     result = PerlEnv_getenv("LC_COLLATE");
613     if (result && strNE(result, "")) {
614         setlocale(LC_COLLATE, result);
615         DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
616                   __FILE__, __LINE__,
617                   _setlocale_debug_string(LC_COLLATE, result, "not captured")));
618     }
619 #   endif
620 #   ifdef USE_LOCALE_MONETARY
621     result = PerlEnv_getenv("LC_MONETARY");
622     if (result && strNE(result, "")) {
623         setlocale(LC_MONETARY, result);
624         DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
625                  __FILE__, __LINE__,
626                  _setlocale_debug_string(LC_MONETARY, result, "not captured")));
627     }
628 #   endif
629 #   ifdef USE_LOCALE_NUMERIC
630     result = PerlEnv_getenv("LC_NUMERIC");
631     if (result && strNE(result, "")) {
632         setlocale(LC_NUMERIC, result);
633         DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
634                  __FILE__, __LINE__,
635                  _setlocale_debug_string(LC_NUMERIC, result, "not captured")));
636     }
637 #   endif
638 #   ifdef USE_LOCALE_MESSAGES
639     result = PerlEnv_getenv("LC_MESSAGES");
640     if (result && strNE(result, "")) {
641         setlocale(LC_MESSAGES, result);
642         DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
643                  __FILE__, __LINE__,
644                  _setlocale_debug_string(LC_MESSAGES, result, "not captured")));
645     }
646 #   endif
647
648     result = setlocale(LC_ALL, NULL);
649     DEBUG_L(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
650                                __FILE__, __LINE__,
651                                _setlocale_debug_string(LC_ALL, NULL, result)));
652
653     return result;
654 }
655
656 #endif
657
658
659 /*
660  * Initialize locale awareness.
661  */
662 int
663 Perl_init_i18nl10n(pTHX_ int printwarn)
664 {
665     /* printwarn is
666      *
667      *    0 if not to output warning when setup locale is bad
668      *    1 if to output warning based on value of PERL_BADLANG
669      *    >1 if to output regardless of PERL_BADLANG
670      *
671      * returns
672      *    1 = set ok or not applicable,
673      *    0 = fallback to a locale of lower priority
674      *   -1 = fallback to all locales failed, not even to the C locale
675      *
676      * Under -DDEBUGGING, if the environment variable PERL_DEBUG_LOCALE_INIT is
677      * set, debugging information is output.
678      *
679      * This looks more complicated than it is, mainly due to the #ifdefs.
680      *
681      * We try to set LC_ALL to the value determined by the environment.  If
682      * there is no LC_ALL on this platform, we try the individual categories we
683      * know about.  If this works, we are done.
684      *
685      * But if it doesn't work, we have to do something else.  We search the
686      * environment variables ourselves instead of relying on the system to do
687      * it.  We look at, in order, LC_ALL, LANG, a system default locale (if we
688      * think there is one), and the ultimate fallback "C".  This is all done in
689      * the same loop as above to avoid duplicating code, but it makes things
690      * more complex.  After the original failure, we add the fallback
691      * possibilities to the list of locales to try, and iterate the loop
692      * through them all until one succeeds.
693      *
694      * On Ultrix, the locale MUST come from the environment, so there is
695      * preliminary code to set it.  I (khw) am not sure that it is necessary,
696      * and that this couldn't be folded into the loop, but barring any real
697      * platforms to test on, it's staying as-is
698      *
699      * A slight complication is that in embedded Perls, the locale may already
700      * be set-up, and we don't want to get it from the normal environment
701      * variables.  This is handled by having a special environment variable
702      * indicate we're in this situation.  We simply set setlocale's 2nd
703      * parameter to be a NULL instead of "".  That indicates to setlocale that
704      * it is not to change anything, but to return the current value,
705      * effectively initializing perl's db to what the locale already is.
706      *
707      * We play the same trick with NULL if a LC_ALL succeeds.  We call
708      * setlocale() on the individual categores with NULL to get their existing
709      * values for our db, instead of trying to change them.
710      * */
711
712     int ok = 1;
713
714 #if defined(USE_LOCALE)
715 #ifdef USE_LOCALE_CTYPE
716     char *curctype   = NULL;
717 #endif /* USE_LOCALE_CTYPE */
718 #ifdef USE_LOCALE_COLLATE
719     char *curcoll    = NULL;
720 #endif /* USE_LOCALE_COLLATE */
721 #ifdef USE_LOCALE_NUMERIC
722     char *curnum     = NULL;
723 #endif /* USE_LOCALE_NUMERIC */
724 #ifdef __GLIBC__
725     const char * const language   = savepv(PerlEnv_getenv("LANGUAGE"));
726 #endif
727
728     /* NULL uses the existing already set up locale */
729     const char * const setlocale_init = (PerlEnv_getenv("PERL_SKIP_LOCALE_INIT"))
730                                         ? NULL
731                                         : "";
732 #ifdef DEBUGGING
733     const bool debug = (PerlEnv_getenv("PERL_DEBUG_LOCALE_INIT"))
734                        ? TRUE
735                        : FALSE;
736 #   define DEBUG_LOCALE_INIT(category, locale, result)                      \
737         STMT_START {                                                        \
738                 if (debug) {                                                \
739                     PerlIO_printf(Perl_debug_log,                           \
740                                   "%s:%d: %s\n",                            \
741                                   __FILE__, __LINE__,                       \
742                                   _setlocale_debug_string(category,         \
743                                                           locale,           \
744                                                           result));         \
745                 }                                                           \
746         } STMT_END
747 #else
748 #   define DEBUG_LOCALE_INIT(a,b,c)
749 #endif
750     const char* trial_locales[5];   /* 5 = 1 each for "", LC_ALL, LANG, "", C */
751     unsigned int trial_locales_count;
752     const char * const lc_all     = savepv(PerlEnv_getenv("LC_ALL"));
753     const char * const lang       = savepv(PerlEnv_getenv("LANG"));
754     bool setlocale_failure = FALSE;
755     unsigned int i;
756     char *p;
757
758     /* A later getenv() could zap this, so only use here */
759     const char * const bad_lang_use_once = PerlEnv_getenv("PERL_BADLANG");
760
761     const bool locwarn = (printwarn > 1
762                           || (printwarn
763                               && (! bad_lang_use_once
764                                   || (
765                                     /* disallow with "" or "0" */
766                                     *bad_lang_use_once
767                                     && strNE("0", bad_lang_use_once)))));
768     bool done = FALSE;
769     char * sl_result;   /* return from setlocale() */
770     char * locale_param;
771 #ifdef WIN32
772     /* In some systems you can find out the system default locale
773      * and use that as the fallback locale. */
774 #   define SYSTEM_DEFAULT_LOCALE
775 #endif
776 #ifdef SYSTEM_DEFAULT_LOCALE
777     const char *system_default_locale = NULL;
778 #endif
779
780 #ifndef LOCALE_ENVIRON_REQUIRED
781     PERL_UNUSED_VAR(done);
782     PERL_UNUSED_VAR(locale_param);
783 #else
784
785     /*
786      * Ultrix setlocale(..., "") fails if there are no environment
787      * variables from which to get a locale name.
788      */
789
790 #   ifdef LC_ALL
791     if (lang) {
792         sl_result = my_setlocale(LC_ALL, setlocale_init);
793         DEBUG_LOCALE_INIT(LC_ALL, setlocale_init, sl_result);
794         if (sl_result)
795             done = TRUE;
796         else
797             setlocale_failure = TRUE;
798     }
799     if (! setlocale_failure) {
800 #       ifdef USE_LOCALE_CTYPE
801         locale_param = (! done && (lang || PerlEnv_getenv("LC_CTYPE")))
802                        ? setlocale_init
803                        : NULL;
804         curctype = my_setlocale(LC_CTYPE, locale_param);
805         DEBUG_LOCALE_INIT(LC_CTYPE, locale_param, sl_result);
806         if (! curctype)
807             setlocale_failure = TRUE;
808         else
809             curctype = savepv(curctype);
810 #       endif /* USE_LOCALE_CTYPE */
811 #       ifdef USE_LOCALE_COLLATE
812         locale_param = (! done && (lang || PerlEnv_getenv("LC_COLLATE")))
813                        ? setlocale_init
814                        : NULL;
815         curcoll = my_setlocale(LC_COLLATE, locale_param);
816         DEBUG_LOCALE_INIT(LC_COLLATE, locale_param, sl_result);
817         if (! curcoll)
818             setlocale_failure = TRUE;
819         else
820             curcoll = savepv(curcoll);
821 #       endif /* USE_LOCALE_COLLATE */
822 #       ifdef USE_LOCALE_NUMERIC
823         locale_param = (! done && (lang || PerlEnv_getenv("LC_NUMERIC")))
824                        ? setlocale_init
825                        : NULL;
826         curnum = my_setlocale(LC_NUMERIC, locale_param);
827         DEBUG_LOCALE_INIT(LC_NUMERIC, locale_param, sl_result);
828         if (! curnum)
829             setlocale_failure = TRUE;
830         else
831             curnum = savepv(curnum);
832 #       endif /* USE_LOCALE_NUMERIC */
833 #       ifdef USE_LOCALE_MESSAGES
834         locale_param = (! done && (lang || PerlEnv_getenv("LC_MESSAGES")))
835                        ? setlocale_init
836                        : NULL;
837         sl_result = my_setlocale(LC_MESSAGES, locale_param);
838         DEBUG_LOCALE_INIT(LC_MESSAGES, locale_param, sl_result);
839         if (! sl_result)
840             setlocale_failure = TRUE;
841         }
842 #       endif /* USE_LOCALE_MESSAGES */
843 #       ifdef USE_LOCALE_MONETARY
844         locale_param = (! done && (lang || PerlEnv_getenv("LC_MONETARY")))
845                        ? setlocale_init
846                        : NULL;
847         sl_result = my_setlocale(LC_MONETARY, locale_param);
848         DEBUG_LOCALE_INIT(LC_MONETARY, locale_param, sl_result);
849         if (! sl_result) {
850             setlocale_failure = TRUE;
851         }
852 #       endif /* USE_LOCALE_MONETARY */
853     }
854
855 #   endif /* LC_ALL */
856
857 #endif /* !LOCALE_ENVIRON_REQUIRED */
858
859     /* We try each locale in the list until we get one that works, or exhaust
860      * the list.  Normally the loop is executed just once.  But if setting the
861      * locale fails, inside the loop we add fallback trials to the array and so
862      * will execute the loop multiple times */
863     trial_locales[0] = setlocale_init;
864     trial_locales_count = 1;
865     for (i= 0; i < trial_locales_count; i++) {
866         const char * trial_locale = trial_locales[i];
867
868         if (i > 0) {
869
870             /* XXX This is to preserve old behavior for LOCALE_ENVIRON_REQUIRED
871              * when i==0, but I (khw) don't think that behavior makes much
872              * sense */
873             setlocale_failure = FALSE;
874
875 #ifdef SYSTEM_DEFAULT_LOCALE
876 #  ifdef WIN32
877             /* On Windows machines, an entry of "" after the 0th means to use
878              * the system default locale, which we now proceed to get. */
879             if (strEQ(trial_locale, "")) {
880                 unsigned int j;
881
882                 /* Note that this may change the locale, but we are going to do
883                  * that anyway just below */
884                 system_default_locale = setlocale(LC_ALL, "");
885                 DEBUG_LOCALE_INIT(LC_ALL, "", system_default_locale);
886
887                 /* Skip if invalid or it's already on the list of locales to
888                  * try */
889                 if (! system_default_locale) {
890                     goto next_iteration;
891                 }
892                 for (j = 0; j < trial_locales_count; j++) {
893                     if (strEQ(system_default_locale, trial_locales[j])) {
894                         goto next_iteration;
895                     }
896                 }
897
898                 trial_locale = system_default_locale;
899             }
900 #  endif /* WIN32 */
901 #endif /* SYSTEM_DEFAULT_LOCALE */
902         }
903
904 #ifdef LC_ALL
905         sl_result = my_setlocale(LC_ALL, trial_locale);
906         DEBUG_LOCALE_INIT(LC_ALL, trial_locale, sl_result);
907         if (! sl_result) {
908             setlocale_failure = TRUE;
909         }
910         else {
911             /* Since LC_ALL succeeded, it should have changed all the other
912              * categories it can to its value; so we massage things so that the
913              * setlocales below just return their category's current values.
914              * This adequately handles the case in NetBSD where LC_COLLATE may
915              * not be defined for a locale, and setting it individually will
916              * fail, whereas setting LC_ALL suceeds, leaving LC_COLLATE set to
917              * the POSIX locale. */
918             trial_locale = NULL;
919         }
920 #endif /* LC_ALL */
921
922         if (!setlocale_failure) {
923 #ifdef USE_LOCALE_CTYPE
924             Safefree(curctype);
925             curctype = my_setlocale(LC_CTYPE, trial_locale);
926             DEBUG_LOCALE_INIT(LC_CTYPE, trial_locale, curctype);
927             if (! curctype)
928                 setlocale_failure = TRUE;
929             else
930                 curctype = savepv(curctype);
931 #endif /* USE_LOCALE_CTYPE */
932 #ifdef USE_LOCALE_COLLATE
933             Safefree(curcoll);
934             curcoll = my_setlocale(LC_COLLATE, trial_locale);
935             DEBUG_LOCALE_INIT(LC_COLLATE, trial_locale, curcoll);
936             if (! curcoll)
937                 setlocale_failure = TRUE;
938             else
939                 curcoll = savepv(curcoll);
940 #endif /* USE_LOCALE_COLLATE */
941 #ifdef USE_LOCALE_NUMERIC
942             Safefree(curnum);
943             curnum = my_setlocale(LC_NUMERIC, trial_locale);
944             DEBUG_LOCALE_INIT(LC_NUMERIC, trial_locale, curnum);
945             if (! curnum)
946                 setlocale_failure = TRUE;
947             else
948                 curnum = savepv(curnum);
949 #endif /* USE_LOCALE_NUMERIC */
950 #ifdef USE_LOCALE_MESSAGES
951             sl_result = my_setlocale(LC_MESSAGES, trial_locale);
952             DEBUG_LOCALE_INIT(LC_MESSAGES, trial_locale, sl_result);
953             if (! (sl_result))
954                 setlocale_failure = TRUE;
955 #endif /* USE_LOCALE_MESSAGES */
956 #ifdef USE_LOCALE_MONETARY
957             sl_result = my_setlocale(LC_MONETARY, trial_locale);
958             DEBUG_LOCALE_INIT(LC_MONETARY, trial_locale, sl_result);
959             if (! (sl_result))
960                 setlocale_failure = TRUE;
961 #endif /* USE_LOCALE_MONETARY */
962
963             if (! setlocale_failure) {  /* Success */
964                 break;
965             }
966         }
967
968         /* Here, something failed; will need to try a fallback. */
969         ok = 0;
970
971         if (i == 0) {
972             unsigned int j;
973
974             if (locwarn) { /* Output failure info only on the first one */
975 #ifdef LC_ALL
976
977                 PerlIO_printf(Perl_error_log,
978                 "perl: warning: Setting locale failed.\n");
979
980 #else /* !LC_ALL */
981
982                 PerlIO_printf(Perl_error_log,
983                 "perl: warning: Setting locale failed for the categories:\n\t");
984 #  ifdef USE_LOCALE_CTYPE
985                 if (! curctype)
986                     PerlIO_printf(Perl_error_log, "LC_CTYPE ");
987 #  endif /* USE_LOCALE_CTYPE */
988 #  ifdef USE_LOCALE_COLLATE
989                 if (! curcoll)
990                     PerlIO_printf(Perl_error_log, "LC_COLLATE ");
991 #  endif /* USE_LOCALE_COLLATE */
992 #  ifdef USE_LOCALE_NUMERIC
993                 if (! curnum)
994                     PerlIO_printf(Perl_error_log, "LC_NUMERIC ");
995 #  endif /* USE_LOCALE_NUMERIC */
996                 PerlIO_printf(Perl_error_log, "and possibly others\n");
997
998 #endif /* LC_ALL */
999
1000                 PerlIO_printf(Perl_error_log,
1001                     "perl: warning: Please check that your locale settings:\n");
1002
1003 #ifdef __GLIBC__
1004                 PerlIO_printf(Perl_error_log,
1005                             "\tLANGUAGE = %c%s%c,\n",
1006                             language ? '"' : '(',
1007                             language ? language : "unset",
1008                             language ? '"' : ')');
1009 #endif
1010
1011                 PerlIO_printf(Perl_error_log,
1012                             "\tLC_ALL = %c%s%c,\n",
1013                             lc_all ? '"' : '(',
1014                             lc_all ? lc_all : "unset",
1015                             lc_all ? '"' : ')');
1016
1017 #if defined(USE_ENVIRON_ARRAY)
1018                 {
1019                 char **e;
1020                 for (e = environ; *e; e++) {
1021                     if (strnEQ(*e, "LC_", 3)
1022                             && strnNE(*e, "LC_ALL=", 7)
1023                             && (p = strchr(*e, '=')))
1024                         PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
1025                                         (int)(p - *e), *e, p + 1);
1026                 }
1027                 }
1028 #else
1029                 PerlIO_printf(Perl_error_log,
1030                             "\t(possibly more locale environment variables)\n");
1031 #endif
1032
1033                 PerlIO_printf(Perl_error_log,
1034                             "\tLANG = %c%s%c\n",
1035                             lang ? '"' : '(',
1036                             lang ? lang : "unset",
1037                             lang ? '"' : ')');
1038
1039                 PerlIO_printf(Perl_error_log,
1040                             "    are supported and installed on your system.\n");
1041             }
1042
1043             /* Calculate what fallback locales to try.  We have avoided this
1044              * until we have to, because failure is quite unlikely.  This will
1045              * usually change the upper bound of the loop we are in.
1046              *
1047              * Since the system's default way of setting the locale has not
1048              * found one that works, We use Perl's defined ordering: LC_ALL,
1049              * LANG, and the C locale.  We don't try the same locale twice, so
1050              * don't add to the list if already there.  (On POSIX systems, the
1051              * LC_ALL element will likely be a repeat of the 0th element "",
1052              * but there's no harm done by doing it explicitly.
1053              *
1054              * Note that this tries the LC_ALL environment variable even on
1055              * systems which have no LC_ALL locale setting.  This may or may
1056              * not have been originally intentional, but there's no real need
1057              * to change the behavior. */
1058             if (lc_all) {
1059                 for (j = 0; j < trial_locales_count; j++) {
1060                     if (strEQ(lc_all, trial_locales[j])) {
1061                         goto done_lc_all;
1062                     }
1063                 }
1064                 trial_locales[trial_locales_count++] = lc_all;
1065             }
1066           done_lc_all:
1067
1068             if (lang) {
1069                 for (j = 0; j < trial_locales_count; j++) {
1070                     if (strEQ(lang, trial_locales[j])) {
1071                         goto done_lang;
1072                     }
1073                 }
1074                 trial_locales[trial_locales_count++] = lang;
1075             }
1076           done_lang:
1077
1078 #if defined(WIN32) && defined(LC_ALL)
1079             /* For Windows, we also try the system default locale before "C".
1080              * (If there exists a Windows without LC_ALL we skip this because
1081              * it gets too complicated.  For those, the "C" is the next
1082              * fallback possibility).  The "" is the same as the 0th element of
1083              * the array, but the code at the loop above knows to treat it
1084              * differently when not the 0th */
1085             trial_locales[trial_locales_count++] = "";
1086 #endif
1087
1088             for (j = 0; j < trial_locales_count; j++) {
1089                 if (strEQ("C", trial_locales[j])) {
1090                     goto done_C;
1091                 }
1092             }
1093             trial_locales[trial_locales_count++] = "C";
1094
1095           done_C: ;
1096         }   /* end of first time through the loop */
1097
1098 #ifdef WIN32
1099       next_iteration: ;
1100 #endif
1101
1102     }   /* end of looping through the trial locales */
1103
1104     if (ok < 1) {   /* If we tried to fallback */
1105         const char* msg;
1106         if (! setlocale_failure) {  /* fallback succeeded */
1107            msg = "Falling back to";
1108         }
1109         else {  /* fallback failed */
1110
1111             /* We dropped off the end of the loop, so have to decrement i to
1112              * get back to the value the last time through */
1113             i--;
1114
1115             ok = -1;
1116             msg = "Failed to fall back to";
1117
1118             /* To continue, we should use whatever values we've got */
1119 #ifdef USE_LOCALE_CTYPE
1120             Safefree(curctype);
1121             curctype = savepv(setlocale(LC_CTYPE, NULL));
1122             DEBUG_LOCALE_INIT(LC_CTYPE, NULL, curctype);
1123 #endif /* USE_LOCALE_CTYPE */
1124 #ifdef USE_LOCALE_COLLATE
1125             Safefree(curcoll);
1126             curcoll = savepv(setlocale(LC_COLLATE, NULL));
1127             DEBUG_LOCALE_INIT(LC_COLLATE, NULL, curcoll);
1128 #endif /* USE_LOCALE_COLLATE */
1129 #ifdef USE_LOCALE_NUMERIC
1130             Safefree(curnum);
1131             curnum = savepv(setlocale(LC_NUMERIC, NULL));
1132             DEBUG_LOCALE_INIT(LC_NUMERIC, NULL, curnum);
1133 #endif /* USE_LOCALE_NUMERIC */
1134         }
1135
1136         if (locwarn) {
1137             const char * description;
1138             const char * name = "";
1139             if (strEQ(trial_locales[i], "C")) {
1140                 description = "the standard locale";
1141                 name = "C";
1142             }
1143 #ifdef SYSTEM_DEFAULT_LOCALE
1144             else if (strEQ(trial_locales[i], "")) {
1145                 description = "the system default locale";
1146                 if (system_default_locale) {
1147                     name = system_default_locale;
1148                 }
1149             }
1150 #endif /* SYSTEM_DEFAULT_LOCALE */
1151             else {
1152                 description = "a fallback locale";
1153                 name = trial_locales[i];
1154             }
1155             if (name && strNE(name, "")) {
1156                 PerlIO_printf(Perl_error_log,
1157                     "perl: warning: %s %s (\"%s\").\n", msg, description, name);
1158             }
1159             else {
1160                 PerlIO_printf(Perl_error_log,
1161                                    "perl: warning: %s %s.\n", msg, description);
1162             }
1163         }
1164     } /* End of tried to fallback */
1165
1166 #ifdef USE_LOCALE_CTYPE
1167     new_ctype(curctype);
1168 #endif /* USE_LOCALE_CTYPE */
1169
1170 #ifdef USE_LOCALE_COLLATE
1171     new_collate(curcoll);
1172 #endif /* USE_LOCALE_COLLATE */
1173
1174 #ifdef USE_LOCALE_NUMERIC
1175     new_numeric(curnum);
1176 #endif /* USE_LOCALE_NUMERIC */
1177
1178 #if defined(USE_PERLIO) && defined(USE_LOCALE_CTYPE)
1179     /* Set PL_utf8locale to TRUE if using PerlIO _and_ the current LC_CTYPE
1180      * locale is UTF-8.  If PL_utf8locale and PL_unicode (set by -C or by
1181      * $ENV{PERL_UNICODE}) are true, perl.c:S_parse_body() will turn on the
1182      * PerlIO :utf8 layer on STDIN, STDOUT, STDERR, _and_ the default open
1183      * discipline.  */
1184     PL_utf8locale = _is_cur_LC_category_utf8(LC_CTYPE);
1185
1186     /* Set PL_unicode to $ENV{PERL_UNICODE} if using PerlIO.
1187        This is an alternative to using the -C command line switch
1188        (the -C if present will override this). */
1189     {
1190          const char *p = PerlEnv_getenv("PERL_UNICODE");
1191          PL_unicode = p ? parse_unicode_opts(&p) : 0;
1192          if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
1193              PL_utf8cache = -1;
1194     }
1195 #endif
1196
1197 #ifdef USE_LOCALE_CTYPE
1198     Safefree(curctype);
1199 #endif /* USE_LOCALE_CTYPE */
1200 #ifdef USE_LOCALE_COLLATE
1201     Safefree(curcoll);
1202 #endif /* USE_LOCALE_COLLATE */
1203 #ifdef USE_LOCALE_NUMERIC
1204     Safefree(curnum);
1205 #endif /* USE_LOCALE_NUMERIC */
1206
1207 #ifdef __GLIBC__
1208     Safefree(language);
1209 #endif
1210
1211     Safefree(lc_all);
1212     Safefree(lang);
1213
1214 #else  /* !USE_LOCALE */
1215     PERL_UNUSED_ARG(printwarn);
1216 #endif /* USE_LOCALE */
1217
1218     return ok;
1219 }
1220
1221
1222 #ifdef USE_LOCALE_COLLATE
1223
1224 /*
1225  * mem_collxfrm() is a bit like strxfrm() but with two important
1226  * differences. First, it handles embedded NULs. Second, it allocates
1227  * a bit more memory than needed for the transformed data itself.
1228  * The real transformed data begins at offset sizeof(collationix).
1229  * Please see sv_collxfrm() to see how this is used.
1230  */
1231
1232 char *
1233 Perl_mem_collxfrm(pTHX_ const char *s, STRLEN len, STRLEN *xlen)
1234 {
1235     char *xbuf;
1236     STRLEN xAlloc, xin, xout; /* xalloc is a reserved word in VC */
1237
1238     PERL_ARGS_ASSERT_MEM_COLLXFRM;
1239
1240     /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
1241     /* the +1 is for the terminating NUL. */
1242
1243     xAlloc = sizeof(PL_collation_ix) + PL_collxfrm_base + (PL_collxfrm_mult * len) + 1;
1244     Newx(xbuf, xAlloc, char);
1245     if (! xbuf)
1246         goto bad;
1247
1248     *(U32*)xbuf = PL_collation_ix;
1249     xout = sizeof(PL_collation_ix);
1250     for (xin = 0; xin < len; ) {
1251         Size_t xused;
1252
1253         for (;;) {
1254             xused = strxfrm(xbuf + xout, s + xin, xAlloc - xout);
1255             if (xused >= PERL_INT_MAX)
1256                 goto bad;
1257             if ((STRLEN)xused < xAlloc - xout)
1258                 break;
1259             xAlloc = (2 * xAlloc) + 1;
1260             Renew(xbuf, xAlloc, char);
1261             if (! xbuf)
1262                 goto bad;
1263         }
1264
1265         xin += strlen(s + xin) + 1;
1266         xout += xused;
1267
1268         /* Embedded NULs are understood but silently skipped
1269          * because they make no sense in locale collation. */
1270     }
1271
1272     xbuf[xout] = '\0';
1273     *xlen = xout - sizeof(PL_collation_ix);
1274     return xbuf;
1275
1276   bad:
1277     Safefree(xbuf);
1278     *xlen = 0;
1279     return NULL;
1280 }
1281
1282 #endif /* USE_LOCALE_COLLATE */
1283
1284 #ifdef USE_LOCALE
1285
1286 bool
1287 Perl__is_cur_LC_category_utf8(pTHX_ int category)
1288 {
1289     /* Returns TRUE if the current locale for 'category' is UTF-8; FALSE
1290      * otherwise. 'category' may not be LC_ALL.  If the platform doesn't have
1291      * nl_langinfo(), nor MB_CUR_MAX, this employs a heuristic, which hence
1292      * could give the wrong result.  The result will very likely be correct for
1293      * languages that have commonly used non-ASCII characters, but for notably
1294      * English, it comes down to if the locale's name ends in something like
1295      * "UTF-8".  It errs on the side of not being a UTF-8 locale. */
1296
1297     char *save_input_locale = NULL;
1298     STRLEN final_pos;
1299
1300 #ifdef LC_ALL
1301     assert(category != LC_ALL);
1302 #endif
1303
1304     /* First dispose of the trivial cases */
1305     save_input_locale = setlocale(category, NULL);
1306     if (! save_input_locale) {
1307         DEBUG_L(PerlIO_printf(Perl_debug_log,
1308                               "Could not find current locale for category %d\n",
1309                               category));
1310         return FALSE;   /* XXX maybe should croak */
1311     }
1312     save_input_locale = stdize_locale(savepv(save_input_locale));
1313     if (isNAME_C_OR_POSIX(save_input_locale)) {
1314         DEBUG_L(PerlIO_printf(Perl_debug_log,
1315                               "Current locale for category %d is %s\n",
1316                               category, save_input_locale));
1317         Safefree(save_input_locale);
1318         return FALSE;
1319     }
1320
1321 #if defined(USE_LOCALE_CTYPE)    \
1322     && (defined(MB_CUR_MAX) || (defined(HAS_NL_LANGINFO) && defined(CODESET)))
1323
1324     { /* Next try nl_langinfo or MB_CUR_MAX if available */
1325
1326         char *save_ctype_locale = NULL;
1327         bool is_utf8;
1328
1329         if (category != LC_CTYPE) { /* These work only on LC_CTYPE */
1330
1331             /* Get the current LC_CTYPE locale */
1332             save_ctype_locale = setlocale(LC_CTYPE, NULL);
1333             if (! save_ctype_locale) {
1334                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1335                                "Could not find current locale for LC_CTYPE\n"));
1336                 goto cant_use_nllanginfo;
1337             }
1338             save_ctype_locale = stdize_locale(savepv(save_ctype_locale));
1339
1340             /* If LC_CTYPE and the desired category use the same locale, this
1341              * means that finding the value for LC_CTYPE is the same as finding
1342              * the value for the desired category.  Otherwise, switch LC_CTYPE
1343              * to the desired category's locale */
1344             if (strEQ(save_ctype_locale, save_input_locale)) {
1345                 Safefree(save_ctype_locale);
1346                 save_ctype_locale = NULL;
1347             }
1348             else if (! setlocale(LC_CTYPE, save_input_locale)) {
1349                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1350                                     "Could not change LC_CTYPE locale to %s\n",
1351                                     save_input_locale));
1352                 Safefree(save_ctype_locale);
1353                 goto cant_use_nllanginfo;
1354             }
1355         }
1356
1357         DEBUG_L(PerlIO_printf(Perl_debug_log, "Current LC_CTYPE locale=%s\n",
1358                                               save_input_locale));
1359
1360         /* Here the current LC_CTYPE is set to the locale of the category whose
1361          * information is desired.  This means that nl_langinfo() and MB_CUR_MAX
1362          * should give the correct results */
1363
1364 #   if defined(HAS_NL_LANGINFO) && defined(CODESET)
1365         {
1366             char *codeset = nl_langinfo(CODESET);
1367             if (codeset && strNE(codeset, "")) {
1368                 codeset = savepv(codeset);
1369
1370                 /* If we switched LC_CTYPE, switch back */
1371                 if (save_ctype_locale) {
1372                     setlocale(LC_CTYPE, save_ctype_locale);
1373                     Safefree(save_ctype_locale);
1374                 }
1375
1376                 is_utf8 = foldEQ(codeset, STR_WITH_LEN("UTF-8"))
1377                         || foldEQ(codeset, STR_WITH_LEN("UTF8"));
1378
1379                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1380                        "\tnllanginfo returned CODESET '%s'; ?UTF8 locale=%d\n",
1381                                                      codeset,         is_utf8));
1382                 Safefree(codeset);
1383                 Safefree(save_input_locale);
1384                 return is_utf8;
1385             }
1386         }
1387
1388 #   endif
1389 #   ifdef MB_CUR_MAX
1390
1391         /* Here, either we don't have nl_langinfo, or it didn't return a
1392          * codeset.  Try MB_CUR_MAX */
1393
1394         /* Standard UTF-8 needs at least 4 bytes to represent the maximum
1395          * Unicode code point.  Since UTF-8 is the only non-single byte
1396          * encoding we handle, we just say any such encoding is UTF-8, and if
1397          * turns out to be wrong, other things will fail */
1398         is_utf8 = MB_CUR_MAX >= 4;
1399
1400         DEBUG_L(PerlIO_printf(Perl_debug_log,
1401                               "\tMB_CUR_MAX=%d; ?UTF8 locale=%d\n",
1402                                    (int) MB_CUR_MAX,      is_utf8));
1403
1404         Safefree(save_input_locale);
1405
1406 #       ifdef HAS_MBTOWC
1407
1408         /* ... But, most system that have MB_CUR_MAX will also have mbtowc(),
1409          * since they are both in the C99 standard.  We can feed a known byte
1410          * string to the latter function, and check that it gives the expected
1411          * result */
1412         if (is_utf8) {
1413             wchar_t wc;
1414             PERL_UNUSED_RESULT(mbtowc(&wc, NULL, 0));/* Reset any shift state */
1415             errno = 0;
1416             if ((size_t)mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8))
1417                                                         != strlen(HYPHEN_UTF8)
1418                 || wc != (wchar_t) 0x2010)
1419             {
1420                 is_utf8 = FALSE;
1421                 DEBUG_L(PerlIO_printf(Perl_debug_log, "\thyphen=U+%x\n", (unsigned int)wc));
1422                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1423                         "\treturn from mbtowc=%d; errno=%d; ?UTF8 locale=0\n",
1424                         mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8)), errno));
1425             }
1426         }
1427 #       endif
1428
1429         /* If we switched LC_CTYPE, switch back */
1430         if (save_ctype_locale) {
1431             setlocale(LC_CTYPE, save_ctype_locale);
1432             Safefree(save_ctype_locale);
1433         }
1434
1435         return is_utf8;
1436 #   endif
1437     }
1438
1439   cant_use_nllanginfo:
1440
1441 #else   /* nl_langinfo should work if available, so don't bother compiling this
1442            fallback code.  The final fallback of looking at the name is
1443            compiled, and will be executed if nl_langinfo fails */
1444
1445     /* nl_langinfo not available or failed somehow.  Next try looking at the
1446      * currency symbol to see if it disambiguates things.  Often that will be
1447      * in the native script, and if the symbol isn't in UTF-8, we know that the
1448      * locale isn't.  If it is non-ASCII UTF-8, we infer that the locale is
1449      * too, as the odds of a non-UTF8 string being valid UTF-8 are quite small
1450      * */
1451
1452 #ifdef HAS_LOCALECONV
1453 #   ifdef USE_LOCALE_MONETARY
1454     {
1455         char *save_monetary_locale = NULL;
1456         bool only_ascii = FALSE;
1457         bool is_utf8 = FALSE;
1458         struct lconv* lc;
1459
1460         /* Like above for LC_CTYPE, we first set LC_MONETARY to the locale of
1461          * the desired category, if it isn't that locale already */
1462
1463         if (category != LC_MONETARY) {
1464
1465             save_monetary_locale = setlocale(LC_MONETARY, NULL);
1466             if (! save_monetary_locale) {
1467                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1468                             "Could not find current locale for LC_MONETARY\n"));
1469                 goto cant_use_monetary;
1470             }
1471             save_monetary_locale = stdize_locale(savepv(save_monetary_locale));
1472
1473             if (strEQ(save_monetary_locale, save_input_locale)) {
1474                 Safefree(save_monetary_locale);
1475                 save_monetary_locale = NULL;
1476             }
1477             else if (! setlocale(LC_MONETARY, save_input_locale)) {
1478                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1479                             "Could not change LC_MONETARY locale to %s\n",
1480                                                         save_input_locale));
1481                 Safefree(save_monetary_locale);
1482                 goto cant_use_monetary;
1483             }
1484         }
1485
1486         /* Here the current LC_MONETARY is set to the locale of the category
1487          * whose information is desired. */
1488
1489         lc = localeconv();
1490         if (! lc
1491             || ! lc->currency_symbol
1492             || is_invariant_string((U8 *) lc->currency_symbol, 0))
1493         {
1494             DEBUG_L(PerlIO_printf(Perl_debug_log, "Couldn't get currency symbol for %s, or contains only ASCII; can't use for determining if UTF-8 locale\n", save_input_locale));
1495             only_ascii = TRUE;
1496         }
1497         else {
1498             is_utf8 = is_utf8_string((U8 *) lc->currency_symbol, 0);
1499         }
1500
1501         /* If we changed it, restore LC_MONETARY to its original locale */
1502         if (save_monetary_locale) {
1503             setlocale(LC_MONETARY, save_monetary_locale);
1504             Safefree(save_monetary_locale);
1505         }
1506
1507         if (! only_ascii) {
1508
1509             /* It isn't a UTF-8 locale if the symbol is not legal UTF-8;
1510              * otherwise assume the locale is UTF-8 if and only if the symbol
1511              * is non-ascii UTF-8. */
1512             DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?Currency symbol for %s is UTF-8=%d\n",
1513                                     save_input_locale, is_utf8));
1514             Safefree(save_input_locale);
1515             return is_utf8;
1516         }
1517     }
1518   cant_use_monetary:
1519
1520 #   endif /* USE_LOCALE_MONETARY */
1521 #endif /* HAS_LOCALECONV */
1522
1523 #if defined(HAS_STRFTIME) && defined(USE_LOCALE_TIME)
1524
1525 /* Still haven't found a non-ASCII string to disambiguate UTF-8 or not.  Try
1526  * the names of the months and weekdays, timezone, and am/pm indicator */
1527     {
1528         char *save_time_locale = NULL;
1529         int hour = 10;
1530         bool is_dst = FALSE;
1531         int dom = 1;
1532         int month = 0;
1533         int i;
1534         char * formatted_time;
1535
1536
1537         /* Like above for LC_MONETARY, we set LC_TIME to the locale of the
1538          * desired category, if it isn't that locale already */
1539
1540         if (category != LC_TIME) {
1541
1542             save_time_locale = setlocale(LC_TIME, NULL);
1543             if (! save_time_locale) {
1544                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1545                             "Could not find current locale for LC_TIME\n"));
1546                 goto cant_use_time;
1547             }
1548             save_time_locale = stdize_locale(savepv(save_time_locale));
1549
1550             if (strEQ(save_time_locale, save_input_locale)) {
1551                 Safefree(save_time_locale);
1552                 save_time_locale = NULL;
1553             }
1554             else if (! setlocale(LC_TIME, save_input_locale)) {
1555                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1556                             "Could not change LC_TIME locale to %s\n",
1557                                                         save_input_locale));
1558                 Safefree(save_time_locale);
1559                 goto cant_use_time;
1560             }
1561         }
1562
1563         /* Here the current LC_TIME is set to the locale of the category
1564          * whose information is desired.  Look at all the days of the week and
1565          * month names, and the timezone and am/pm indicator for UTF-8 variant
1566          * characters.  The first such a one found will tell us if the locale
1567          * is UTF-8 or not */
1568
1569         for (i = 0; i < 7 + 12; i++) {  /* 7 days; 12 months */
1570             formatted_time = my_strftime("%A %B %Z %p",
1571                                     0, 0, hour, dom, month, 112, 0, 0, is_dst);
1572             if (! formatted_time || is_invariant_string((U8 *) formatted_time, 0)) {
1573
1574                 /* Here, we didn't find a non-ASCII.  Try the next time through
1575                  * with the complemented dst and am/pm, and try with the next
1576                  * weekday.  After we have gotten all weekdays, try the next
1577                  * month */
1578                 is_dst = ! is_dst;
1579                 hour = (hour + 12) % 24;
1580                 dom++;
1581                 if (i > 6) {
1582                     month++;
1583                 }
1584                 continue;
1585             }
1586
1587             /* Here, we have a non-ASCII.  Return TRUE is it is valid UTF8;
1588              * false otherwise.  But first, restore LC_TIME to its original
1589              * locale if we changed it */
1590             if (save_time_locale) {
1591                 setlocale(LC_TIME, save_time_locale);
1592                 Safefree(save_time_locale);
1593             }
1594
1595             DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?time-related strings for %s are UTF-8=%d\n",
1596                                 save_input_locale,
1597                                 is_utf8_string((U8 *) formatted_time, 0)));
1598             Safefree(save_input_locale);
1599             return is_utf8_string((U8 *) formatted_time, 0);
1600         }
1601
1602         /* Falling off the end of the loop indicates all the names were just
1603          * ASCII.  Go on to the next test.  If we changed it, restore LC_TIME
1604          * to its original locale */
1605         if (save_time_locale) {
1606             setlocale(LC_TIME, save_time_locale);
1607             Safefree(save_time_locale);
1608         }
1609         DEBUG_L(PerlIO_printf(Perl_debug_log, "All time-related words for %s contain only ASCII; can't use for determining if UTF-8 locale\n", save_input_locale));
1610     }
1611   cant_use_time:
1612
1613 #endif
1614
1615 #if 0 && defined(USE_LOCALE_MESSAGES) && defined(HAS_SYS_ERRLIST)
1616
1617 /* This code is ifdefd out because it was found to not be necessary in testing
1618  * on our dromedary test machine, which has over 700 locales.  There, this
1619  * added no value to looking at the currency symbol and the time strings.  I
1620  * left it in so as to avoid rewriting it if real-world experience indicates
1621  * that dromedary is an outlier.  Essentially, instead of returning abpve if we
1622  * haven't found illegal utf8, we continue on and examine all the strerror()
1623  * messages on the platform for utf8ness.  If all are ASCII, we still don't
1624  * know the answer; but otherwise we have a pretty good indication of the
1625  * utf8ness.  The reason this doesn't help much is that the messages may not
1626  * have been translated into the locale.  The currency symbol and time strings
1627  * are much more likely to have been translated.  */
1628     {
1629         int e;
1630         bool is_utf8 = FALSE;
1631         bool non_ascii = FALSE;
1632         char *save_messages_locale = NULL;
1633         const char * errmsg = NULL;
1634
1635         /* Like above, we set LC_MESSAGES to the locale of the desired
1636          * category, if it isn't that locale already */
1637
1638         if (category != LC_MESSAGES) {
1639
1640             save_messages_locale = setlocale(LC_MESSAGES, NULL);
1641             if (! save_messages_locale) {
1642                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1643                             "Could not find current locale for LC_MESSAGES\n"));
1644                 goto cant_use_messages;
1645             }
1646             save_messages_locale = stdize_locale(savepv(save_messages_locale));
1647
1648             if (strEQ(save_messages_locale, save_input_locale)) {
1649                 Safefree(save_messages_locale);
1650                 save_messages_locale = NULL;
1651             }
1652             else if (! setlocale(LC_MESSAGES, save_input_locale)) {
1653                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1654                             "Could not change LC_MESSAGES locale to %s\n",
1655                                                         save_input_locale));
1656                 Safefree(save_messages_locale);
1657                 goto cant_use_messages;
1658             }
1659         }
1660
1661         /* Here the current LC_MESSAGES is set to the locale of the category
1662          * whose information is desired.  Look through all the messages.  We
1663          * can't use Strerror() here because it may expand to code that
1664          * segfaults in miniperl */
1665
1666         for (e = 0; e <= sys_nerr; e++) {
1667             errno = 0;
1668             errmsg = sys_errlist[e];
1669             if (errno || !errmsg) {
1670                 break;
1671             }
1672             errmsg = savepv(errmsg);
1673             if (! is_invariant_string((U8 *) errmsg, 0)) {
1674                 non_ascii = TRUE;
1675                 is_utf8 = is_utf8_string((U8 *) errmsg, 0);
1676                 break;
1677             }
1678         }
1679         Safefree(errmsg);
1680
1681         /* And, if we changed it, restore LC_MESSAGES to its original locale */
1682         if (save_messages_locale) {
1683             setlocale(LC_MESSAGES, save_messages_locale);
1684             Safefree(save_messages_locale);
1685         }
1686
1687         if (non_ascii) {
1688
1689             /* Any non-UTF-8 message means not a UTF-8 locale; if all are valid,
1690              * any non-ascii means it is one; otherwise we assume it isn't */
1691             DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?error messages for %s are UTF-8=%d\n",
1692                                 save_input_locale,
1693                                 is_utf8));
1694             Safefree(save_input_locale);
1695             return is_utf8;
1696         }
1697
1698         DEBUG_L(PerlIO_printf(Perl_debug_log, "All error messages for %s contain only ASCII; can't use for determining if UTF-8 locale\n", save_input_locale));
1699     }
1700   cant_use_messages:
1701
1702 #endif
1703
1704 #endif /* the code that is compiled when no nl_langinfo */
1705
1706 #ifndef EBCDIC  /* On os390, even if the name ends with "UTF-8', it isn't a
1707                    UTF-8 locale */
1708     /* As a last resort, look at the locale name to see if it matches
1709      * qr/UTF -?  * 8 /ix, or some other common locale names.  This "name", the
1710      * return of setlocale(), is actually defined to be opaque, so we can't
1711      * really rely on the absence of various substrings in the name to indicate
1712      * its UTF-8ness, but if it has UTF8 in the name, it is extremely likely to
1713      * be a UTF-8 locale.  Similarly for the other common names */
1714
1715     final_pos = strlen(save_input_locale) - 1;
1716     if (final_pos >= 3) {
1717         char *name = save_input_locale;
1718
1719         /* Find next 'U' or 'u' and look from there */
1720         while ((name += strcspn(name, "Uu") + 1)
1721                                             <= save_input_locale + final_pos - 2)
1722         {
1723             if (!isALPHA_FOLD_NE(*name, 't')
1724                 || isALPHA_FOLD_NE(*(name + 1), 'f'))
1725             {
1726                 continue;
1727             }
1728             name += 2;
1729             if (*(name) == '-') {
1730                 if ((name > save_input_locale + final_pos - 1)) {
1731                     break;
1732                 }
1733                 name++;
1734             }
1735             if (*(name) == '8') {
1736                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1737                                       "Locale %s ends with UTF-8 in name\n",
1738                                       save_input_locale));
1739                 Safefree(save_input_locale);
1740                 return TRUE;
1741             }
1742         }
1743         DEBUG_L(PerlIO_printf(Perl_debug_log,
1744                               "Locale %s doesn't end with UTF-8 in name\n",
1745                                 save_input_locale));
1746     }
1747 #endif
1748
1749 #ifdef WIN32
1750     /* http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756.aspx */
1751     if (final_pos >= 4
1752         && *(save_input_locale + final_pos - 0) == '1'
1753         && *(save_input_locale + final_pos - 1) == '0'
1754         && *(save_input_locale + final_pos - 2) == '0'
1755         && *(save_input_locale + final_pos - 3) == '5'
1756         && *(save_input_locale + final_pos - 4) == '6')
1757     {
1758         DEBUG_L(PerlIO_printf(Perl_debug_log,
1759                         "Locale %s ends with 10056 in name, is UTF-8 locale\n",
1760                         save_input_locale));
1761         Safefree(save_input_locale);
1762         return TRUE;
1763     }
1764 #endif
1765
1766     /* Other common encodings are the ISO 8859 series, which aren't UTF-8.  But
1767      * since we are about to return FALSE anyway, there is no point in doing
1768      * this extra work */
1769 #if 0
1770     if (instr(save_input_locale, "8859")) {
1771         DEBUG_L(PerlIO_printf(Perl_debug_log,
1772                              "Locale %s has 8859 in name, not UTF-8 locale\n",
1773                              save_input_locale));
1774         Safefree(save_input_locale);
1775         return FALSE;
1776     }
1777 #endif
1778
1779     DEBUG_L(PerlIO_printf(Perl_debug_log,
1780                           "Assuming locale %s is not a UTF-8 locale\n",
1781                                     save_input_locale));
1782     Safefree(save_input_locale);
1783     return FALSE;
1784 }
1785
1786 #endif
1787
1788
1789 bool
1790 Perl__is_in_locale_category(pTHX_ const bool compiling, const int category)
1791 {
1792     dVAR;
1793     /* Internal function which returns if we are in the scope of a pragma that
1794      * enables the locale category 'category'.  'compiling' should indicate if
1795      * this is during the compilation phase (TRUE) or not (FALSE). */
1796
1797     const COP * const cop = (compiling) ? &PL_compiling : PL_curcop;
1798
1799     SV *categories = cop_hints_fetch_pvs(cop, "locale", 0);
1800     if (! categories || categories == &PL_sv_placeholder) {
1801         return FALSE;
1802     }
1803
1804     /* The pseudo-category 'not_characters' is -1, so just add 1 to each to get
1805      * a valid unsigned */
1806     assert(category >= -1);
1807     return cBOOL(SvUV(categories) & (1U << (category + 1)));
1808 }
1809
1810 char *
1811 Perl_my_strerror(pTHX_ const int errnum) {
1812
1813     /* Uses C locale for the error text unless within scope of 'use locale' for
1814      * LC_MESSAGES */
1815
1816 #ifdef USE_LOCALE_MESSAGES
1817     if (! IN_LC(LC_MESSAGES)) {
1818         char * save_locale = setlocale(LC_MESSAGES, NULL);
1819         if (! isNAME_C_OR_POSIX(save_locale)) {
1820             char *errstr;
1821
1822             /* The next setlocale likely will zap this, so create a copy */
1823             save_locale = savepv(save_locale);
1824
1825             setlocale(LC_MESSAGES, "C");
1826
1827             /* This points to the static space in Strerror, with all its
1828              * limitations */
1829             errstr = Strerror(errnum);
1830
1831             setlocale(LC_MESSAGES, save_locale);
1832             Safefree(save_locale);
1833             return errstr;
1834         }
1835     }
1836 #endif
1837
1838     return Strerror(errnum);
1839 }
1840
1841 /*
1842
1843 =head1 Locale-related functions and macros
1844
1845 =for apidoc sync_locale
1846
1847 Changing the program's locale should be avoided by XS code.  Nevertheless,
1848 certain non-Perl libraries called from XS, such as C<Gtk> do so.  When this
1849 happens, Perl needs to be told that the locale has changed.  Use this function
1850 to do so, before returning to Perl.
1851
1852 =cut
1853 */
1854
1855 void
1856 Perl_sync_locale(pTHX)
1857 {
1858
1859 #ifdef USE_LOCALE_CTYPE
1860     new_ctype(setlocale(LC_CTYPE, NULL));
1861 #endif /* USE_LOCALE_CTYPE */
1862
1863 #ifdef USE_LOCALE_COLLATE
1864     new_collate(setlocale(LC_COLLATE, NULL));
1865 #endif
1866
1867 #ifdef USE_LOCALE_NUMERIC
1868     set_numeric_local();    /* Switch from "C" to underlying LC_NUMERIC */
1869     new_numeric(setlocale(LC_NUMERIC, NULL));
1870 #endif /* USE_LOCALE_NUMERIC */
1871
1872 }
1873
1874 #if defined(DEBUGGING) && defined(USE_LOCALE)
1875
1876 char *
1877 Perl__setlocale_debug_string(const int category,        /* category number,
1878                                                            like LC_ALL */
1879                             const char* const locale,   /* locale name */
1880
1881                             /* return value from setlocale() when attempting to
1882                              * set 'category' to 'locale' */
1883                             const char* const retval)
1884 {
1885     /* Returns a pointer to a NUL-terminated string in static storage with
1886      * added text about the info passed in.  This is not thread safe and will
1887      * be overwritten by the next call, so this should be used just to
1888      * formulate a string to immediately print or savepv() on. */
1889
1890     /* initialise to a non-null value to keep it out of BSS and so keep
1891      * -DPERL_GLOBAL_STRUCT_PRIVATE happy */
1892     static char ret[128] = "x";
1893
1894     my_strlcpy(ret, "setlocale(", sizeof(ret));
1895
1896     switch (category) {
1897         default:
1898             my_snprintf(ret, sizeof(ret), "%s? %d", ret, category);
1899             break;
1900 #   ifdef LC_ALL
1901         case LC_ALL:
1902             my_strlcat(ret, "LC_ALL", sizeof(ret));
1903             break;
1904 #   endif
1905 #   ifdef LC_CTYPE
1906         case LC_CTYPE:
1907             my_strlcat(ret, "LC_CTYPE", sizeof(ret));
1908             break;
1909 #   endif
1910 #   ifdef LC_NUMERIC
1911         case LC_NUMERIC:
1912             my_strlcat(ret, "LC_NUMERIC", sizeof(ret));
1913             break;
1914 #   endif
1915 #   ifdef LC_COLLATE
1916         case LC_COLLATE:
1917             my_strlcat(ret, "LC_COLLATE", sizeof(ret));
1918             break;
1919 #   endif
1920 #   ifdef LC_TIME
1921         case LC_TIME:
1922             my_strlcat(ret, "LC_TIME", sizeof(ret));
1923             break;
1924 #   endif
1925 #   ifdef LC_MONETARY
1926         case LC_MONETARY:
1927             my_strlcat(ret, "LC_MONETARY", sizeof(ret));
1928             break;
1929 #   endif
1930 #   ifdef LC_MESSAGES
1931         case LC_MESSAGES:
1932             my_strlcat(ret, "LC_MESSAGES", sizeof(ret));
1933             break;
1934 #   endif
1935     }
1936
1937     my_strlcat(ret, ", ", sizeof(ret));
1938
1939     if (locale) {
1940         my_strlcat(ret, "\"", sizeof(ret));
1941         my_strlcat(ret, locale, sizeof(ret));
1942         my_strlcat(ret, "\"", sizeof(ret));
1943     }
1944     else {
1945         my_strlcat(ret, "NULL", sizeof(ret));
1946     }
1947
1948     my_strlcat(ret, ") returned ", sizeof(ret));
1949
1950     if (retval) {
1951         my_strlcat(ret, "\"", sizeof(ret));
1952         my_strlcat(ret, retval, sizeof(ret));
1953         my_strlcat(ret, "\"", sizeof(ret));
1954     }
1955     else {
1956         my_strlcat(ret, "NULL", sizeof(ret));
1957     }
1958
1959     assert(strlen(ret) < sizeof(ret));
1960
1961     return ret;
1962 }
1963
1964 #endif
1965
1966
1967 /*
1968  * ex: set ts=8 sts=4 sw=4 et:
1969  */