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