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