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