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