This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Dump empty-string ENAMEs as empty strings
[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 more 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      * The design of locale collation is that every locale change is given an
465      * index 'PL_collation_ix'.  The first time a string particpates in an
466      * operation that requires collation while locale collation is active, it
467      * is given PERL_MAGIC_collxfrm magic (via sv_collxfrm_flags()).  That
468      * magic includes the collation index, and the transformation of the string
469      * by strxfrm(), q.v.  That transformation is used when doing comparisons,
470      * instead of the string itself.  If a string changes, the magic is
471      * cleared.  The next time the locale changes, the index is incremented,
472      * and so we know during a comparison that the transformation is not
473      * necessarily still valid, and so is recomputed.  Note that if the locale
474      * changes enough times, the index could wrap (a U32), and it is possible
475      * that a transformation would improperly be considered valid, leading to
476      * an unlikely bug */
477
478     if (! newcoll) {
479         if (PL_collation_name) {
480             ++PL_collation_ix;
481             Safefree(PL_collation_name);
482             PL_collation_name = NULL;
483         }
484         PL_collation_standard = TRUE;
485         PL_collxfrm_base = 0;
486         PL_collxfrm_mult = 2;
487         return;
488     }
489
490     /* If this is not the same locale as currently, set the new one up */
491     if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
492         ++PL_collation_ix;
493         Safefree(PL_collation_name);
494         PL_collation_name = stdize_locale(savepv(newcoll));
495         PL_collation_standard = isNAME_C_OR_POSIX(newcoll);
496
497         {
498             /* A locale collation definition includes primary, secondary,
499              * tertiary, etc. weights for each character.  To sort, the primary
500              * weights are used, and only if they compare equal, then the
501              * secondary weights are used, and only if they compare equal, then
502              * the tertiary, etc.  strxfrm() works by taking the input string,
503              * say ABC, and creating an output string consisting of first the
504              * primary weights, A¹B¹C¹ followed by the secondary ones, A²B²C²;
505              * and then the tertiary, etc, yielding A¹B¹C¹A²B²C²A³B³C³....
506              * Some characters may not have weights at every level.  In our
507              * example, let's say B doesn't have a tertiary weight, and A
508              * doesn't have a secondary weight.  The constructed string is then
509              * going to be A¹B¹C¹B²C²A³C³....  This has the desired
510              * characteristics that strcmp() will look at the secondary or
511              * tertiary weights only if the strings compare equal at all higher
512              * priority weights.  The length of the transformed string is
513              * roughly a linear function of the input string.  It's not exactly
514              * linear because some characters don't have weights at all levels,
515              * and there are some complications, so there is often per-string
516              * overhead.  When we call strxfrm() we have to allocate some
517              * memory to hold the transformed string.  The calculations below
518              * try to find constants for this locale 'm' and 'b' so that m*x +
519              * b equals how much space we need given the size of the input
520              * string in 'x'.  If we calculate too small, we increase the size
521              * as needed, and call strxfrm() again, but it is better to get it
522              * right the first time to avoid wasted expensive string
523              * transformations. */
524           /*  2: at most so many chars ('a', 'b'). */
525           /* 50: surely no system expands a char more. */
526 #define XFRMBUFSIZE  (2 * 50)
527           char xbuf[XFRMBUFSIZE];
528           const Size_t fa = strxfrm(xbuf, "a",  XFRMBUFSIZE);
529           const Size_t fb = strxfrm(xbuf, "ab", XFRMBUFSIZE);
530           const SSize_t mult = fb - fa;
531           if (mult < 1 && !(fa == 0 && fb == 0))
532               Perl_croak(aTHX_ "panic: strxfrm() gets absurd - a => %"UVuf", ab => %"UVuf,
533                          (UV) fa, (UV) fb);
534           PL_collxfrm_base = (fa > (Size_t)mult) ? (fa - mult) : 0;
535           PL_collxfrm_mult = mult;
536         }
537     }
538
539 #else
540     PERL_UNUSED_ARG(newcoll);
541 #endif /* USE_LOCALE_COLLATE */
542 }
543
544 #ifdef WIN32
545
546 char *
547 Perl_my_setlocale(pTHX_ int category, const char* locale)
548 {
549     /* This, for Windows, emulates POSIX setlocale() behavior.  There is no
550      * difference unless the input locale is "", which means on Windows to get
551      * the machine default, which is set via the computer's "Regional and
552      * Language Options" (or its current equivalent).  In POSIX, it instead
553      * means to find the locale from the user's environment.  This routine
554      * looks in the environment, and, if anything is found, uses that instead
555      * of going to the machine default.  If there is no environment override,
556      * the machine default is used, as normal, by calling the real setlocale()
557      * with "".  The POSIX behavior is to use the LC_ALL variable if set;
558      * otherwise to use the particular category's variable if set; otherwise to
559      * use the LANG variable. */
560
561     bool override_LC_ALL = FALSE;
562     char * result;
563
564     if (locale && strEQ(locale, "")) {
565 #   ifdef LC_ALL
566         locale = PerlEnv_getenv("LC_ALL");
567         if (! locale) {
568 #endif
569             switch (category) {
570 #   ifdef LC_ALL
571                 case LC_ALL:
572                     override_LC_ALL = TRUE;
573                     break;  /* We already know its variable isn't set */
574 #   endif
575 #   ifdef USE_LOCALE_TIME
576                 case LC_TIME:
577                     locale = PerlEnv_getenv("LC_TIME");
578                     break;
579 #   endif
580 #   ifdef USE_LOCALE_CTYPE
581                 case LC_CTYPE:
582                     locale = PerlEnv_getenv("LC_CTYPE");
583                     break;
584 #   endif
585 #   ifdef USE_LOCALE_COLLATE
586                 case LC_COLLATE:
587                     locale = PerlEnv_getenv("LC_COLLATE");
588                     break;
589 #   endif
590 #   ifdef USE_LOCALE_MONETARY
591                 case LC_MONETARY:
592                     locale = PerlEnv_getenv("LC_MONETARY");
593                     break;
594 #   endif
595 #   ifdef USE_LOCALE_NUMERIC
596                 case LC_NUMERIC:
597                     locale = PerlEnv_getenv("LC_NUMERIC");
598                     break;
599 #   endif
600 #   ifdef USE_LOCALE_MESSAGES
601                 case LC_MESSAGES:
602                     locale = PerlEnv_getenv("LC_MESSAGES");
603                     break;
604 #   endif
605                 default:
606                     /* This is a category, like PAPER_SIZE that we don't
607                      * know about; and so can't provide a wrapper. */
608                     break;
609             }
610             if (! locale) {
611                 locale = PerlEnv_getenv("LANG");
612                 if (! locale) {
613                     locale = "";
614                 }
615             }
616 #   ifdef LC_ALL
617         }
618 #   endif
619     }
620
621     result = setlocale(category, locale);
622     DEBUG_L(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n", __FILE__, __LINE__,
623                             _setlocale_debug_string(category, locale, result)));
624
625     if (! override_LC_ALL)  {
626         return result;
627     }
628
629     /* Here the input category was LC_ALL, and we have set it to what is in the
630      * LANG variable or the system default if there is no LANG.  But these have
631      * lower priority than the other LC_foo variables, so override it for each
632      * one that is set.  (If they are set to "", it means to use the same thing
633      * we just set LC_ALL to, so can skip) */
634 #   ifdef USE_LOCALE_TIME
635     result = PerlEnv_getenv("LC_TIME");
636     if (result && strNE(result, "")) {
637         setlocale(LC_TIME, result);
638         DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
639                     __FILE__, __LINE__,
640                     _setlocale_debug_string(LC_TIME, result, "not captured")));
641     }
642 #   endif
643 #   ifdef USE_LOCALE_CTYPE
644     result = PerlEnv_getenv("LC_CTYPE");
645     if (result && strNE(result, "")) {
646         setlocale(LC_CTYPE, result);
647         DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
648                     __FILE__, __LINE__,
649                     _setlocale_debug_string(LC_CTYPE, result, "not captured")));
650     }
651 #   endif
652 #   ifdef USE_LOCALE_COLLATE
653     result = PerlEnv_getenv("LC_COLLATE");
654     if (result && strNE(result, "")) {
655         setlocale(LC_COLLATE, result);
656         DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
657                   __FILE__, __LINE__,
658                   _setlocale_debug_string(LC_COLLATE, result, "not captured")));
659     }
660 #   endif
661 #   ifdef USE_LOCALE_MONETARY
662     result = PerlEnv_getenv("LC_MONETARY");
663     if (result && strNE(result, "")) {
664         setlocale(LC_MONETARY, result);
665         DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
666                  __FILE__, __LINE__,
667                  _setlocale_debug_string(LC_MONETARY, result, "not captured")));
668     }
669 #   endif
670 #   ifdef USE_LOCALE_NUMERIC
671     result = PerlEnv_getenv("LC_NUMERIC");
672     if (result && strNE(result, "")) {
673         setlocale(LC_NUMERIC, result);
674         DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
675                  __FILE__, __LINE__,
676                  _setlocale_debug_string(LC_NUMERIC, result, "not captured")));
677     }
678 #   endif
679 #   ifdef USE_LOCALE_MESSAGES
680     result = PerlEnv_getenv("LC_MESSAGES");
681     if (result && strNE(result, "")) {
682         setlocale(LC_MESSAGES, result);
683         DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
684                  __FILE__, __LINE__,
685                  _setlocale_debug_string(LC_MESSAGES, result, "not captured")));
686     }
687 #   endif
688
689     result = setlocale(LC_ALL, NULL);
690     DEBUG_L(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
691                                __FILE__, __LINE__,
692                                _setlocale_debug_string(LC_ALL, NULL, result)));
693
694     return result;
695 }
696
697 #endif
698
699
700 /*
701  * Initialize locale awareness.
702  */
703 int
704 Perl_init_i18nl10n(pTHX_ int printwarn)
705 {
706     /* printwarn is
707      *
708      *    0 if not to output warning when setup locale is bad
709      *    1 if to output warning based on value of PERL_BADLANG
710      *    >1 if to output regardless of PERL_BADLANG
711      *
712      * returns
713      *    1 = set ok or not applicable,
714      *    0 = fallback to a locale of lower priority
715      *   -1 = fallback to all locales failed, not even to the C locale
716      *
717      * Under -DDEBUGGING, if the environment variable PERL_DEBUG_LOCALE_INIT is
718      * set, debugging information is output.
719      *
720      * This looks more complicated than it is, mainly due to the #ifdefs.
721      *
722      * We try to set LC_ALL to the value determined by the environment.  If
723      * there is no LC_ALL on this platform, we try the individual categories we
724      * know about.  If this works, we are done.
725      *
726      * But if it doesn't work, we have to do something else.  We search the
727      * environment variables ourselves instead of relying on the system to do
728      * it.  We look at, in order, LC_ALL, LANG, a system default locale (if we
729      * think there is one), and the ultimate fallback "C".  This is all done in
730      * the same loop as above to avoid duplicating code, but it makes things
731      * more complex.  After the original failure, we add the fallback
732      * possibilities to the list of locales to try, and iterate the loop
733      * through them all until one succeeds.
734      *
735      * On Ultrix, the locale MUST come from the environment, so there is
736      * preliminary code to set it.  I (khw) am not sure that it is necessary,
737      * and that this couldn't be folded into the loop, but barring any real
738      * platforms to test on, it's staying as-is
739      *
740      * A slight complication is that in embedded Perls, the locale may already
741      * be set-up, and we don't want to get it from the normal environment
742      * variables.  This is handled by having a special environment variable
743      * indicate we're in this situation.  We simply set setlocale's 2nd
744      * parameter to be a NULL instead of "".  That indicates to setlocale that
745      * it is not to change anything, but to return the current value,
746      * effectively initializing perl's db to what the locale already is.
747      *
748      * We play the same trick with NULL if a LC_ALL succeeds.  We call
749      * setlocale() on the individual categores with NULL to get their existing
750      * values for our db, instead of trying to change them.
751      * */
752
753     int ok = 1;
754
755 #if defined(USE_LOCALE)
756 #ifdef USE_LOCALE_CTYPE
757     char *curctype   = NULL;
758 #endif /* USE_LOCALE_CTYPE */
759 #ifdef USE_LOCALE_COLLATE
760     char *curcoll    = NULL;
761 #endif /* USE_LOCALE_COLLATE */
762 #ifdef USE_LOCALE_NUMERIC
763     char *curnum     = NULL;
764 #endif /* USE_LOCALE_NUMERIC */
765 #ifdef __GLIBC__
766     const char * const language   = savepv(PerlEnv_getenv("LANGUAGE"));
767 #endif
768
769     /* NULL uses the existing already set up locale */
770     const char * const setlocale_init = (PerlEnv_getenv("PERL_SKIP_LOCALE_INIT"))
771                                         ? NULL
772                                         : "";
773 #ifdef DEBUGGING
774     const bool debug = (PerlEnv_getenv("PERL_DEBUG_LOCALE_INIT"))
775                        ? TRUE
776                        : FALSE;
777 #   define DEBUG_LOCALE_INIT(category, locale, result)                      \
778         STMT_START {                                                        \
779                 if (debug) {                                                \
780                     PerlIO_printf(Perl_debug_log,                           \
781                                   "%s:%d: %s\n",                            \
782                                   __FILE__, __LINE__,                       \
783                                   _setlocale_debug_string(category,         \
784                                                           locale,           \
785                                                           result));         \
786                 }                                                           \
787         } STMT_END
788 #else
789 #   define DEBUG_LOCALE_INIT(a,b,c)
790 #endif
791     const char* trial_locales[5];   /* 5 = 1 each for "", LC_ALL, LANG, "", C */
792     unsigned int trial_locales_count;
793     const char * const lc_all     = savepv(PerlEnv_getenv("LC_ALL"));
794     const char * const lang       = savepv(PerlEnv_getenv("LANG"));
795     bool setlocale_failure = FALSE;
796     unsigned int i;
797     char *p;
798
799     /* A later getenv() could zap this, so only use here */
800     const char * const bad_lang_use_once = PerlEnv_getenv("PERL_BADLANG");
801
802     const bool locwarn = (printwarn > 1
803                           || (printwarn
804                               && (! bad_lang_use_once
805                                   || (
806                                     /* disallow with "" or "0" */
807                                     *bad_lang_use_once
808                                     && strNE("0", bad_lang_use_once)))));
809     bool done = FALSE;
810     char * sl_result;   /* return from setlocale() */
811     char * locale_param;
812 #ifdef WIN32
813     /* In some systems you can find out the system default locale
814      * and use that as the fallback locale. */
815 #   define SYSTEM_DEFAULT_LOCALE
816 #endif
817 #ifdef SYSTEM_DEFAULT_LOCALE
818     const char *system_default_locale = NULL;
819 #endif
820
821 #ifndef LOCALE_ENVIRON_REQUIRED
822     PERL_UNUSED_VAR(done);
823     PERL_UNUSED_VAR(locale_param);
824 #else
825
826     /*
827      * Ultrix setlocale(..., "") fails if there are no environment
828      * variables from which to get a locale name.
829      */
830
831 #   ifdef LC_ALL
832     if (lang) {
833         sl_result = my_setlocale(LC_ALL, setlocale_init);
834         DEBUG_LOCALE_INIT(LC_ALL, setlocale_init, sl_result);
835         if (sl_result)
836             done = TRUE;
837         else
838             setlocale_failure = TRUE;
839     }
840     if (! setlocale_failure) {
841 #       ifdef USE_LOCALE_CTYPE
842         locale_param = (! done && (lang || PerlEnv_getenv("LC_CTYPE")))
843                        ? setlocale_init
844                        : NULL;
845         curctype = my_setlocale(LC_CTYPE, locale_param);
846         DEBUG_LOCALE_INIT(LC_CTYPE, locale_param, sl_result);
847         if (! curctype)
848             setlocale_failure = TRUE;
849         else
850             curctype = savepv(curctype);
851 #       endif /* USE_LOCALE_CTYPE */
852 #       ifdef USE_LOCALE_COLLATE
853         locale_param = (! done && (lang || PerlEnv_getenv("LC_COLLATE")))
854                        ? setlocale_init
855                        : NULL;
856         curcoll = my_setlocale(LC_COLLATE, locale_param);
857         DEBUG_LOCALE_INIT(LC_COLLATE, locale_param, sl_result);
858         if (! curcoll)
859             setlocale_failure = TRUE;
860         else
861             curcoll = savepv(curcoll);
862 #       endif /* USE_LOCALE_COLLATE */
863 #       ifdef USE_LOCALE_NUMERIC
864         locale_param = (! done && (lang || PerlEnv_getenv("LC_NUMERIC")))
865                        ? setlocale_init
866                        : NULL;
867         curnum = my_setlocale(LC_NUMERIC, locale_param);
868         DEBUG_LOCALE_INIT(LC_NUMERIC, locale_param, sl_result);
869         if (! curnum)
870             setlocale_failure = TRUE;
871         else
872             curnum = savepv(curnum);
873 #       endif /* USE_LOCALE_NUMERIC */
874 #       ifdef USE_LOCALE_MESSAGES
875         locale_param = (! done && (lang || PerlEnv_getenv("LC_MESSAGES")))
876                        ? setlocale_init
877                        : NULL;
878         sl_result = my_setlocale(LC_MESSAGES, locale_param);
879         DEBUG_LOCALE_INIT(LC_MESSAGES, locale_param, sl_result);
880         if (! sl_result)
881             setlocale_failure = TRUE;
882         }
883 #       endif /* USE_LOCALE_MESSAGES */
884 #       ifdef USE_LOCALE_MONETARY
885         locale_param = (! done && (lang || PerlEnv_getenv("LC_MONETARY")))
886                        ? setlocale_init
887                        : NULL;
888         sl_result = my_setlocale(LC_MONETARY, locale_param);
889         DEBUG_LOCALE_INIT(LC_MONETARY, locale_param, sl_result);
890         if (! sl_result) {
891             setlocale_failure = TRUE;
892         }
893 #       endif /* USE_LOCALE_MONETARY */
894     }
895
896 #   endif /* LC_ALL */
897
898 #endif /* !LOCALE_ENVIRON_REQUIRED */
899
900     /* We try each locale in the list until we get one that works, or exhaust
901      * the list.  Normally the loop is executed just once.  But if setting the
902      * locale fails, inside the loop we add fallback trials to the array and so
903      * will execute the loop multiple times */
904     trial_locales[0] = setlocale_init;
905     trial_locales_count = 1;
906     for (i= 0; i < trial_locales_count; i++) {
907         const char * trial_locale = trial_locales[i];
908
909         if (i > 0) {
910
911             /* XXX This is to preserve old behavior for LOCALE_ENVIRON_REQUIRED
912              * when i==0, but I (khw) don't think that behavior makes much
913              * sense */
914             setlocale_failure = FALSE;
915
916 #ifdef SYSTEM_DEFAULT_LOCALE
917 #  ifdef WIN32
918             /* On Windows machines, an entry of "" after the 0th means to use
919              * the system default locale, which we now proceed to get. */
920             if (strEQ(trial_locale, "")) {
921                 unsigned int j;
922
923                 /* Note that this may change the locale, but we are going to do
924                  * that anyway just below */
925                 system_default_locale = setlocale(LC_ALL, "");
926                 DEBUG_LOCALE_INIT(LC_ALL, "", system_default_locale);
927
928                 /* Skip if invalid or it's already on the list of locales to
929                  * try */
930                 if (! system_default_locale) {
931                     goto next_iteration;
932                 }
933                 for (j = 0; j < trial_locales_count; j++) {
934                     if (strEQ(system_default_locale, trial_locales[j])) {
935                         goto next_iteration;
936                     }
937                 }
938
939                 trial_locale = system_default_locale;
940             }
941 #  endif /* WIN32 */
942 #endif /* SYSTEM_DEFAULT_LOCALE */
943         }
944
945 #ifdef LC_ALL
946         sl_result = my_setlocale(LC_ALL, trial_locale);
947         DEBUG_LOCALE_INIT(LC_ALL, trial_locale, sl_result);
948         if (! sl_result) {
949             setlocale_failure = TRUE;
950         }
951         else {
952             /* Since LC_ALL succeeded, it should have changed all the other
953              * categories it can to its value; so we massage things so that the
954              * setlocales below just return their category's current values.
955              * This adequately handles the case in NetBSD where LC_COLLATE may
956              * not be defined for a locale, and setting it individually will
957              * fail, whereas setting LC_ALL suceeds, leaving LC_COLLATE set to
958              * the POSIX locale. */
959             trial_locale = NULL;
960         }
961 #endif /* LC_ALL */
962
963         if (!setlocale_failure) {
964 #ifdef USE_LOCALE_CTYPE
965             Safefree(curctype);
966             curctype = my_setlocale(LC_CTYPE, trial_locale);
967             DEBUG_LOCALE_INIT(LC_CTYPE, trial_locale, curctype);
968             if (! curctype)
969                 setlocale_failure = TRUE;
970             else
971                 curctype = savepv(curctype);
972 #endif /* USE_LOCALE_CTYPE */
973 #ifdef USE_LOCALE_COLLATE
974             Safefree(curcoll);
975             curcoll = my_setlocale(LC_COLLATE, trial_locale);
976             DEBUG_LOCALE_INIT(LC_COLLATE, trial_locale, curcoll);
977             if (! curcoll)
978                 setlocale_failure = TRUE;
979             else
980                 curcoll = savepv(curcoll);
981 #endif /* USE_LOCALE_COLLATE */
982 #ifdef USE_LOCALE_NUMERIC
983             Safefree(curnum);
984             curnum = my_setlocale(LC_NUMERIC, trial_locale);
985             DEBUG_LOCALE_INIT(LC_NUMERIC, trial_locale, curnum);
986             if (! curnum)
987                 setlocale_failure = TRUE;
988             else
989                 curnum = savepv(curnum);
990 #endif /* USE_LOCALE_NUMERIC */
991 #ifdef USE_LOCALE_MESSAGES
992             sl_result = my_setlocale(LC_MESSAGES, trial_locale);
993             DEBUG_LOCALE_INIT(LC_MESSAGES, trial_locale, sl_result);
994             if (! (sl_result))
995                 setlocale_failure = TRUE;
996 #endif /* USE_LOCALE_MESSAGES */
997 #ifdef USE_LOCALE_MONETARY
998             sl_result = my_setlocale(LC_MONETARY, trial_locale);
999             DEBUG_LOCALE_INIT(LC_MONETARY, trial_locale, sl_result);
1000             if (! (sl_result))
1001                 setlocale_failure = TRUE;
1002 #endif /* USE_LOCALE_MONETARY */
1003
1004             if (! setlocale_failure) {  /* Success */
1005                 break;
1006             }
1007         }
1008
1009         /* Here, something failed; will need to try a fallback. */
1010         ok = 0;
1011
1012         if (i == 0) {
1013             unsigned int j;
1014
1015             if (locwarn) { /* Output failure info only on the first one */
1016 #ifdef LC_ALL
1017
1018                 PerlIO_printf(Perl_error_log,
1019                 "perl: warning: Setting locale failed.\n");
1020
1021 #else /* !LC_ALL */
1022
1023                 PerlIO_printf(Perl_error_log,
1024                 "perl: warning: Setting locale failed for the categories:\n\t");
1025 #  ifdef USE_LOCALE_CTYPE
1026                 if (! curctype)
1027                     PerlIO_printf(Perl_error_log, "LC_CTYPE ");
1028 #  endif /* USE_LOCALE_CTYPE */
1029 #  ifdef USE_LOCALE_COLLATE
1030                 if (! curcoll)
1031                     PerlIO_printf(Perl_error_log, "LC_COLLATE ");
1032 #  endif /* USE_LOCALE_COLLATE */
1033 #  ifdef USE_LOCALE_NUMERIC
1034                 if (! curnum)
1035                     PerlIO_printf(Perl_error_log, "LC_NUMERIC ");
1036 #  endif /* USE_LOCALE_NUMERIC */
1037                 PerlIO_printf(Perl_error_log, "and possibly others\n");
1038
1039 #endif /* LC_ALL */
1040
1041                 PerlIO_printf(Perl_error_log,
1042                     "perl: warning: Please check that your locale settings:\n");
1043
1044 #ifdef __GLIBC__
1045                 PerlIO_printf(Perl_error_log,
1046                             "\tLANGUAGE = %c%s%c,\n",
1047                             language ? '"' : '(',
1048                             language ? language : "unset",
1049                             language ? '"' : ')');
1050 #endif
1051
1052                 PerlIO_printf(Perl_error_log,
1053                             "\tLC_ALL = %c%s%c,\n",
1054                             lc_all ? '"' : '(',
1055                             lc_all ? lc_all : "unset",
1056                             lc_all ? '"' : ')');
1057
1058 #if defined(USE_ENVIRON_ARRAY)
1059                 {
1060                 char **e;
1061                 for (e = environ; *e; e++) {
1062                     if (strnEQ(*e, "LC_", 3)
1063                             && strnNE(*e, "LC_ALL=", 7)
1064                             && (p = strchr(*e, '=')))
1065                         PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
1066                                         (int)(p - *e), *e, p + 1);
1067                 }
1068                 }
1069 #else
1070                 PerlIO_printf(Perl_error_log,
1071                             "\t(possibly more locale environment variables)\n");
1072 #endif
1073
1074                 PerlIO_printf(Perl_error_log,
1075                             "\tLANG = %c%s%c\n",
1076                             lang ? '"' : '(',
1077                             lang ? lang : "unset",
1078                             lang ? '"' : ')');
1079
1080                 PerlIO_printf(Perl_error_log,
1081                             "    are supported and installed on your system.\n");
1082             }
1083
1084             /* Calculate what fallback locales to try.  We have avoided this
1085              * until we have to, because failure is quite unlikely.  This will
1086              * usually change the upper bound of the loop we are in.
1087              *
1088              * Since the system's default way of setting the locale has not
1089              * found one that works, We use Perl's defined ordering: LC_ALL,
1090              * LANG, and the C locale.  We don't try the same locale twice, so
1091              * don't add to the list if already there.  (On POSIX systems, the
1092              * LC_ALL element will likely be a repeat of the 0th element "",
1093              * but there's no harm done by doing it explicitly.
1094              *
1095              * Note that this tries the LC_ALL environment variable even on
1096              * systems which have no LC_ALL locale setting.  This may or may
1097              * not have been originally intentional, but there's no real need
1098              * to change the behavior. */
1099             if (lc_all) {
1100                 for (j = 0; j < trial_locales_count; j++) {
1101                     if (strEQ(lc_all, trial_locales[j])) {
1102                         goto done_lc_all;
1103                     }
1104                 }
1105                 trial_locales[trial_locales_count++] = lc_all;
1106             }
1107           done_lc_all:
1108
1109             if (lang) {
1110                 for (j = 0; j < trial_locales_count; j++) {
1111                     if (strEQ(lang, trial_locales[j])) {
1112                         goto done_lang;
1113                     }
1114                 }
1115                 trial_locales[trial_locales_count++] = lang;
1116             }
1117           done_lang:
1118
1119 #if defined(WIN32) && defined(LC_ALL)
1120             /* For Windows, we also try the system default locale before "C".
1121              * (If there exists a Windows without LC_ALL we skip this because
1122              * it gets too complicated.  For those, the "C" is the next
1123              * fallback possibility).  The "" is the same as the 0th element of
1124              * the array, but the code at the loop above knows to treat it
1125              * differently when not the 0th */
1126             trial_locales[trial_locales_count++] = "";
1127 #endif
1128
1129             for (j = 0; j < trial_locales_count; j++) {
1130                 if (strEQ("C", trial_locales[j])) {
1131                     goto done_C;
1132                 }
1133             }
1134             trial_locales[trial_locales_count++] = "C";
1135
1136           done_C: ;
1137         }   /* end of first time through the loop */
1138
1139 #ifdef WIN32
1140       next_iteration: ;
1141 #endif
1142
1143     }   /* end of looping through the trial locales */
1144
1145     if (ok < 1) {   /* If we tried to fallback */
1146         const char* msg;
1147         if (! setlocale_failure) {  /* fallback succeeded */
1148            msg = "Falling back to";
1149         }
1150         else {  /* fallback failed */
1151
1152             /* We dropped off the end of the loop, so have to decrement i to
1153              * get back to the value the last time through */
1154             i--;
1155
1156             ok = -1;
1157             msg = "Failed to fall back to";
1158
1159             /* To continue, we should use whatever values we've got */
1160 #ifdef USE_LOCALE_CTYPE
1161             Safefree(curctype);
1162             curctype = savepv(setlocale(LC_CTYPE, NULL));
1163             DEBUG_LOCALE_INIT(LC_CTYPE, NULL, curctype);
1164 #endif /* USE_LOCALE_CTYPE */
1165 #ifdef USE_LOCALE_COLLATE
1166             Safefree(curcoll);
1167             curcoll = savepv(setlocale(LC_COLLATE, NULL));
1168             DEBUG_LOCALE_INIT(LC_COLLATE, NULL, curcoll);
1169 #endif /* USE_LOCALE_COLLATE */
1170 #ifdef USE_LOCALE_NUMERIC
1171             Safefree(curnum);
1172             curnum = savepv(setlocale(LC_NUMERIC, NULL));
1173             DEBUG_LOCALE_INIT(LC_NUMERIC, NULL, curnum);
1174 #endif /* USE_LOCALE_NUMERIC */
1175         }
1176
1177         if (locwarn) {
1178             const char * description;
1179             const char * name = "";
1180             if (strEQ(trial_locales[i], "C")) {
1181                 description = "the standard locale";
1182                 name = "C";
1183             }
1184 #ifdef SYSTEM_DEFAULT_LOCALE
1185             else if (strEQ(trial_locales[i], "")) {
1186                 description = "the system default locale";
1187                 if (system_default_locale) {
1188                     name = system_default_locale;
1189                 }
1190             }
1191 #endif /* SYSTEM_DEFAULT_LOCALE */
1192             else {
1193                 description = "a fallback locale";
1194                 name = trial_locales[i];
1195             }
1196             if (name && strNE(name, "")) {
1197                 PerlIO_printf(Perl_error_log,
1198                     "perl: warning: %s %s (\"%s\").\n", msg, description, name);
1199             }
1200             else {
1201                 PerlIO_printf(Perl_error_log,
1202                                    "perl: warning: %s %s.\n", msg, description);
1203             }
1204         }
1205     } /* End of tried to fallback */
1206
1207 #ifdef USE_LOCALE_CTYPE
1208     new_ctype(curctype);
1209 #endif /* USE_LOCALE_CTYPE */
1210
1211 #ifdef USE_LOCALE_COLLATE
1212     new_collate(curcoll);
1213 #endif /* USE_LOCALE_COLLATE */
1214
1215 #ifdef USE_LOCALE_NUMERIC
1216     new_numeric(curnum);
1217 #endif /* USE_LOCALE_NUMERIC */
1218
1219 #if defined(USE_PERLIO) && defined(USE_LOCALE_CTYPE)
1220     /* Set PL_utf8locale to TRUE if using PerlIO _and_ the current LC_CTYPE
1221      * locale is UTF-8.  If PL_utf8locale and PL_unicode (set by -C or by
1222      * $ENV{PERL_UNICODE}) are true, perl.c:S_parse_body() will turn on the
1223      * PerlIO :utf8 layer on STDIN, STDOUT, STDERR, _and_ the default open
1224      * discipline.  */
1225     PL_utf8locale = _is_cur_LC_category_utf8(LC_CTYPE);
1226
1227     /* Set PL_unicode to $ENV{PERL_UNICODE} if using PerlIO.
1228        This is an alternative to using the -C command line switch
1229        (the -C if present will override this). */
1230     {
1231          const char *p = PerlEnv_getenv("PERL_UNICODE");
1232          PL_unicode = p ? parse_unicode_opts(&p) : 0;
1233          if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
1234              PL_utf8cache = -1;
1235     }
1236 #endif
1237
1238 #ifdef USE_LOCALE_CTYPE
1239     Safefree(curctype);
1240 #endif /* USE_LOCALE_CTYPE */
1241 #ifdef USE_LOCALE_COLLATE
1242     Safefree(curcoll);
1243 #endif /* USE_LOCALE_COLLATE */
1244 #ifdef USE_LOCALE_NUMERIC
1245     Safefree(curnum);
1246 #endif /* USE_LOCALE_NUMERIC */
1247
1248 #ifdef __GLIBC__
1249     Safefree(language);
1250 #endif
1251
1252     Safefree(lc_all);
1253     Safefree(lang);
1254
1255 #else  /* !USE_LOCALE */
1256     PERL_UNUSED_ARG(printwarn);
1257 #endif /* USE_LOCALE */
1258
1259     return ok;
1260 }
1261
1262
1263 #ifdef USE_LOCALE_COLLATE
1264
1265 /*
1266  * mem_collxfrm() is a bit like strxfrm() but with two important
1267  * differences. First, it handles embedded NULs. Second, it allocates
1268  * a bit more memory than needed for the transformed data itself.
1269  * The real transformed data begins at offset sizeof(collationix).
1270  * *xlen is set to the length of that, and doesn't include the collation index
1271  * size.
1272  * Please see sv_collxfrm() to see how this is used.
1273  */
1274
1275 char *
1276 Perl_mem_collxfrm(pTHX_ const char *s, STRLEN len, STRLEN *xlen)
1277 {
1278     char *xbuf;
1279     STRLEN xAlloc, xin, xout; /* xalloc is a reserved word in VC */
1280
1281     PERL_ARGS_ASSERT_MEM_COLLXFRM;
1282
1283     /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
1284     /* the +1 is for the terminating NUL. */
1285
1286     xAlloc = sizeof(PL_collation_ix) + PL_collxfrm_base + (PL_collxfrm_mult * len) + 1;
1287     Newx(xbuf, xAlloc, char);
1288     if (UNLIKELY(! xbuf))
1289         goto bad;
1290
1291     /* Store the collation id */
1292     *(U32*)xbuf = PL_collation_ix;
1293     xout = sizeof(PL_collation_ix);
1294
1295     /* Then the transformation of the input.  We loop until successful, or we
1296      * give up */
1297     for (xin = 0; xin < len; ) {
1298         Size_t xused;
1299
1300         for (;;) {
1301             xused = strxfrm(xbuf + xout, s + xin, xAlloc - xout);
1302
1303             /* If the transformed string occupies less space than we told
1304              * strxfrm() was available, it means it successfully transformed
1305              * the whole string. */
1306             if ((STRLEN)xused < xAlloc - xout)
1307                 break;
1308
1309             if (UNLIKELY(xused >= PERL_INT_MAX))
1310                 goto bad;
1311
1312             /* Otherwise it should be that the transformation stopped in the
1313              * middle because it ran out of space.  Malloc more, and try again.
1314              * */
1315             xAlloc = (2 * xAlloc) + 1;
1316             Renew(xbuf, xAlloc, char);
1317             if (UNLIKELY(! xbuf))
1318                 goto bad;
1319         }
1320
1321         xin += strlen(s + xin) + 1;
1322         xout += xused;
1323
1324         /* Embedded NULs are understood but silently skipped
1325          * because they make no sense in locale collation. */
1326     }
1327
1328     xbuf[xout] = '\0';
1329     *xlen = xout - sizeof(PL_collation_ix);
1330     return xbuf;
1331
1332   bad:
1333     Safefree(xbuf);
1334     *xlen = 0;
1335     return NULL;
1336 }
1337
1338 #endif /* USE_LOCALE_COLLATE */
1339
1340 #ifdef USE_LOCALE
1341
1342 bool
1343 Perl__is_cur_LC_category_utf8(pTHX_ int category)
1344 {
1345     /* Returns TRUE if the current locale for 'category' is UTF-8; FALSE
1346      * otherwise. 'category' may not be LC_ALL.  If the platform doesn't have
1347      * nl_langinfo(), nor MB_CUR_MAX, this employs a heuristic, which hence
1348      * could give the wrong result.  The result will very likely be correct for
1349      * languages that have commonly used non-ASCII characters, but for notably
1350      * English, it comes down to if the locale's name ends in something like
1351      * "UTF-8".  It errs on the side of not being a UTF-8 locale. */
1352
1353     char *save_input_locale = NULL;
1354     STRLEN final_pos;
1355
1356 #ifdef LC_ALL
1357     assert(category != LC_ALL);
1358 #endif
1359
1360     /* First dispose of the trivial cases */
1361     save_input_locale = setlocale(category, NULL);
1362     if (! save_input_locale) {
1363         DEBUG_L(PerlIO_printf(Perl_debug_log,
1364                               "Could not find current locale for category %d\n",
1365                               category));
1366         return FALSE;   /* XXX maybe should croak */
1367     }
1368     save_input_locale = stdize_locale(savepv(save_input_locale));
1369     if (isNAME_C_OR_POSIX(save_input_locale)) {
1370         DEBUG_L(PerlIO_printf(Perl_debug_log,
1371                               "Current locale for category %d is %s\n",
1372                               category, save_input_locale));
1373         Safefree(save_input_locale);
1374         return FALSE;
1375     }
1376
1377 #if defined(USE_LOCALE_CTYPE)    \
1378     && (defined(MB_CUR_MAX) || (defined(HAS_NL_LANGINFO) && defined(CODESET)))
1379
1380     { /* Next try nl_langinfo or MB_CUR_MAX if available */
1381
1382         char *save_ctype_locale = NULL;
1383         bool is_utf8;
1384
1385         if (category != LC_CTYPE) { /* These work only on LC_CTYPE */
1386
1387             /* Get the current LC_CTYPE locale */
1388             save_ctype_locale = setlocale(LC_CTYPE, NULL);
1389             if (! save_ctype_locale) {
1390                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1391                                "Could not find current locale for LC_CTYPE\n"));
1392                 goto cant_use_nllanginfo;
1393             }
1394             save_ctype_locale = stdize_locale(savepv(save_ctype_locale));
1395
1396             /* If LC_CTYPE and the desired category use the same locale, this
1397              * means that finding the value for LC_CTYPE is the same as finding
1398              * the value for the desired category.  Otherwise, switch LC_CTYPE
1399              * to the desired category's locale */
1400             if (strEQ(save_ctype_locale, save_input_locale)) {
1401                 Safefree(save_ctype_locale);
1402                 save_ctype_locale = NULL;
1403             }
1404             else if (! setlocale(LC_CTYPE, save_input_locale)) {
1405                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1406                                     "Could not change LC_CTYPE locale to %s\n",
1407                                     save_input_locale));
1408                 Safefree(save_ctype_locale);
1409                 goto cant_use_nllanginfo;
1410             }
1411         }
1412
1413         DEBUG_L(PerlIO_printf(Perl_debug_log, "Current LC_CTYPE locale=%s\n",
1414                                               save_input_locale));
1415
1416         /* Here the current LC_CTYPE is set to the locale of the category whose
1417          * information is desired.  This means that nl_langinfo() and MB_CUR_MAX
1418          * should give the correct results */
1419
1420 #   if defined(HAS_NL_LANGINFO) && defined(CODESET)
1421         {
1422             char *codeset = nl_langinfo(CODESET);
1423             if (codeset && strNE(codeset, "")) {
1424                 codeset = savepv(codeset);
1425
1426                 /* If we switched LC_CTYPE, switch back */
1427                 if (save_ctype_locale) {
1428                     setlocale(LC_CTYPE, save_ctype_locale);
1429                     Safefree(save_ctype_locale);
1430                 }
1431
1432                 is_utf8 = foldEQ(codeset, STR_WITH_LEN("UTF-8"))
1433                         || foldEQ(codeset, STR_WITH_LEN("UTF8"));
1434
1435                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1436                        "\tnllanginfo returned CODESET '%s'; ?UTF8 locale=%d\n",
1437                                                      codeset,         is_utf8));
1438                 Safefree(codeset);
1439                 Safefree(save_input_locale);
1440                 return is_utf8;
1441             }
1442         }
1443
1444 #   endif
1445 #   ifdef MB_CUR_MAX
1446
1447         /* Here, either we don't have nl_langinfo, or it didn't return a
1448          * codeset.  Try MB_CUR_MAX */
1449
1450         /* Standard UTF-8 needs at least 4 bytes to represent the maximum
1451          * Unicode code point.  Since UTF-8 is the only non-single byte
1452          * encoding we handle, we just say any such encoding is UTF-8, and if
1453          * turns out to be wrong, other things will fail */
1454         is_utf8 = MB_CUR_MAX >= 4;
1455
1456         DEBUG_L(PerlIO_printf(Perl_debug_log,
1457                               "\tMB_CUR_MAX=%d; ?UTF8 locale=%d\n",
1458                                    (int) MB_CUR_MAX,      is_utf8));
1459
1460         Safefree(save_input_locale);
1461
1462 #       ifdef HAS_MBTOWC
1463
1464         /* ... But, most system that have MB_CUR_MAX will also have mbtowc(),
1465          * since they are both in the C99 standard.  We can feed a known byte
1466          * string to the latter function, and check that it gives the expected
1467          * result */
1468         if (is_utf8) {
1469             wchar_t wc;
1470             PERL_UNUSED_RESULT(mbtowc(&wc, NULL, 0));/* Reset any shift state */
1471             errno = 0;
1472             if ((size_t)mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8))
1473                                                         != strlen(HYPHEN_UTF8)
1474                 || wc != (wchar_t) 0x2010)
1475             {
1476                 is_utf8 = FALSE;
1477                 DEBUG_L(PerlIO_printf(Perl_debug_log, "\thyphen=U+%x\n", (unsigned int)wc));
1478                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1479                         "\treturn from mbtowc=%d; errno=%d; ?UTF8 locale=0\n",
1480                         mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8)), errno));
1481             }
1482         }
1483 #       endif
1484
1485         /* If we switched LC_CTYPE, switch back */
1486         if (save_ctype_locale) {
1487             setlocale(LC_CTYPE, save_ctype_locale);
1488             Safefree(save_ctype_locale);
1489         }
1490
1491         return is_utf8;
1492 #   endif
1493     }
1494
1495   cant_use_nllanginfo:
1496
1497 #else   /* nl_langinfo should work if available, so don't bother compiling this
1498            fallback code.  The final fallback of looking at the name is
1499            compiled, and will be executed if nl_langinfo fails */
1500
1501     /* nl_langinfo not available or failed somehow.  Next try looking at the
1502      * currency symbol to see if it disambiguates things.  Often that will be
1503      * in the native script, and if the symbol isn't in UTF-8, we know that the
1504      * locale isn't.  If it is non-ASCII UTF-8, we infer that the locale is
1505      * too, as the odds of a non-UTF8 string being valid UTF-8 are quite small
1506      * */
1507
1508 #ifdef HAS_LOCALECONV
1509 #   ifdef USE_LOCALE_MONETARY
1510     {
1511         char *save_monetary_locale = NULL;
1512         bool only_ascii = FALSE;
1513         bool is_utf8 = FALSE;
1514         struct lconv* lc;
1515
1516         /* Like above for LC_CTYPE, we first set LC_MONETARY to the locale of
1517          * the desired category, if it isn't that locale already */
1518
1519         if (category != LC_MONETARY) {
1520
1521             save_monetary_locale = setlocale(LC_MONETARY, NULL);
1522             if (! save_monetary_locale) {
1523                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1524                             "Could not find current locale for LC_MONETARY\n"));
1525                 goto cant_use_monetary;
1526             }
1527             save_monetary_locale = stdize_locale(savepv(save_monetary_locale));
1528
1529             if (strEQ(save_monetary_locale, save_input_locale)) {
1530                 Safefree(save_monetary_locale);
1531                 save_monetary_locale = NULL;
1532             }
1533             else if (! setlocale(LC_MONETARY, save_input_locale)) {
1534                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1535                             "Could not change LC_MONETARY locale to %s\n",
1536                                                         save_input_locale));
1537                 Safefree(save_monetary_locale);
1538                 goto cant_use_monetary;
1539             }
1540         }
1541
1542         /* Here the current LC_MONETARY is set to the locale of the category
1543          * whose information is desired. */
1544
1545         lc = localeconv();
1546         if (! lc
1547             || ! lc->currency_symbol
1548             || is_invariant_string((U8 *) lc->currency_symbol, 0))
1549         {
1550             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));
1551             only_ascii = TRUE;
1552         }
1553         else {
1554             is_utf8 = is_utf8_string((U8 *) lc->currency_symbol, 0);
1555         }
1556
1557         /* If we changed it, restore LC_MONETARY to its original locale */
1558         if (save_monetary_locale) {
1559             setlocale(LC_MONETARY, save_monetary_locale);
1560             Safefree(save_monetary_locale);
1561         }
1562
1563         if (! only_ascii) {
1564
1565             /* It isn't a UTF-8 locale if the symbol is not legal UTF-8;
1566              * otherwise assume the locale is UTF-8 if and only if the symbol
1567              * is non-ascii UTF-8. */
1568             DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?Currency symbol for %s is UTF-8=%d\n",
1569                                     save_input_locale, is_utf8));
1570             Safefree(save_input_locale);
1571             return is_utf8;
1572         }
1573     }
1574   cant_use_monetary:
1575
1576 #   endif /* USE_LOCALE_MONETARY */
1577 #endif /* HAS_LOCALECONV */
1578
1579 #if defined(HAS_STRFTIME) && defined(USE_LOCALE_TIME)
1580
1581 /* Still haven't found a non-ASCII string to disambiguate UTF-8 or not.  Try
1582  * the names of the months and weekdays, timezone, and am/pm indicator */
1583     {
1584         char *save_time_locale = NULL;
1585         int hour = 10;
1586         bool is_dst = FALSE;
1587         int dom = 1;
1588         int month = 0;
1589         int i;
1590         char * formatted_time;
1591
1592
1593         /* Like above for LC_MONETARY, we set LC_TIME to the locale of the
1594          * desired category, if it isn't that locale already */
1595
1596         if (category != LC_TIME) {
1597
1598             save_time_locale = setlocale(LC_TIME, NULL);
1599             if (! save_time_locale) {
1600                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1601                             "Could not find current locale for LC_TIME\n"));
1602                 goto cant_use_time;
1603             }
1604             save_time_locale = stdize_locale(savepv(save_time_locale));
1605
1606             if (strEQ(save_time_locale, save_input_locale)) {
1607                 Safefree(save_time_locale);
1608                 save_time_locale = NULL;
1609             }
1610             else if (! setlocale(LC_TIME, save_input_locale)) {
1611                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1612                             "Could not change LC_TIME locale to %s\n",
1613                                                         save_input_locale));
1614                 Safefree(save_time_locale);
1615                 goto cant_use_time;
1616             }
1617         }
1618
1619         /* Here the current LC_TIME is set to the locale of the category
1620          * whose information is desired.  Look at all the days of the week and
1621          * month names, and the timezone and am/pm indicator for UTF-8 variant
1622          * characters.  The first such a one found will tell us if the locale
1623          * is UTF-8 or not */
1624
1625         for (i = 0; i < 7 + 12; i++) {  /* 7 days; 12 months */
1626             formatted_time = my_strftime("%A %B %Z %p",
1627                                     0, 0, hour, dom, month, 112, 0, 0, is_dst);
1628             if (! formatted_time || is_invariant_string((U8 *) formatted_time, 0)) {
1629
1630                 /* Here, we didn't find a non-ASCII.  Try the next time through
1631                  * with the complemented dst and am/pm, and try with the next
1632                  * weekday.  After we have gotten all weekdays, try the next
1633                  * month */
1634                 is_dst = ! is_dst;
1635                 hour = (hour + 12) % 24;
1636                 dom++;
1637                 if (i > 6) {
1638                     month++;
1639                 }
1640                 continue;
1641             }
1642
1643             /* Here, we have a non-ASCII.  Return TRUE is it is valid UTF8;
1644              * false otherwise.  But first, restore LC_TIME to its original
1645              * locale if we changed it */
1646             if (save_time_locale) {
1647                 setlocale(LC_TIME, save_time_locale);
1648                 Safefree(save_time_locale);
1649             }
1650
1651             DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?time-related strings for %s are UTF-8=%d\n",
1652                                 save_input_locale,
1653                                 is_utf8_string((U8 *) formatted_time, 0)));
1654             Safefree(save_input_locale);
1655             return is_utf8_string((U8 *) formatted_time, 0);
1656         }
1657
1658         /* Falling off the end of the loop indicates all the names were just
1659          * ASCII.  Go on to the next test.  If we changed it, restore LC_TIME
1660          * to its original locale */
1661         if (save_time_locale) {
1662             setlocale(LC_TIME, save_time_locale);
1663             Safefree(save_time_locale);
1664         }
1665         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));
1666     }
1667   cant_use_time:
1668
1669 #endif
1670
1671 #if 0 && defined(USE_LOCALE_MESSAGES) && defined(HAS_SYS_ERRLIST)
1672
1673 /* This code is ifdefd out because it was found to not be necessary in testing
1674  * on our dromedary test machine, which has over 700 locales.  There, this
1675  * added no value to looking at the currency symbol and the time strings.  I
1676  * left it in so as to avoid rewriting it if real-world experience indicates
1677  * that dromedary is an outlier.  Essentially, instead of returning abpve if we
1678  * haven't found illegal utf8, we continue on and examine all the strerror()
1679  * messages on the platform for utf8ness.  If all are ASCII, we still don't
1680  * know the answer; but otherwise we have a pretty good indication of the
1681  * utf8ness.  The reason this doesn't help much is that the messages may not
1682  * have been translated into the locale.  The currency symbol and time strings
1683  * are much more likely to have been translated.  */
1684     {
1685         int e;
1686         bool is_utf8 = FALSE;
1687         bool non_ascii = FALSE;
1688         char *save_messages_locale = NULL;
1689         const char * errmsg = NULL;
1690
1691         /* Like above, we set LC_MESSAGES to the locale of the desired
1692          * category, if it isn't that locale already */
1693
1694         if (category != LC_MESSAGES) {
1695
1696             save_messages_locale = setlocale(LC_MESSAGES, NULL);
1697             if (! save_messages_locale) {
1698                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1699                             "Could not find current locale for LC_MESSAGES\n"));
1700                 goto cant_use_messages;
1701             }
1702             save_messages_locale = stdize_locale(savepv(save_messages_locale));
1703
1704             if (strEQ(save_messages_locale, save_input_locale)) {
1705                 Safefree(save_messages_locale);
1706                 save_messages_locale = NULL;
1707             }
1708             else if (! setlocale(LC_MESSAGES, save_input_locale)) {
1709                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1710                             "Could not change LC_MESSAGES locale to %s\n",
1711                                                         save_input_locale));
1712                 Safefree(save_messages_locale);
1713                 goto cant_use_messages;
1714             }
1715         }
1716
1717         /* Here the current LC_MESSAGES is set to the locale of the category
1718          * whose information is desired.  Look through all the messages.  We
1719          * can't use Strerror() here because it may expand to code that
1720          * segfaults in miniperl */
1721
1722         for (e = 0; e <= sys_nerr; e++) {
1723             errno = 0;
1724             errmsg = sys_errlist[e];
1725             if (errno || !errmsg) {
1726                 break;
1727             }
1728             errmsg = savepv(errmsg);
1729             if (! is_invariant_string((U8 *) errmsg, 0)) {
1730                 non_ascii = TRUE;
1731                 is_utf8 = is_utf8_string((U8 *) errmsg, 0);
1732                 break;
1733             }
1734         }
1735         Safefree(errmsg);
1736
1737         /* And, if we changed it, restore LC_MESSAGES to its original locale */
1738         if (save_messages_locale) {
1739             setlocale(LC_MESSAGES, save_messages_locale);
1740             Safefree(save_messages_locale);
1741         }
1742
1743         if (non_ascii) {
1744
1745             /* Any non-UTF-8 message means not a UTF-8 locale; if all are valid,
1746              * any non-ascii means it is one; otherwise we assume it isn't */
1747             DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?error messages for %s are UTF-8=%d\n",
1748                                 save_input_locale,
1749                                 is_utf8));
1750             Safefree(save_input_locale);
1751             return is_utf8;
1752         }
1753
1754         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));
1755     }
1756   cant_use_messages:
1757
1758 #endif
1759
1760 #endif /* the code that is compiled when no nl_langinfo */
1761
1762 #ifndef EBCDIC  /* On os390, even if the name ends with "UTF-8', it isn't a
1763                    UTF-8 locale */
1764     /* As a last resort, look at the locale name to see if it matches
1765      * qr/UTF -?  * 8 /ix, or some other common locale names.  This "name", the
1766      * return of setlocale(), is actually defined to be opaque, so we can't
1767      * really rely on the absence of various substrings in the name to indicate
1768      * its UTF-8ness, but if it has UTF8 in the name, it is extremely likely to
1769      * be a UTF-8 locale.  Similarly for the other common names */
1770
1771     final_pos = strlen(save_input_locale) - 1;
1772     if (final_pos >= 3) {
1773         char *name = save_input_locale;
1774
1775         /* Find next 'U' or 'u' and look from there */
1776         while ((name += strcspn(name, "Uu") + 1)
1777                                             <= save_input_locale + final_pos - 2)
1778         {
1779             if (!isALPHA_FOLD_NE(*name, 't')
1780                 || isALPHA_FOLD_NE(*(name + 1), 'f'))
1781             {
1782                 continue;
1783             }
1784             name += 2;
1785             if (*(name) == '-') {
1786                 if ((name > save_input_locale + final_pos - 1)) {
1787                     break;
1788                 }
1789                 name++;
1790             }
1791             if (*(name) == '8') {
1792                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1793                                       "Locale %s ends with UTF-8 in name\n",
1794                                       save_input_locale));
1795                 Safefree(save_input_locale);
1796                 return TRUE;
1797             }
1798         }
1799         DEBUG_L(PerlIO_printf(Perl_debug_log,
1800                               "Locale %s doesn't end with UTF-8 in name\n",
1801                                 save_input_locale));
1802     }
1803 #endif
1804
1805 #ifdef WIN32
1806     /* http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756.aspx */
1807     if (final_pos >= 4
1808         && *(save_input_locale + final_pos - 0) == '1'
1809         && *(save_input_locale + final_pos - 1) == '0'
1810         && *(save_input_locale + final_pos - 2) == '0'
1811         && *(save_input_locale + final_pos - 3) == '5'
1812         && *(save_input_locale + final_pos - 4) == '6')
1813     {
1814         DEBUG_L(PerlIO_printf(Perl_debug_log,
1815                         "Locale %s ends with 10056 in name, is UTF-8 locale\n",
1816                         save_input_locale));
1817         Safefree(save_input_locale);
1818         return TRUE;
1819     }
1820 #endif
1821
1822     /* Other common encodings are the ISO 8859 series, which aren't UTF-8.  But
1823      * since we are about to return FALSE anyway, there is no point in doing
1824      * this extra work */
1825 #if 0
1826     if (instr(save_input_locale, "8859")) {
1827         DEBUG_L(PerlIO_printf(Perl_debug_log,
1828                              "Locale %s has 8859 in name, not UTF-8 locale\n",
1829                              save_input_locale));
1830         Safefree(save_input_locale);
1831         return FALSE;
1832     }
1833 #endif
1834
1835     DEBUG_L(PerlIO_printf(Perl_debug_log,
1836                           "Assuming locale %s is not a UTF-8 locale\n",
1837                                     save_input_locale));
1838     Safefree(save_input_locale);
1839     return FALSE;
1840 }
1841
1842 #endif
1843
1844
1845 bool
1846 Perl__is_in_locale_category(pTHX_ const bool compiling, const int category)
1847 {
1848     dVAR;
1849     /* Internal function which returns if we are in the scope of a pragma that
1850      * enables the locale category 'category'.  'compiling' should indicate if
1851      * this is during the compilation phase (TRUE) or not (FALSE). */
1852
1853     const COP * const cop = (compiling) ? &PL_compiling : PL_curcop;
1854
1855     SV *categories = cop_hints_fetch_pvs(cop, "locale", 0);
1856     if (! categories || categories == &PL_sv_placeholder) {
1857         return FALSE;
1858     }
1859
1860     /* The pseudo-category 'not_characters' is -1, so just add 1 to each to get
1861      * a valid unsigned */
1862     assert(category >= -1);
1863     return cBOOL(SvUV(categories) & (1U << (category + 1)));
1864 }
1865
1866 char *
1867 Perl_my_strerror(pTHX_ const int errnum) {
1868     dVAR;
1869
1870     /* Uses C locale for the error text unless within scope of 'use locale' for
1871      * LC_MESSAGES */
1872
1873 #ifdef USE_LOCALE_MESSAGES
1874     if (! IN_LC(LC_MESSAGES)) {
1875         char * save_locale;
1876
1877         /* We have a critical section to prevent another thread from changing
1878          * the locale out from under us (or zapping the buffer returned from
1879          * setlocale() ) */
1880         LOCALE_LOCK;
1881
1882         save_locale = setlocale(LC_MESSAGES, NULL);
1883         if (! isNAME_C_OR_POSIX(save_locale)) {
1884             char *errstr;
1885
1886             /* The next setlocale likely will zap this, so create a copy */
1887             save_locale = savepv(save_locale);
1888
1889             setlocale(LC_MESSAGES, "C");
1890
1891             /* This points to the static space in Strerror, with all its
1892              * limitations */
1893             errstr = Strerror(errnum);
1894
1895             setlocale(LC_MESSAGES, save_locale);
1896             Safefree(save_locale);
1897
1898             LOCALE_UNLOCK;
1899
1900             return errstr;
1901         }
1902
1903         LOCALE_UNLOCK;
1904     }
1905 #endif
1906
1907     return Strerror(errnum);
1908 }
1909
1910 /*
1911
1912 =head1 Locale-related functions and macros
1913
1914 =for apidoc sync_locale
1915
1916 Changing the program's locale should be avoided by XS code.  Nevertheless,
1917 certain non-Perl libraries called from XS, such as C<Gtk> do so.  When this
1918 happens, Perl needs to be told that the locale has changed.  Use this function
1919 to do so, before returning to Perl.
1920
1921 =cut
1922 */
1923
1924 void
1925 Perl_sync_locale(pTHX)
1926 {
1927
1928 #ifdef USE_LOCALE_CTYPE
1929     new_ctype(setlocale(LC_CTYPE, NULL));
1930 #endif /* USE_LOCALE_CTYPE */
1931
1932 #ifdef USE_LOCALE_COLLATE
1933     new_collate(setlocale(LC_COLLATE, NULL));
1934 #endif
1935
1936 #ifdef USE_LOCALE_NUMERIC
1937     set_numeric_local();    /* Switch from "C" to underlying LC_NUMERIC */
1938     new_numeric(setlocale(LC_NUMERIC, NULL));
1939 #endif /* USE_LOCALE_NUMERIC */
1940
1941 }
1942
1943 #if defined(DEBUGGING) && defined(USE_LOCALE)
1944
1945 char *
1946 Perl__setlocale_debug_string(const int category,        /* category number,
1947                                                            like LC_ALL */
1948                             const char* const locale,   /* locale name */
1949
1950                             /* return value from setlocale() when attempting to
1951                              * set 'category' to 'locale' */
1952                             const char* const retval)
1953 {
1954     /* Returns a pointer to a NUL-terminated string in static storage with
1955      * added text about the info passed in.  This is not thread safe and will
1956      * be overwritten by the next call, so this should be used just to
1957      * formulate a string to immediately print or savepv() on. */
1958
1959     /* initialise to a non-null value to keep it out of BSS and so keep
1960      * -DPERL_GLOBAL_STRUCT_PRIVATE happy */
1961     static char ret[128] = "x";
1962
1963     my_strlcpy(ret, "setlocale(", sizeof(ret));
1964
1965     switch (category) {
1966         default:
1967             my_snprintf(ret, sizeof(ret), "%s? %d", ret, category);
1968             break;
1969 #   ifdef LC_ALL
1970         case LC_ALL:
1971             my_strlcat(ret, "LC_ALL", sizeof(ret));
1972             break;
1973 #   endif
1974 #   ifdef LC_CTYPE
1975         case LC_CTYPE:
1976             my_strlcat(ret, "LC_CTYPE", sizeof(ret));
1977             break;
1978 #   endif
1979 #   ifdef LC_NUMERIC
1980         case LC_NUMERIC:
1981             my_strlcat(ret, "LC_NUMERIC", sizeof(ret));
1982             break;
1983 #   endif
1984 #   ifdef LC_COLLATE
1985         case LC_COLLATE:
1986             my_strlcat(ret, "LC_COLLATE", sizeof(ret));
1987             break;
1988 #   endif
1989 #   ifdef LC_TIME
1990         case LC_TIME:
1991             my_strlcat(ret, "LC_TIME", sizeof(ret));
1992             break;
1993 #   endif
1994 #   ifdef LC_MONETARY
1995         case LC_MONETARY:
1996             my_strlcat(ret, "LC_MONETARY", sizeof(ret));
1997             break;
1998 #   endif
1999 #   ifdef LC_MESSAGES
2000         case LC_MESSAGES:
2001             my_strlcat(ret, "LC_MESSAGES", sizeof(ret));
2002             break;
2003 #   endif
2004     }
2005
2006     my_strlcat(ret, ", ", sizeof(ret));
2007
2008     if (locale) {
2009         my_strlcat(ret, "\"", sizeof(ret));
2010         my_strlcat(ret, locale, sizeof(ret));
2011         my_strlcat(ret, "\"", sizeof(ret));
2012     }
2013     else {
2014         my_strlcat(ret, "NULL", sizeof(ret));
2015     }
2016
2017     my_strlcat(ret, ") returned ", sizeof(ret));
2018
2019     if (retval) {
2020         my_strlcat(ret, "\"", sizeof(ret));
2021         my_strlcat(ret, retval, sizeof(ret));
2022         my_strlcat(ret, "\"", sizeof(ret));
2023     }
2024     else {
2025         my_strlcat(ret, "NULL", sizeof(ret));
2026     }
2027
2028     assert(strlen(ret) < sizeof(ret));
2029
2030     return ret;
2031 }
2032
2033 #endif
2034
2035
2036 /*
2037  * ex: set ts=8 sts=4 sw=4 et:
2038  */