This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Another 'use encoding' issue
[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     dVAR;
97 # ifdef HAS_LOCALECONV
98     const struct lconv* const lc = localeconv();
99
100     if (lc && lc->decimal_point) {
101         if (lc->decimal_point[0] == '.' && lc->decimal_point[1] == 0) {
102             SvREFCNT_dec(PL_numeric_radix_sv);
103             PL_numeric_radix_sv = NULL;
104         }
105         else {
106             if (PL_numeric_radix_sv)
107                 sv_setpv(PL_numeric_radix_sv, lc->decimal_point);
108             else
109                 PL_numeric_radix_sv = newSVpv(lc->decimal_point, 0);
110             if (! is_ascii_string((U8 *) lc->decimal_point, 0)
111                 && is_utf8_string((U8 *) lc->decimal_point, 0)
112                 && _is_cur_LC_category_utf8(LC_NUMERIC))
113             {
114                 SvUTF8_on(PL_numeric_radix_sv);
115             }
116         }
117     }
118     else
119         PL_numeric_radix_sv = NULL;
120
121     DEBUG_L(PerlIO_printf(Perl_debug_log, "Locale radix is %s\n",
122                                           (PL_numeric_radix_sv)
123                                           ? lc->decimal_point
124                                           : "NULL"));
125
126 # endif /* HAS_LOCALECONV */
127 #endif /* USE_LOCALE_NUMERIC */
128 }
129
130 void
131 Perl_new_numeric(pTHX_ const char *newnum)
132 {
133 #ifdef USE_LOCALE_NUMERIC
134
135     /* Called after all libc setlocale() calls affecting LC_NUMERIC, to tell
136      * core Perl this and that 'newnum' is the name of the new locale.
137      * It installs this locale as the current underlying default.
138      *
139      * The default locale and the C locale can be toggled between by use of the
140      * set_numeric_local() and set_numeric_standard() functions, which should
141      * probably not be called directly, but only via macros like
142      * SET_NUMERIC_STANDARD() in perl.h.
143      *
144      * The toggling is necessary mainly so that a non-dot radix decimal point
145      * character can be output, while allowing internal calculations to use a
146      * dot.
147      *
148      * This sets several interpreter-level variables:
149      * PL_numeric_name  The default locale's name: a copy of 'newnum'
150      * PL_numeric_local A boolean indicating if the toggled state is such
151      *                  that the current locale is the program's underlying
152      *                  locale
153      * PL_numeric_standard An int indicating if the toggled state is such
154      *                  that the current locale is the C locale.  If non-zero,
155      *                  it is in C; if > 1, it means it may not be toggled away
156      *                  from C.
157      * Note that both of the last two variables can be true at the same time,
158      * if the underlying locale is C.  (Toggling is a no-op under these
159      * circumstances.)
160      *
161      * Any code changing the locale (outside this file) should use
162      * POSIX::setlocale, which calls this function.  Therefore this function
163      * should be called directly only from this file and from
164      * POSIX::setlocale() */
165
166     char *save_newnum;
167     dVAR;
168
169     if (! newnum) {
170         Safefree(PL_numeric_name);
171         PL_numeric_name = NULL;
172         PL_numeric_standard = TRUE;
173         PL_numeric_local = TRUE;
174         return;
175     }
176
177     save_newnum = stdize_locale(savepv(newnum));
178     if (! PL_numeric_name || strNE(PL_numeric_name, save_newnum)) {
179         Safefree(PL_numeric_name);
180         PL_numeric_name = save_newnum;
181     }
182
183     PL_numeric_standard = ((*save_newnum == 'C' && save_newnum[1] == '\0')
184                             || strEQ(save_newnum, "POSIX"));
185     PL_numeric_local = TRUE;
186
187     /* Keep LC_NUMERIC in the C locale.  This is for XS modules, so they don't
188      * have to worry about the radix being a non-dot.  (Core operations that
189      * need the underlying locale change to it temporarily). */
190     set_numeric_standard();
191
192     set_numeric_radix();
193
194 #endif /* USE_LOCALE_NUMERIC */
195 }
196
197 void
198 Perl_set_numeric_standard(pTHX)
199 {
200 #ifdef USE_LOCALE_NUMERIC
201     dVAR;
202
203     /* Toggle the LC_NUMERIC locale to C, if not already there.  Probably
204      * should use the macros like SET_NUMERIC_STANDARD() in perl.h instead of
205      * calling this directly. */
206
207     if (_NOT_IN_NUMERIC_STANDARD) {
208         setlocale(LC_NUMERIC, "C");
209         PL_numeric_standard = TRUE;
210         PL_numeric_local = FALSE;
211         set_numeric_radix();
212     }
213     DEBUG_L(PerlIO_printf(Perl_debug_log,
214                           "Underlying LC_NUMERIC locale now is C\n"));
215
216 #endif /* USE_LOCALE_NUMERIC */
217 }
218
219 void
220 Perl_set_numeric_local(pTHX)
221 {
222 #ifdef USE_LOCALE_NUMERIC
223     dVAR;
224
225     /* Toggle the LC_NUMERIC locale to the current underlying default, if not
226      * already there.  Probably should use the macros like SET_NUMERIC_LOCAL()
227      * in perl.h instead of calling this directly. */
228
229     if (_NOT_IN_NUMERIC_LOCAL) {
230         setlocale(LC_NUMERIC, PL_numeric_name);
231         PL_numeric_standard = FALSE;
232         PL_numeric_local = TRUE;
233         set_numeric_radix();
234     }
235     DEBUG_L(PerlIO_printf(Perl_debug_log,
236                           "Underlying LC_NUMERIC locale now is %s\n",
237                           PL_numeric_name));
238
239 #endif /* USE_LOCALE_NUMERIC */
240 }
241
242 /*
243  * Set up for a new ctype locale.
244  */
245 void
246 Perl_new_ctype(pTHX_ const char *newctype)
247 {
248 #ifdef USE_LOCALE_CTYPE
249
250     /* Called after all libc setlocale() calls affecting LC_CTYPE, to tell
251      * core Perl this and that 'newctype' is the name of the new locale.
252      *
253      * This function sets up the folding arrays for all 256 bytes, assuming
254      * that tofold() is tolc() since fold case is not a concept in POSIX,
255      *
256      * Any code changing the locale (outside this file) should use
257      * POSIX::setlocale, which calls this function.  Therefore this function
258      * should be called directly only from this file and from
259      * POSIX::setlocale() */
260
261     dVAR;
262     UV i;
263
264     PERL_ARGS_ASSERT_NEW_CTYPE;
265
266     PL_in_utf8_CTYPE_locale = _is_cur_LC_category_utf8(LC_CTYPE);
267
268     /* A UTF-8 locale gets standard rules.  But note that code still has to
269      * handle this specially because of the three problematic code points */
270     if (PL_in_utf8_CTYPE_locale) {
271         Copy(PL_fold_latin1, PL_fold_locale, 256, U8);
272     }
273     else {
274         for (i = 0; i < 256; i++) {
275             if (isUPPER_LC((U8) i))
276                 PL_fold_locale[i] = (U8) toLOWER_LC((U8) i);
277             else if (isLOWER_LC((U8) i))
278                 PL_fold_locale[i] = (U8) toUPPER_LC((U8) i);
279             else
280                 PL_fold_locale[i] = (U8) i;
281         }
282     }
283
284 #endif /* USE_LOCALE_CTYPE */
285     PERL_ARGS_ASSERT_NEW_CTYPE;
286     PERL_UNUSED_ARG(newctype);
287     PERL_UNUSED_CONTEXT;
288 }
289
290 void
291 Perl_new_collate(pTHX_ const char *newcoll)
292 {
293 #ifdef USE_LOCALE_COLLATE
294
295     /* Called after all libc setlocale() calls affecting LC_COLLATE, to tell
296      * core Perl this and that 'newcoll' is the name of the new locale.
297      *
298      * Any code changing the locale (outside this file) should use
299      * POSIX::setlocale, which calls this function.  Therefore this function
300      * should be called directly only from this file and from
301      * POSIX::setlocale() */
302
303     dVAR;
304
305     if (! newcoll) {
306         if (PL_collation_name) {
307             ++PL_collation_ix;
308             Safefree(PL_collation_name);
309             PL_collation_name = NULL;
310         }
311         PL_collation_standard = TRUE;
312         PL_collxfrm_base = 0;
313         PL_collxfrm_mult = 2;
314         return;
315     }
316
317     if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
318         ++PL_collation_ix;
319         Safefree(PL_collation_name);
320         PL_collation_name = stdize_locale(savepv(newcoll));
321         PL_collation_standard = ((*newcoll == 'C' && newcoll[1] == '\0')
322                                  || strEQ(newcoll, "POSIX"));
323
324         {
325           /*  2: at most so many chars ('a', 'b'). */
326           /* 50: surely no system expands a char more. */
327 #define XFRMBUFSIZE  (2 * 50)
328           char xbuf[XFRMBUFSIZE];
329           const Size_t fa = strxfrm(xbuf, "a",  XFRMBUFSIZE);
330           const Size_t fb = strxfrm(xbuf, "ab", XFRMBUFSIZE);
331           const SSize_t mult = fb - fa;
332           if (mult < 1 && !(fa == 0 && fb == 0))
333               Perl_croak(aTHX_ "panic: strxfrm() gets absurd - a => %"UVuf", ab => %"UVuf,
334                          (UV) fa, (UV) fb);
335           PL_collxfrm_base = (fa > (Size_t)mult) ? (fa - mult) : 0;
336           PL_collxfrm_mult = mult;
337         }
338     }
339
340 #endif /* USE_LOCALE_COLLATE */
341 }
342
343 #ifdef WIN32
344
345 char *
346 Perl_my_setlocale(pTHX_ int category, const char* locale)
347 {
348     /* This, for Windows, emulates POSIX setlocale() behavior.  There is no
349      * difference unless the input locale is "", which means on Windows to get
350      * the machine default, which is set via the computer's "Regional and
351      * Language Options" (or its current equivalent).  In POSIX, it instead
352      * means to find the locale from the user's environment.  This routine
353      * looks in the environment, and, if anything is found, uses that instead
354      * of going to the machine default.  If there is no environment override,
355      * the machine default is used, as normal, by calling the real setlocale()
356      * with "".  The POSIX behavior is to use the LC_ALL variable if set;
357      * otherwise to use the particular category's variable if set; otherwise to
358      * use the LANG variable. */
359
360     bool override_LC_ALL = 0;
361     char * result;
362
363     if (locale && strEQ(locale, "")) {
364 #   ifdef LC_ALL
365         locale = PerlEnv_getenv("LC_ALL");
366         if (! locale) {
367 #endif
368             switch (category) {
369 #   ifdef LC_ALL
370                 case LC_ALL:
371                     override_LC_ALL = TRUE;
372                     break;  /* We already know its variable isn't set */
373 #   endif
374 #   ifdef USE_LOCALE_TIME
375                 case LC_TIME:
376                     locale = PerlEnv_getenv("LC_TIME");
377                     break;
378 #   endif
379 #   ifdef USE_LOCALE_CTYPE
380                 case LC_CTYPE:
381                     locale = PerlEnv_getenv("LC_CTYPE");
382                     break;
383 #   endif
384 #   ifdef USE_LOCALE_COLLATE
385                 case LC_COLLATE:
386                     locale = PerlEnv_getenv("LC_COLLATE");
387                     break;
388 #   endif
389 #   ifdef USE_LOCALE_MONETARY
390                 case LC_MONETARY:
391                     locale = PerlEnv_getenv("LC_MONETARY");
392                     break;
393 #   endif
394 #   ifdef USE_LOCALE_NUMERIC
395                 case LC_NUMERIC:
396                     locale = PerlEnv_getenv("LC_NUMERIC");
397                     break;
398 #   endif
399 #   ifdef USE_LOCALE_MESSAGES
400                 case LC_MESSAGES:
401                     locale = PerlEnv_getenv("LC_MESSAGES");
402                     break;
403 #   endif
404                 default:
405                     /* This is a category, like PAPER_SIZE that we don't
406                      * know about; and so can't provide a wrapper. */
407                     break;
408             }
409             if (! locale) {
410                 locale = PerlEnv_getenv("LANG");
411                 if (! locale) {
412                     locale = "";
413                 }
414             }
415 #   ifdef LC_ALL
416         }
417 #   endif
418     }
419
420     result = setlocale(category, locale);
421
422     if (! override_LC_ALL)  {
423         return result;
424     }
425
426     /* Here the input locale was LC_ALL, and we have set it to what is in the
427      * LANG variable or the system default if there is no LANG.  But these have
428      * lower priority than the other LC_foo variables, so override it for each
429      * one that is set.  (If they are set to "", it means to use the same thing
430      * we just set LC_ALL to, so can skip) */
431 #   ifdef USE_LOCALE_TIME
432     result = PerlEnv_getenv("LC_TIME");
433     if (result && strNE(result, "")) {
434         setlocale(LC_TIME, result);
435     }
436 #   endif
437 #   ifdef USE_LOCALE_CTYPE
438     result = PerlEnv_getenv("LC_CTYPE");
439     if (result && strNE(result, "")) {
440         setlocale(LC_CTYPE, result);
441     }
442 #   endif
443 #   ifdef USE_LOCALE_COLLATE
444     result = PerlEnv_getenv("LC_COLLATE");
445     if (result && strNE(result, "")) {
446         setlocale(LC_COLLATE, result);
447     }
448 #   endif
449 #   ifdef USE_LOCALE_MONETARY
450     result = PerlEnv_getenv("LC_MONETARY");
451     if (result && strNE(result, "")) {
452         setlocale(LC_MONETARY, result);
453     }
454 #   endif
455 #   ifdef USE_LOCALE_NUMERIC
456     result = PerlEnv_getenv("LC_NUMERIC");
457     if (result && strNE(result, "")) {
458         setlocale(LC_NUMERIC, result);
459     }
460 #   endif
461 #   ifdef USE_LOCALE_MESSAGES
462     result = PerlEnv_getenv("LC_MESSAGES");
463     if (result && strNE(result, "")) {
464         setlocale(LC_MESSAGES, result);
465     }
466 #   endif
467
468     return setlocale(LC_ALL, NULL);
469
470 }
471
472 #endif
473
474
475 /*
476  * Initialize locale awareness.
477  */
478 int
479 Perl_init_i18nl10n(pTHX_ int printwarn)
480 {
481     /* printwarn is
482      *
483      *    0 if not to output warning when setup locale is bad
484      *    1 if to output warning based on value of PERL_BADLANG
485      *    >1 if to output regardless of PERL_BADLANG
486      *
487      * returns
488      *    1 = set ok or not applicable,
489      *    0 = fallback to a locale of lower priority
490      *   -1 = fallback to all locales failed, not even to the C locale
491      */
492
493     int ok = 1;
494
495 #if defined(USE_LOCALE)
496     dVAR;
497
498 #ifdef USE_LOCALE_CTYPE
499     char *curctype   = NULL;
500 #endif /* USE_LOCALE_CTYPE */
501 #ifdef USE_LOCALE_COLLATE
502     char *curcoll    = NULL;
503 #endif /* USE_LOCALE_COLLATE */
504 #ifdef USE_LOCALE_NUMERIC
505     char *curnum     = NULL;
506 #endif /* USE_LOCALE_NUMERIC */
507 #ifdef __GLIBC__
508     char * const language   = PerlEnv_getenv("LANGUAGE");
509 #endif
510
511     /* NULL uses the existing already set up locale */
512     const char * const setlocale_init = (PerlEnv_getenv("PERL_SKIP_LOCALE_INIT"))
513                                         ? NULL
514                                         : "";
515     const char* trial_locales[5];   /* 5 = 1 each for "", LC_ALL, LANG, "", C */
516     unsigned int trial_locales_count;
517     char * const lc_all     = PerlEnv_getenv("LC_ALL");
518     char * const lang       = PerlEnv_getenv("LANG");
519     bool setlocale_failure = FALSE;
520     unsigned int i;
521     char *p;
522     const bool locwarn = (printwarn > 1 ||
523                     (printwarn &&
524                      (!(p = PerlEnv_getenv("PERL_BADLANG")) || atoi(p))));
525     bool done = FALSE;
526 #ifdef WIN32
527     /* In some systems you can find out the system default locale
528      * and use that as the fallback locale. */
529 #   define SYSTEM_DEFAULT_LOCALE
530 #endif
531 #ifdef SYSTEM_DEFAULT_LOCALE
532     const char *system_default_locale = NULL;
533 #endif
534
535 #ifndef LOCALE_ENVIRON_REQUIRED
536     PERL_UNUSED_VAR(done);
537 #else
538
539     /*
540      * Ultrix setlocale(..., "") fails if there are no environment
541      * variables from which to get a locale name.
542      */
543
544 #   ifdef LC_ALL
545     if (lang) {
546         if (my_setlocale(LC_ALL, setlocale_init))
547             done = TRUE;
548         else
549             setlocale_failure = TRUE;
550     }
551     if (!setlocale_failure) {
552 #       ifdef USE_LOCALE_CTYPE
553         Safefree(curctype);
554         if (! (curctype =
555                my_setlocale(LC_CTYPE,
556                          (!done && (lang || PerlEnv_getenv("LC_CTYPE")))
557                                     ? setlocale_init : NULL)))
558             setlocale_failure = TRUE;
559         else
560             curctype = savepv(curctype);
561 #       endif /* USE_LOCALE_CTYPE */
562 #       ifdef USE_LOCALE_COLLATE
563         Safefree(curcoll);
564         if (! (curcoll =
565                my_setlocale(LC_COLLATE,
566                          (!done && (lang || PerlEnv_getenv("LC_COLLATE")))
567                                    ? setlocale_init : NULL)))
568             setlocale_failure = TRUE;
569         else
570             curcoll = savepv(curcoll);
571 #       endif /* USE_LOCALE_COLLATE */
572 #       ifdef USE_LOCALE_NUMERIC
573         Safefree(curnum);
574         if (! (curnum =
575                my_setlocale(LC_NUMERIC,
576                          (!done && (lang || PerlEnv_getenv("LC_NUMERIC")))
577                                   ? setlocale_init : NULL)))
578             setlocale_failure = TRUE;
579         else
580             curnum = savepv(curnum);
581 #       endif /* USE_LOCALE_NUMERIC */
582 #       ifdef USE_LOCALE_MESSAGES
583         if (! my_setlocale(LC_MESSAGES,
584                          (!done && (lang || PerlEnv_getenv("LC_MESSAGES")))
585                                   ? setlocale_init : NULL))
586         {
587             setlocale_failure = TRUE;
588         }
589 #       endif /* USE_LOCALE_MESSAGES */
590 #       ifdef USE_LOCALE_MONETARY
591         if (! my_setlocale(LC_MONETARY,
592                          (!done && (lang || PerlEnv_getenv("LC_MONETARY")))
593                                   ? setlocale_init : NULL))
594         {
595             setlocale_failure = TRUE;
596         }
597 #       endif /* USE_LOCALE_MONETARY */
598     }
599
600 #   endif /* LC_ALL */
601
602 #endif /* !LOCALE_ENVIRON_REQUIRED */
603
604     /* We try each locale in the list until we get one that works, or exhaust
605      * the list */
606     trial_locales[0] = setlocale_init;
607     trial_locales_count = 1;
608     for (i= 0; i < trial_locales_count; i++) {
609         const char * trial_locale = trial_locales[i];
610
611         if (i > 0) {
612
613             /* XXX This is to preserve old behavior for LOCALE_ENVIRON_REQUIRED
614              * when i==0, but I (khw) don't think that behavior makes much
615              * sense */
616             setlocale_failure = FALSE;
617
618 #ifdef SYSTEM_DEFAULT_LOCALE
619 #  ifdef WIN32
620             /* On Windows machines, an entry of "" after the 0th means to use
621              * the system default locale, which we now proceed to get. */
622             if (strEQ(trial_locale, "")) {
623                 unsigned int j;
624
625                 /* Note that this may change the locale, but we are going to do
626                  * that anyway just below */
627                 system_default_locale = setlocale(LC_ALL, "");
628
629                 /* Skip if invalid or it's already on the list of locales to
630                  * try */
631                 if (! system_default_locale) {
632                     goto next_iteration;
633                 }
634                 for (j = 0; j < trial_locales_count; j++) {
635                     if (strEQ(system_default_locale, trial_locales[j])) {
636                         goto next_iteration;
637                     }
638                 }
639
640                 trial_locale = system_default_locale;
641             }
642 #  endif /* WIN32 */
643 #endif /* SYSTEM_DEFAULT_LOCALE */
644         }
645
646 #ifdef LC_ALL
647         if (! my_setlocale(LC_ALL, trial_locale)) {
648             setlocale_failure = TRUE;
649         }
650         else {
651             /* Since LC_ALL succeeded, it should have changed all the other
652              * categories it can to its value; so we massage things so that the
653              * setlocales below just return their category's current values.
654              * This adequately handles the case in NetBSD where LC_COLLATE may
655              * not be defined for a locale, and setting it individually will
656              * fail, whereas setting LC_ALL suceeds, leaving LC_COLLATE set to
657              * the POSIX locale. */
658             trial_locale = NULL;
659         }
660 #endif /* LC_ALL */
661
662         if (!setlocale_failure) {
663 #ifdef USE_LOCALE_CTYPE
664             Safefree(curctype);
665             if (! (curctype = my_setlocale(LC_CTYPE, trial_locale)))
666                 setlocale_failure = TRUE;
667             else
668                 curctype = savepv(curctype);
669 #endif /* USE_LOCALE_CTYPE */
670 #ifdef USE_LOCALE_COLLATE
671             Safefree(curcoll);
672             if (! (curcoll = my_setlocale(LC_COLLATE, trial_locale)))
673                 setlocale_failure = TRUE;
674             else
675                 curcoll = savepv(curcoll);
676 #endif /* USE_LOCALE_COLLATE */
677 #ifdef USE_LOCALE_NUMERIC
678             Safefree(curnum);
679             if (! (curnum = my_setlocale(LC_NUMERIC, trial_locale)))
680                 setlocale_failure = TRUE;
681             else
682                 curnum = savepv(curnum);
683 #endif /* USE_LOCALE_NUMERIC */
684 #ifdef USE_LOCALE_MESSAGES
685             if (! (my_setlocale(LC_MESSAGES, trial_locale)))
686                 setlocale_failure = TRUE;
687 #endif /* USE_LOCALE_MESSAGES */
688 #ifdef USE_LOCALE_MONETARY
689             if (! (my_setlocale(LC_MONETARY, trial_locale)))
690                 setlocale_failure = TRUE;
691 #endif /* USE_LOCALE_MONETARY */
692
693             if (! setlocale_failure) {  /* Success */
694                 break;
695             }
696         }
697
698         /* Here, something failed; will need to try a fallback. */
699         ok = 0;
700
701         if (i == 0) {
702             unsigned int j;
703
704             if (locwarn) { /* Output failure info only on the first one */
705 #ifdef LC_ALL
706
707                 PerlIO_printf(Perl_error_log,
708                 "perl: warning: Setting locale failed.\n");
709
710 #else /* !LC_ALL */
711
712                 PerlIO_printf(Perl_error_log,
713                 "perl: warning: Setting locale failed for the categories:\n\t");
714 #ifdef USE_LOCALE_CTYPE
715                 if (! curctype)
716                     PerlIO_printf(Perl_error_log, "LC_CTYPE ");
717 #endif /* USE_LOCALE_CTYPE */
718 #ifdef USE_LOCALE_COLLATE
719                 if (! curcoll)
720                     PerlIO_printf(Perl_error_log, "LC_COLLATE ");
721 #endif /* USE_LOCALE_COLLATE */
722 #ifdef USE_LOCALE_NUMERIC
723                 if (! curnum)
724                     PerlIO_printf(Perl_error_log, "LC_NUMERIC ");
725 #endif /* USE_LOCALE_NUMERIC */
726                 PerlIO_printf(Perl_error_log, "and possibly others\n");
727
728 #endif /* LC_ALL */
729
730                 PerlIO_printf(Perl_error_log,
731                     "perl: warning: Please check that your locale settings:\n");
732
733 #ifdef __GLIBC__
734                 PerlIO_printf(Perl_error_log,
735                             "\tLANGUAGE = %c%s%c,\n",
736                             language ? '"' : '(',
737                             language ? language : "unset",
738                             language ? '"' : ')');
739 #endif
740
741                 PerlIO_printf(Perl_error_log,
742                             "\tLC_ALL = %c%s%c,\n",
743                             lc_all ? '"' : '(',
744                             lc_all ? lc_all : "unset",
745                             lc_all ? '"' : ')');
746
747 #if defined(USE_ENVIRON_ARRAY)
748                 {
749                 char **e;
750                 for (e = environ; *e; e++) {
751                     if (strnEQ(*e, "LC_", 3)
752                             && strnNE(*e, "LC_ALL=", 7)
753                             && (p = strchr(*e, '=')))
754                         PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
755                                         (int)(p - *e), *e, p + 1);
756                 }
757                 }
758 #else
759                 PerlIO_printf(Perl_error_log,
760                             "\t(possibly more locale environment variables)\n");
761 #endif
762
763                 PerlIO_printf(Perl_error_log,
764                             "\tLANG = %c%s%c\n",
765                             lang ? '"' : '(',
766                             lang ? lang : "unset",
767                             lang ? '"' : ')');
768
769                 PerlIO_printf(Perl_error_log,
770                             "    are supported and installed on your system.\n");
771             }
772
773             /* Calculate what fallback locales to try.  We have avoided this
774              * until we have to, becuase failure is quite unlikely.  This will
775              * usually change the upper bound of the loop we are in.
776              *
777              * Since the system's default way of setting the locale has not
778              * found one that works, We use Perl's defined ordering: LC_ALL,
779              * LANG, and the C locale.  We don't try the same locale twice, so
780              * don't add to the list if already there.  (On POSIX systems, the
781              * LC_ALL element will likely be a repeat of the 0th element "",
782              * but there's no harm done by doing it explicitly */
783             if (lc_all) {
784                 for (j = 0; j < trial_locales_count; j++) {
785                     if (strEQ(lc_all, trial_locales[j])) {
786                         goto done_lc_all;
787                     }
788                 }
789                 trial_locales[trial_locales_count++] = lc_all;
790             }
791           done_lc_all:
792
793             if (lang) {
794                 for (j = 0; j < trial_locales_count; j++) {
795                     if (strEQ(lang, trial_locales[j])) {
796                         goto done_lang;
797                     }
798                 }
799                 trial_locales[trial_locales_count++] = lang;
800             }
801           done_lang:
802
803 #if defined(WIN32) && defined(LC_ALL)
804             /* For Windows, we also try the system default locale before "C".
805              * (If there exists a Windows without LC_ALL we skip this because
806              * it gets too complicated.  For those, the "C" is the next
807              * fallback possibility).  The "" is the same as the 0th element of
808              * the array, but the code at the loop above knows to treat it
809              * differently when not the 0th */
810             trial_locales[trial_locales_count++] = "";
811 #endif
812
813             for (j = 0; j < trial_locales_count; j++) {
814                 if (strEQ("C", trial_locales[j])) {
815                     goto done_C;
816                 }
817             }
818             trial_locales[trial_locales_count++] = "C";
819
820           done_C: ;
821         }   /* end of first time through the loop */
822
823 #ifdef WIN32
824       next_iteration: ;
825 #endif
826
827     }   /* end of looping through the trial locales */
828
829     if (ok < 1) {   /* If we tried to fallback */
830         const char* msg;
831         if (! setlocale_failure) {  /* fallback succeeded */
832            msg = "Falling back to";
833         }
834         else {  /* fallback failed */
835
836             /* We dropped off the end of the loop, so have to decrement i to
837              * get back to the value the last time through */
838             i--;
839
840             ok = -1;
841             msg = "Failed to fall back to";
842
843             /* To continue, we should use whatever values we've got */
844 #ifdef USE_LOCALE_CTYPE
845             Safefree(curctype);
846             curctype = savepv(setlocale(LC_CTYPE, NULL));
847 #endif /* USE_LOCALE_CTYPE */
848 #ifdef USE_LOCALE_COLLATE
849             Safefree(curcoll);
850             curcoll = savepv(setlocale(LC_COLLATE, NULL));
851 #endif /* USE_LOCALE_COLLATE */
852 #ifdef USE_LOCALE_NUMERIC
853             Safefree(curnum);
854             curnum = savepv(setlocale(LC_NUMERIC, NULL));
855 #endif /* USE_LOCALE_NUMERIC */
856         }
857
858         if (locwarn) {
859             const char * description;
860             const char * name = "";
861             if (strEQ(trial_locales[i], "C")) {
862                 description = "the standard locale";
863                 name = "C";
864             }
865 #ifdef SYSTEM_DEFAULT_LOCALE
866             else if (strEQ(trial_locales[i], "")) {
867                 description = "the system default locale";
868                 if (system_default_locale) {
869                     name = system_default_locale;
870                 }
871             }
872 #endif /* SYSTEM_DEFAULT_LOCALE */
873             else {
874                 description = "a fallback locale";
875                 name = trial_locales[i];
876             }
877             if (name && strNE(name, "")) {
878                 PerlIO_printf(Perl_error_log,
879                     "perl: warning: %s %s (\"%s\").\n", msg, description, name);
880             }
881             else {
882                 PerlIO_printf(Perl_error_log,
883                                    "perl: warning: %s %s.\n", msg, description);
884             }
885         }
886     } /* End of tried to fallback */
887
888 #ifdef USE_LOCALE_CTYPE
889     new_ctype(curctype);
890 #endif /* USE_LOCALE_CTYPE */
891
892 #ifdef USE_LOCALE_COLLATE
893     new_collate(curcoll);
894 #endif /* USE_LOCALE_COLLATE */
895
896 #ifdef USE_LOCALE_NUMERIC
897     new_numeric(curnum);
898 #endif /* USE_LOCALE_NUMERIC */
899
900 #if defined(USE_PERLIO) && defined(USE_LOCALE_CTYPE)
901     /* Set PL_utf8locale to TRUE if using PerlIO _and_ the current LC_CTYPE
902      * locale is UTF-8.  If PL_utf8locale and PL_unicode (set by -C or by
903      * $ENV{PERL_UNICODE}) are true, perl.c:S_parse_body() will turn on the
904      * PerlIO :utf8 layer on STDIN, STDOUT, STDERR, _and_ the default open
905      * discipline.  */
906     PL_utf8locale = _is_cur_LC_category_utf8(LC_CTYPE);
907
908     /* Set PL_unicode to $ENV{PERL_UNICODE} if using PerlIO.
909        This is an alternative to using the -C command line switch
910        (the -C if present will override this). */
911     {
912          const char *p = PerlEnv_getenv("PERL_UNICODE");
913          PL_unicode = p ? parse_unicode_opts(&p) : 0;
914          if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
915              PL_utf8cache = -1;
916     }
917 #endif
918
919 #ifdef USE_LOCALE_CTYPE
920     Safefree(curctype);
921 #endif /* USE_LOCALE_CTYPE */
922 #ifdef USE_LOCALE_COLLATE
923     Safefree(curcoll);
924 #endif /* USE_LOCALE_COLLATE */
925 #ifdef USE_LOCALE_NUMERIC
926     Safefree(curnum);
927 #endif /* USE_LOCALE_NUMERIC */
928
929 #endif /* USE_LOCALE */
930
931     return ok;
932 }
933
934
935 #ifdef USE_LOCALE_COLLATE
936
937 /*
938  * mem_collxfrm() is a bit like strxfrm() but with two important
939  * differences. First, it handles embedded NULs. Second, it allocates
940  * a bit more memory than needed for the transformed data itself.
941  * The real transformed data begins at offset sizeof(collationix).
942  * Please see sv_collxfrm() to see how this is used.
943  */
944
945 char *
946 Perl_mem_collxfrm(pTHX_ const char *s, STRLEN len, STRLEN *xlen)
947 {
948     dVAR;
949     char *xbuf;
950     STRLEN xAlloc, xin, xout; /* xalloc is a reserved word in VC */
951
952     PERL_ARGS_ASSERT_MEM_COLLXFRM;
953
954     /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
955     /* the +1 is for the terminating NUL. */
956
957     xAlloc = sizeof(PL_collation_ix) + PL_collxfrm_base + (PL_collxfrm_mult * len) + 1;
958     Newx(xbuf, xAlloc, char);
959     if (! xbuf)
960         goto bad;
961
962     *(U32*)xbuf = PL_collation_ix;
963     xout = sizeof(PL_collation_ix);
964     for (xin = 0; xin < len; ) {
965         Size_t xused;
966
967         for (;;) {
968             xused = strxfrm(xbuf + xout, s + xin, xAlloc - xout);
969             if (xused >= PERL_INT_MAX)
970                 goto bad;
971             if ((STRLEN)xused < xAlloc - xout)
972                 break;
973             xAlloc = (2 * xAlloc) + 1;
974             Renew(xbuf, xAlloc, char);
975             if (! xbuf)
976                 goto bad;
977         }
978
979         xin += strlen(s + xin) + 1;
980         xout += xused;
981
982         /* Embedded NULs are understood but silently skipped
983          * because they make no sense in locale collation. */
984     }
985
986     xbuf[xout] = '\0';
987     *xlen = xout - sizeof(PL_collation_ix);
988     return xbuf;
989
990   bad:
991     Safefree(xbuf);
992     *xlen = 0;
993     return NULL;
994 }
995
996 #endif /* USE_LOCALE_COLLATE */
997
998 #ifdef USE_LOCALE
999
1000 bool
1001 Perl__is_cur_LC_category_utf8(pTHX_ int category)
1002 {
1003     /* Returns TRUE if the current locale for 'category' is UTF-8; FALSE
1004      * otherwise. 'category' may not be LC_ALL.  If the platform doesn't have
1005      * nl_langinfo(), nor MB_CUR_MAX, this employs a heuristic, which hence
1006      * could give the wrong result.  It errs on the side of not being a UTF-8
1007      * locale. */
1008
1009     char *save_input_locale = NULL;
1010     STRLEN final_pos;
1011
1012 #ifdef LC_ALL
1013     assert(category != LC_ALL);
1014 #endif
1015
1016     /* First dispose of the trivial cases */
1017     save_input_locale = setlocale(category, NULL);
1018     if (! save_input_locale) {
1019         DEBUG_L(PerlIO_printf(Perl_debug_log,
1020                               "Could not find current locale for category %d\n",
1021                               category));
1022         return FALSE;   /* XXX maybe should croak */
1023     }
1024     save_input_locale = stdize_locale(savepv(save_input_locale));
1025     if ((*save_input_locale == 'C' && save_input_locale[1] == '\0')
1026         || strEQ(save_input_locale, "POSIX"))
1027     {
1028         DEBUG_L(PerlIO_printf(Perl_debug_log,
1029                               "Current locale for category %d is %s\n",
1030                               category, save_input_locale));
1031         Safefree(save_input_locale);
1032         return FALSE;
1033     }
1034
1035 #if defined(USE_LOCALE_CTYPE)    \
1036     && (defined(MB_CUR_MAX) || (defined(HAS_NL_LANGINFO) && defined(CODESET)))
1037
1038     { /* Next try nl_langinfo or MB_CUR_MAX if available */
1039
1040         char *save_ctype_locale = NULL;
1041         bool is_utf8;
1042
1043         if (category != LC_CTYPE) { /* These work only on LC_CTYPE */
1044
1045             /* Get the current LC_CTYPE locale */
1046             save_ctype_locale = stdize_locale(savepv(setlocale(LC_CTYPE, NULL)));
1047             if (! save_ctype_locale) {
1048                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1049                                "Could not find current locale for LC_CTYPE\n"));
1050                 goto cant_use_nllanginfo;
1051             }
1052
1053             /* If LC_CTYPE and the desired category use the same locale, this
1054              * means that finding the value for LC_CTYPE is the same as finding
1055              * the value for the desired category.  Otherwise, switch LC_CTYPE
1056              * to the desired category's locale */
1057             if (strEQ(save_ctype_locale, save_input_locale)) {
1058                 Safefree(save_ctype_locale);
1059                 save_ctype_locale = NULL;
1060             }
1061             else if (! setlocale(LC_CTYPE, save_input_locale)) {
1062                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1063                                     "Could not change LC_CTYPE locale to %s\n",
1064                                     save_input_locale));
1065                 Safefree(save_ctype_locale);
1066                 goto cant_use_nllanginfo;
1067             }
1068         }
1069
1070         DEBUG_L(PerlIO_printf(Perl_debug_log, "Current LC_CTYPE locale=%s\n",
1071                                               save_input_locale));
1072
1073         /* Here the current LC_CTYPE is set to the locale of the category whose
1074          * information is desired.  This means that nl_langinfo() and MB_CUR_MAX
1075          * should give the correct results */
1076
1077 #   if defined(HAS_NL_LANGINFO) && defined(CODESET)
1078         {
1079             char *codeset = savepv(nl_langinfo(CODESET));
1080             if (codeset && strNE(codeset, "")) {
1081
1082                 /* If we switched LC_CTYPE, switch back */
1083                 if (save_ctype_locale) {
1084                     setlocale(LC_CTYPE, save_ctype_locale);
1085                     Safefree(save_ctype_locale);
1086                 }
1087
1088                 is_utf8 = foldEQ(codeset, STR_WITH_LEN("UTF-8"))
1089                         || foldEQ(codeset, STR_WITH_LEN("UTF8"));
1090
1091                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1092                        "\tnllanginfo returned CODESET '%s'; ?UTF8 locale=%d\n",
1093                                                      codeset,         is_utf8));
1094                 Safefree(codeset);
1095                 Safefree(save_input_locale);
1096                 return is_utf8;
1097             }
1098             Safefree(codeset);
1099         }
1100
1101 #   endif
1102 #   ifdef MB_CUR_MAX
1103
1104         /* Here, either we don't have nl_langinfo, or it didn't return a
1105          * codeset.  Try MB_CUR_MAX */
1106
1107         /* Standard UTF-8 needs at least 4 bytes to represent the maximum
1108          * Unicode code point.  Since UTF-8 is the only non-single byte
1109          * encoding we handle, we just say any such encoding is UTF-8, and if
1110          * turns out to be wrong, other things will fail */
1111         is_utf8 = MB_CUR_MAX >= 4;
1112
1113         DEBUG_L(PerlIO_printf(Perl_debug_log,
1114                               "\tMB_CUR_MAX=%d; ?UTF8 locale=%d\n",
1115                                    (int) MB_CUR_MAX,      is_utf8));
1116
1117         Safefree(save_input_locale);
1118
1119 #       ifdef HAS_MBTOWC
1120
1121         /* ... But, most system that have MB_CUR_MAX will also have mbtowc(),
1122          * since they are both in the C99 standard.  We can feed a known byte
1123          * string to the latter function, and check that it gives the expected
1124          * result */
1125         if (is_utf8) {
1126             wchar_t wc;
1127             GCC_DIAG_IGNORE(-Wunused-result);
1128             (void) mbtowc(&wc, NULL, 0);    /* Reset any shift state */
1129             GCC_DIAG_RESTORE;
1130             errno = 0;
1131             if ((size_t)mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8))
1132                                                         != strlen(HYPHEN_UTF8)
1133                 || wc != (wchar_t) 0x2010)
1134             {
1135                 is_utf8 = FALSE;
1136                 DEBUG_L(PerlIO_printf(Perl_debug_log, "\thyphen=U+%x\n", wc));
1137                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1138                         "\treturn from mbtowc=%d; errno=%d; ?UTF8 locale=0\n",
1139                         mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8)), errno));
1140             }
1141         }
1142 #       endif
1143
1144         /* If we switched LC_CTYPE, switch back */
1145         if (save_ctype_locale) {
1146             setlocale(LC_CTYPE, save_ctype_locale);
1147             Safefree(save_ctype_locale);
1148         }
1149
1150         return is_utf8;
1151 #   endif
1152     }
1153
1154   cant_use_nllanginfo:
1155
1156 #endif /* HAS_NL_LANGINFO etc */
1157
1158     /* nl_langinfo not available or failed somehow.  Look at the locale name to
1159      * see if it matches qr/UTF -? 8 /ix  */
1160
1161     final_pos = strlen(save_input_locale) - 1;
1162     if (final_pos >= 3) {
1163         char *name = save_input_locale;
1164
1165         /* Find next 'U' or 'u' and look from there */
1166         while ((name += strcspn(name, "Uu") + 1)
1167                                             <= save_input_locale + final_pos - 2)
1168         {
1169             if (toFOLD(*(name)) != 't'
1170                 || toFOLD(*(name + 1)) != 'f')
1171             {
1172                 continue;
1173             }
1174             name += 2;
1175             if (*(name) == '-') {
1176                 if ((name > save_input_locale + final_pos - 1)) {
1177                     break;
1178                 }
1179                 name++;
1180             }
1181             if (*(name) == '8') {
1182                 Safefree(save_input_locale);
1183                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1184                                       "Locale %s ends with UTF-8 in name\n",
1185                                       save_input_locale));
1186                 return TRUE;
1187             }
1188         }
1189         DEBUG_L(PerlIO_printf(Perl_debug_log,
1190                               "Locale %s doesn't end with UTF-8 in name\n",
1191                                 save_input_locale));
1192     }
1193
1194 #ifdef WIN32
1195     /* http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756.aspx */
1196     if (final_pos >= 4
1197         && *(save_input_locale + final_pos - 0) == '1'
1198         && *(save_input_locale + final_pos - 1) == '0'
1199         && *(save_input_locale + final_pos - 2) == '0'
1200         && *(save_input_locale + final_pos - 3) == '5'
1201         && *(save_input_locale + final_pos - 4) == '6')
1202     {
1203         DEBUG_L(PerlIO_printf(Perl_debug_log,
1204                         "Locale %s ends with 10056 in name, is UTF-8 locale\n",
1205                         save_input_locale));
1206         Safefree(save_input_locale);
1207         return TRUE;
1208     }
1209 #endif
1210
1211     /* Other common encodings are the ISO 8859 series, which aren't UTF-8 */
1212     if (instr(save_input_locale, "8859")) {
1213         DEBUG_L(PerlIO_printf(Perl_debug_log,
1214                              "Locale %s has 8859 in name, not UTF-8 locale\n",
1215                              save_input_locale));
1216         Safefree(save_input_locale);
1217         return FALSE;
1218     }
1219
1220 #ifdef HAS_LOCALECONV
1221
1222 #   ifdef USE_LOCALE_MONETARY
1223
1224     /* Here, there is nothing in the locale name to indicate whether the locale
1225      * is UTF-8 or not.  This "name", the return of setlocale(), is actually
1226      * defined to be opaque, so we can't really rely on the absence of various
1227      * substrings in the name to indicate its UTF-8ness.  Look at the locale's
1228      * currency symbol.  Often that will be in the native script, and if the
1229      * symbol isn't in UTF-8, we know that the locale isn't.  If it is
1230      * non-ASCII UTF-8, we infer that the locale is too.
1231      * To do this, like above for LC_CTYPE, we first set LC_MONETARY to the
1232      * locale of the desired category, if it isn't that locale already */
1233
1234     {
1235         char *save_monetary_locale = NULL;
1236         bool illegal_utf8 = FALSE;
1237         bool only_ascii = FALSE;
1238         const struct lconv* const lc = localeconv();
1239
1240         if (category != LC_MONETARY) {
1241
1242             save_monetary_locale = stdize_locale(savepv(setlocale(LC_MONETARY,
1243                                                                   NULL)));
1244             if (! save_monetary_locale) {
1245                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1246                             "Could not find current locale for LC_MONETARY\n"));
1247                 goto cant_use_monetary;
1248             }
1249
1250             if (strNE(save_monetary_locale, save_input_locale)) {
1251                 if (! setlocale(LC_MONETARY, save_input_locale)) {
1252                     DEBUG_L(PerlIO_printf(Perl_debug_log,
1253                                 "Could not change LC_MONETARY locale to %s\n",
1254                                                             save_input_locale));
1255                     Safefree(save_monetary_locale);
1256                     goto cant_use_monetary;
1257                 }
1258             }
1259         }
1260
1261         /* Here the current LC_MONETARY is set to the locale of the category
1262          * whose information is desired. */
1263
1264         if (lc && lc->currency_symbol) {
1265             if (! is_utf8_string((U8 *) lc->currency_symbol, 0)) {
1266                 DEBUG_L(PerlIO_printf(Perl_debug_log,
1267                             "Currency symbol for %s is not legal UTF-8\n",
1268                                         save_input_locale));
1269                 illegal_utf8 = TRUE;
1270             }
1271             else if (is_ascii_string((U8 *) lc->currency_symbol, 0)) {
1272                 DEBUG_L(PerlIO_printf(Perl_debug_log, "Currency symbol for %s contains only ASCII; can't use for determining if UTF-8 locale\n", save_input_locale));
1273                 only_ascii = TRUE;
1274             }
1275         }
1276
1277         /* If we changed it, restore LC_MONETARY to its original locale */
1278         if (save_monetary_locale) {
1279             setlocale(LC_MONETARY, save_monetary_locale);
1280             Safefree(save_monetary_locale);
1281         }
1282
1283         Safefree(save_input_locale);
1284
1285         /* It isn't a UTF-8 locale if the symbol is not legal UTF-8; otherwise
1286          * assume the locale is UTF-8 if and only if the symbol is non-ascii
1287          * UTF-8.  (We can't really tell if the locale is UTF-8 or not if the
1288          * symbol is just a '$', so we err on the side of it not being UTF-8)
1289          * */
1290         DEBUG_L(PerlIO_printf(Perl_debug_log, "\tis_utf8=%d\n", (illegal_utf8)
1291                                                                ? FALSE
1292                                                                : ! only_ascii));
1293         return (illegal_utf8)
1294                 ? FALSE
1295                 : ! only_ascii;
1296
1297     }
1298   cant_use_monetary:
1299
1300 #   endif /* USE_LOCALE_MONETARY */
1301 #endif /* HAS_LOCALECONV */
1302
1303 #if 0 && defined(HAS_STRERROR) && defined(USE_LOCALE_MESSAGES)
1304
1305 /* This code is ifdefd out because it was found to not be necessary in testing
1306  * on our dromedary test machine, which has over 700 locales.  There, looking
1307  * at just the currency symbol gave essentially the same results as doing this
1308  * extra work.  Executing this also caused segfaults in miniperl.  I left it in
1309  * so as to avoid rewriting it if real-world experience indicates that
1310  * dromedary is an outlier.  Essentially, instead of returning abpve if we
1311  * haven't found illegal utf8, we continue on and examine all the strerror()
1312  * messages on the platform for utf8ness.  If all are ASCII, we still don't
1313  * know the answer; but otherwise we have a pretty good indication of the
1314  * utf8ness.  The reason this doesn't necessarily help much is that the
1315  * messages may not have been translated into the locale.  The currency symbol
1316  * is much more likely to have been translated.  The code below would need to
1317  * be altered somewhat to just be a continuation of testing the currency
1318  * symbol. */
1319         int e;
1320         unsigned int failures = 0, non_ascii = 0;
1321         char *save_messages_locale = NULL;
1322
1323         /* Like above for LC_CTYPE, we set LC_MESSAGES to the locale of the
1324          * desired category, if it isn't that locale already */
1325
1326         if (category != LC_MESSAGES) {
1327
1328             save_messages_locale = stdize_locale(savepv(setlocale(LC_MESSAGES,
1329                                                                   NULL)));
1330             if (! save_messages_locale) {
1331                 goto cant_use_messages;
1332             }
1333
1334             if (strEQ(save_messages_locale, save_input_locale)) {
1335                 Safefree(save_input_locale);
1336             }
1337             else if (! setlocale(LC_MESSAGES, save_input_locale)) {
1338                 Safefree(save_messages_locale);
1339                 goto cant_use_messages;
1340             }
1341         }
1342
1343         /* Here the current LC_MESSAGES is set to the locale of the category
1344          * whose information is desired.  Look through all the messages */
1345
1346         for (e = 0;
1347 #ifdef HAS_SYS_ERRLIST
1348              e <= sys_nerr
1349 #endif
1350              ; e++)
1351         {
1352             const U8* const errmsg = (U8 *) Strerror(e) ;
1353             if (!errmsg)
1354                 break;
1355             if (! is_utf8_string(errmsg, 0)) {
1356                 failures++;
1357                 break;
1358             }
1359             else if (! is_ascii_string(errmsg, 0)) {
1360                 non_ascii++;
1361             }
1362         }
1363
1364         /* And, if we changed it, restore LC_MESSAGES to its original locale */
1365         if (save_messages_locale) {
1366             setlocale(LC_MESSAGES, save_messages_locale);
1367             Safefree(save_messages_locale);
1368         }
1369
1370         /* Any non-UTF-8 message means not a UTF-8 locale; if all are valid,
1371          * any non-ascii means it is one; otherwise we assume it isn't */
1372         return (failures) ? FALSE : non_ascii;
1373
1374     }
1375   cant_use_messages:
1376
1377 #endif
1378
1379     DEBUG_L(PerlIO_printf(Perl_debug_log,
1380                           "Assuming locale %s is not a UTF-8 locale\n",
1381                                     save_input_locale));
1382     Safefree(save_input_locale);
1383     return FALSE;
1384 }
1385
1386 #endif
1387
1388
1389 bool
1390 Perl__is_in_locale_category(pTHX_ const bool compiling, const int category)
1391 {
1392     dVAR;
1393     /* Internal function which returns if we are in the scope of a pragma that
1394      * enables the locale category 'category'.  'compiling' should indicate if
1395      * this is during the compilation phase (TRUE) or not (FALSE). */
1396
1397     const COP * const cop = (compiling) ? &PL_compiling : PL_curcop;
1398
1399     SV *categories = cop_hints_fetch_pvs(cop, "locale", 0);
1400     if (! categories || categories == &PL_sv_placeholder) {
1401         return FALSE;
1402     }
1403
1404     /* The pseudo-category 'not_characters' is -1, so just add 1 to each to get
1405      * a valid unsigned */
1406     assert(category >= -1);
1407     return cBOOL(SvUV(categories) & (1U << (category + 1)));
1408 }
1409
1410 char *
1411 Perl_my_strerror(pTHX_ const int errnum) {
1412
1413     /* Uses C locale for the error text unless within scope of 'use locale' for
1414      * LC_MESSAGES */
1415
1416 #ifdef USE_LOCALE_MESSAGES
1417     if (! IN_LC(LC_MESSAGES)) {
1418         char * save_locale = setlocale(LC_MESSAGES, NULL);
1419         if (! ((*save_locale == 'C' && save_locale[1] == '\0')
1420                 || strEQ(save_locale, "POSIX")))
1421         {
1422             char *errstr;
1423
1424             /* The next setlocale likely will zap this, so create a copy */
1425             save_locale = savepv(save_locale);
1426
1427             setlocale(LC_MESSAGES, "C");
1428
1429             /* This points to the static space in Strerror, with all its
1430              * limitations */
1431             errstr = Strerror(errnum);
1432
1433             setlocale(LC_MESSAGES, save_locale);
1434             Safefree(save_locale);
1435             return errstr;
1436         }
1437     }
1438 #endif
1439
1440     return Strerror(errnum);
1441 }
1442
1443 /*
1444  * Local variables:
1445  * c-indentation-style: bsd
1446  * c-basic-offset: 4
1447  * indent-tabs-mode: nil
1448  * End:
1449  *
1450  * ex: set ts=8 sts=4 sw=4 et:
1451  */