3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
4 * 2002, 2003, 2005, 2006, 2007, 2008 by Larry Wall and others
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.
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!
20 * [p.238 of _The Lord of the Rings_, II/i: "Many Meetings"]
23 /* utility functions for handling locale-specific stuff like what
24 * character represents the decimal point.
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.
36 #define PERL_IN_LOCALE_C
40 # include <langinfo.h>
48 * Standardize the locale name from a string returned by 'setlocale', possibly
49 * modifying that string.
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.
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 '='
63 S_stdize_locale(pTHX_ char *locs)
65 const char * const s = strchr(locs, '=');
68 PERL_ARGS_ASSERT_STDIZE_LOCALE;
71 const char * const t = strchr(s, '.');
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);
85 Perl_croak(aTHX_ "Can't fix broken locale name \"%s\"", locs);
93 Perl_set_numeric_radix(pTHX)
95 #ifdef USE_LOCALE_NUMERIC
96 # ifdef HAS_LOCALECONV
97 const struct lconv* const lc = localeconv();
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;
105 if (PL_numeric_radix_sv)
106 sv_setpv(PL_numeric_radix_sv, lc->decimal_point);
108 PL_numeric_radix_sv = newSVpv(lc->decimal_point, 0);
109 if (! is_invariant_string((U8 *) lc->decimal_point, 0)
110 && is_utf8_string((U8 *) lc->decimal_point, 0)
111 && _is_cur_LC_category_utf8(LC_NUMERIC))
113 SvUTF8_on(PL_numeric_radix_sv);
118 PL_numeric_radix_sv = NULL;
120 DEBUG_L(PerlIO_printf(Perl_debug_log, "Locale radix is %s, ?UTF-8=%d\n",
121 (PL_numeric_radix_sv)
122 ? SvPVX(PL_numeric_radix_sv)
124 (PL_numeric_radix_sv)
125 ? SvUTF8(PL_numeric_radix_sv)
128 # endif /* HAS_LOCALECONV */
129 #endif /* USE_LOCALE_NUMERIC */
132 /* Is the C string input 'name' "C" or "POSIX"? If so, and 'name' is the
133 * return of setlocale(), then this is extremely likely to be the C or POSIX
134 * locale. However, the output of setlocale() is documented to be opaque, but
135 * the odds are extremely small that it would return these two strings for some
136 * other locale. Note that VMS in these two locales includes many non-ASCII
137 * characters as controls and punctuation (below are hex bytes):
138 * cntrl: 00-1F 7F 84-97 9B-9F
139 * 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
140 * Oddly, none there are listed as alphas, though some represent alphabetics
141 * http://www.nntp.perl.org/group/perl.perl5.porters/2013/02/msg198753.html */
142 #define isNAME_C_OR_POSIX(name) ((name) != NULL \
143 && ((*(name) == 'C' && (*(name + 1)) == '\0') \
144 || strEQ((name), "POSIX")))
147 Perl_new_numeric(pTHX_ const char *newnum)
149 #ifdef USE_LOCALE_NUMERIC
151 /* Called after all libc setlocale() calls affecting LC_NUMERIC, to tell
152 * core Perl this and that 'newnum' is the name of the new locale.
153 * It installs this locale as the current underlying default.
155 * The default locale and the C locale can be toggled between by use of the
156 * set_numeric_local() and set_numeric_standard() functions, which should
157 * probably not be called directly, but only via macros like
158 * SET_NUMERIC_STANDARD() in perl.h.
160 * The toggling is necessary mainly so that a non-dot radix decimal point
161 * character can be output, while allowing internal calculations to use a
164 * This sets several interpreter-level variables:
165 * PL_numeric_name The underlying locale's name: a copy of 'newnum'
166 * PL_numeric_local A boolean indicating if the toggled state is such
167 * that the current locale is the program's underlying
169 * PL_numeric_standard An int indicating if the toggled state is such
170 * that the current locale is the C locale. If non-zero,
171 * it is in C; if > 1, it means it may not be toggled away
173 * Note that both of the last two variables can be true at the same time,
174 * if the underlying locale is C. (Toggling is a no-op under these
177 * Any code changing the locale (outside this file) should use
178 * POSIX::setlocale, which calls this function. Therefore this function
179 * should be called directly only from this file and from
180 * POSIX::setlocale() */
185 Safefree(PL_numeric_name);
186 PL_numeric_name = NULL;
187 PL_numeric_standard = TRUE;
188 PL_numeric_local = TRUE;
192 save_newnum = stdize_locale(savepv(newnum));
193 if (! PL_numeric_name || strNE(PL_numeric_name, save_newnum)) {
194 Safefree(PL_numeric_name);
195 PL_numeric_name = save_newnum;
198 PL_numeric_standard = isNAME_C_OR_POSIX(save_newnum);
199 PL_numeric_local = TRUE;
201 /* Keep LC_NUMERIC in the C locale. This is for XS modules, so they don't
202 * have to worry about the radix being a non-dot. (Core operations that
203 * need the underlying locale change to it temporarily). */
204 set_numeric_standard();
209 PERL_UNUSED_ARG(newnum);
210 #endif /* USE_LOCALE_NUMERIC */
214 Perl_set_numeric_standard(pTHX)
216 #ifdef USE_LOCALE_NUMERIC
217 /* Toggle the LC_NUMERIC locale to C. Most code should use the macros like
218 * SET_NUMERIC_STANDARD() in perl.h instead of calling this directly. The
219 * macro avoids calling this routine if toggling isn't necessary according
220 * to our records (which could be wrong if some XS code has changed the
221 * locale behind our back) */
223 setlocale(LC_NUMERIC, "C");
224 PL_numeric_standard = TRUE;
225 PL_numeric_local = isNAME_C_OR_POSIX(PL_numeric_name);
227 DEBUG_L(PerlIO_printf(Perl_debug_log,
228 "Underlying LC_NUMERIC locale now is C\n"));
230 #endif /* USE_LOCALE_NUMERIC */
234 Perl_set_numeric_local(pTHX)
236 #ifdef USE_LOCALE_NUMERIC
237 /* Toggle the LC_NUMERIC locale to the current underlying default. Most
238 * code should use the macros like SET_NUMERIC_LOCAL() in perl.h instead of
239 * calling this directly. The macro avoids calling this routine if
240 * toggling isn't necessary according to our records (which could be wrong
241 * if some XS code has changed the locale behind our back) */
243 setlocale(LC_NUMERIC, PL_numeric_name);
244 PL_numeric_standard = isNAME_C_OR_POSIX(PL_numeric_name);
245 PL_numeric_local = TRUE;
247 DEBUG_L(PerlIO_printf(Perl_debug_log,
248 "Underlying LC_NUMERIC locale now is %s\n",
251 #endif /* USE_LOCALE_NUMERIC */
255 * Set up for a new ctype locale.
258 Perl_new_ctype(pTHX_ const char *newctype)
260 #ifdef USE_LOCALE_CTYPE
262 /* Called after all libc setlocale() calls affecting LC_CTYPE, to tell
263 * core Perl this and that 'newctype' is the name of the new locale.
265 * This function sets up the folding arrays for all 256 bytes, assuming
266 * that tofold() is tolc() since fold case is not a concept in POSIX,
268 * Any code changing the locale (outside this file) should use
269 * POSIX::setlocale, which calls this function. Therefore this function
270 * should be called directly only from this file and from
271 * POSIX::setlocale() */
276 PERL_ARGS_ASSERT_NEW_CTYPE;
278 /* We will replace any bad locale warning with 1) nothing if the new one is
279 * ok; or 2) a new warning for the bad new locale */
280 if (PL_warn_locale) {
281 SvREFCNT_dec_NN(PL_warn_locale);
282 PL_warn_locale = NULL;
285 PL_in_utf8_CTYPE_locale = _is_cur_LC_category_utf8(LC_CTYPE);
287 /* A UTF-8 locale gets standard rules. But note that code still has to
288 * handle this specially because of the three problematic code points */
289 if (PL_in_utf8_CTYPE_locale) {
290 Copy(PL_fold_latin1, PL_fold_locale, 256, U8);
293 /* Assume enough space for every character being bad. 4 spaces each
294 * for the 94 printable characters that are output like "'x' "; and 5
295 * spaces each for "'\\' ", "'\t' ", and "'\n' "; plus a terminating
297 char bad_chars_list[ (94 * 4) + (3 * 5) + 1 ];
299 bool check_for_problems = ckWARN_d(WARN_LOCALE); /* No warnings means
301 bool multi_byte_locale = FALSE; /* Assume is a single-byte locale
303 unsigned int bad_count = 0; /* Count of bad characters */
305 for (i = 0; i < 256; i++) {
306 if (isUPPER_LC((U8) i))
307 PL_fold_locale[i] = (U8) toLOWER_LC((U8) i);
308 else if (isLOWER_LC((U8) i))
309 PL_fold_locale[i] = (U8) toUPPER_LC((U8) i);
311 PL_fold_locale[i] = (U8) i;
313 /* If checking for locale problems, see if the native ASCII-range
314 * printables plus \n and \t are in their expected categories in
315 * the new locale. If not, this could mean big trouble, upending
316 * Perl's and most programs' assumptions, like having a
317 * metacharacter with special meaning become a \w. Fortunately,
318 * it's very rare to find locales that aren't supersets of ASCII
319 * nowadays. It isn't a problem for most controls to be changed
320 * into something else; we check only \n and \t, though perhaps \r
321 * could be an issue as well. */
322 if (check_for_problems
323 && (isGRAPH_A(i) || isBLANK_A(i) || i == '\n'))
325 if ((isALPHANUMERIC_A(i) && ! isALPHANUMERIC_LC(i))
326 || (isPUNCT_A(i) && ! isPUNCT_LC(i))
327 || (isBLANK_A(i) && ! isBLANK_LC(i))
328 || (i == '\n' && ! isCNTRL_LC(i)))
330 if (bad_count) { /* Separate multiple entries with a
332 bad_chars_list[bad_count++] = ' ';
334 bad_chars_list[bad_count++] = '\'';
336 bad_chars_list[bad_count++] = (char) i;
339 bad_chars_list[bad_count++] = '\\';
341 bad_chars_list[bad_count++] = 'n';
345 bad_chars_list[bad_count++] = 't';
348 bad_chars_list[bad_count++] = '\'';
349 bad_chars_list[bad_count] = '\0';
355 /* We only handle single-byte locales (outside of UTF-8 ones; so if
356 * this locale requires than one byte, there are going to be
358 if (check_for_problems && MB_CUR_MAX > 1
360 /* Some platforms return MB_CUR_MAX > 1 for even the "C"
361 * locale. Just assume that the implementation for them (plus
362 * for POSIX) is correct and the > 1 value is spurious. (Since
363 * these are specially handled to never be considered UTF-8
364 * locales, as long as this is the only problem, everything
365 * should work fine */
366 && strNE(newctype, "C") && strNE(newctype, "POSIX"))
368 multi_byte_locale = TRUE;
372 if (bad_count || multi_byte_locale) {
373 PL_warn_locale = Perl_newSVpvf(aTHX_
374 "Locale '%s' may not work well.%s%s%s\n",
377 ? " Some characters in it are not recognized by"
381 ? "\nThe following characters (and maybe others)"
382 " may not have the same meaning as the Perl"
383 " program expects:\n"
389 /* If we are actually in the scope of the locale, output the
390 * message now. Otherwise we save it to be output at the first
391 * operation using this locale, if that actually happens. Most
392 * programs don't use locales, so they are immune to bad ones */
393 if (IN_LC(LC_CTYPE)) {
395 /* We have to save 'newctype' because the setlocale() just
396 * below may destroy it. The next setlocale() further down
397 * should restore it properly so that the intermediate change
398 * here is transparent to this function's caller */
399 const char * const badlocale = savepv(newctype);
401 setlocale(LC_CTYPE, "C");
403 /* The '0' below suppresses a bogus gcc compiler warning */
404 Perl_warner(aTHX_ packWARN(WARN_LOCALE), SvPVX(PL_warn_locale), 0);
405 setlocale(LC_CTYPE, badlocale);
407 SvREFCNT_dec_NN(PL_warn_locale);
408 PL_warn_locale = NULL;
413 #endif /* USE_LOCALE_CTYPE */
414 PERL_ARGS_ASSERT_NEW_CTYPE;
415 PERL_UNUSED_ARG(newctype);
420 Perl__warn_problematic_locale()
423 #ifdef USE_LOCALE_CTYPE
427 /* Internal-to-core function that outputs the message in PL_warn_locale,
428 * and then NULLS it. Should be called only through the macro
429 * _CHECK_AND_WARN_PROBLEMATIC_LOCALE */
431 if (PL_warn_locale) {
432 /*GCC_DIAG_IGNORE(-Wformat-security); Didn't work */
433 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
434 SvPVX(PL_warn_locale),
435 0 /* dummy to avoid compiler warning */ );
436 /* GCC_DIAG_RESTORE; */
437 SvREFCNT_dec_NN(PL_warn_locale);
438 PL_warn_locale = NULL;
446 Perl_new_collate(pTHX_ const char *newcoll)
448 #ifdef USE_LOCALE_COLLATE
450 /* Called after all libc setlocale() calls affecting LC_COLLATE, to tell
451 * core Perl this and that 'newcoll' is the name of the new locale.
453 * Any code changing the locale (outside this file) should use
454 * POSIX::setlocale, which calls this function. Therefore this function
455 * should be called directly only from this file and from
456 * POSIX::setlocale() */
459 if (PL_collation_name) {
461 Safefree(PL_collation_name);
462 PL_collation_name = NULL;
464 PL_collation_standard = TRUE;
465 PL_collxfrm_base = 0;
466 PL_collxfrm_mult = 2;
470 if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
472 Safefree(PL_collation_name);
473 PL_collation_name = stdize_locale(savepv(newcoll));
474 PL_collation_standard = isNAME_C_OR_POSIX(newcoll);
477 /* 2: at most so many chars ('a', 'b'). */
478 /* 50: surely no system expands a char more. */
479 #define XFRMBUFSIZE (2 * 50)
480 char xbuf[XFRMBUFSIZE];
481 const Size_t fa = strxfrm(xbuf, "a", XFRMBUFSIZE);
482 const Size_t fb = strxfrm(xbuf, "ab", XFRMBUFSIZE);
483 const SSize_t mult = fb - fa;
484 if (mult < 1 && !(fa == 0 && fb == 0))
485 Perl_croak(aTHX_ "panic: strxfrm() gets absurd - a => %"UVuf", ab => %"UVuf,
487 PL_collxfrm_base = (fa > (Size_t)mult) ? (fa - mult) : 0;
488 PL_collxfrm_mult = mult;
493 PERL_UNUSED_ARG(newcoll);
494 #endif /* USE_LOCALE_COLLATE */
500 Perl_my_setlocale(pTHX_ int category, const char* locale)
502 /* This, for Windows, emulates POSIX setlocale() behavior. There is no
503 * difference unless the input locale is "", which means on Windows to get
504 * the machine default, which is set via the computer's "Regional and
505 * Language Options" (or its current equivalent). In POSIX, it instead
506 * means to find the locale from the user's environment. This routine
507 * looks in the environment, and, if anything is found, uses that instead
508 * of going to the machine default. If there is no environment override,
509 * the machine default is used, as normal, by calling the real setlocale()
510 * with "". The POSIX behavior is to use the LC_ALL variable if set;
511 * otherwise to use the particular category's variable if set; otherwise to
512 * use the LANG variable. */
514 bool override_LC_ALL = FALSE;
517 if (locale && strEQ(locale, "")) {
519 locale = PerlEnv_getenv("LC_ALL");
525 override_LC_ALL = TRUE;
526 break; /* We already know its variable isn't set */
528 # ifdef USE_LOCALE_TIME
530 locale = PerlEnv_getenv("LC_TIME");
533 # ifdef USE_LOCALE_CTYPE
535 locale = PerlEnv_getenv("LC_CTYPE");
538 # ifdef USE_LOCALE_COLLATE
540 locale = PerlEnv_getenv("LC_COLLATE");
543 # ifdef USE_LOCALE_MONETARY
545 locale = PerlEnv_getenv("LC_MONETARY");
548 # ifdef USE_LOCALE_NUMERIC
550 locale = PerlEnv_getenv("LC_NUMERIC");
553 # ifdef USE_LOCALE_MESSAGES
555 locale = PerlEnv_getenv("LC_MESSAGES");
559 /* This is a category, like PAPER_SIZE that we don't
560 * know about; and so can't provide a wrapper. */
564 locale = PerlEnv_getenv("LANG");
574 result = setlocale(category, locale);
575 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n", __FILE__, __LINE__,
576 _setlocale_debug_string(category, locale, result)));
578 if (! override_LC_ALL) {
582 /* Here the input category was LC_ALL, and we have set it to what is in the
583 * LANG variable or the system default if there is no LANG. But these have
584 * lower priority than the other LC_foo variables, so override it for each
585 * one that is set. (If they are set to "", it means to use the same thing
586 * we just set LC_ALL to, so can skip) */
587 # ifdef USE_LOCALE_TIME
588 result = PerlEnv_getenv("LC_TIME");
589 if (result && strNE(result, "")) {
590 setlocale(LC_TIME, result);
591 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
593 _setlocale_debug_string(LC_TIME, result, "not captured")));
596 # ifdef USE_LOCALE_CTYPE
597 result = PerlEnv_getenv("LC_CTYPE");
598 if (result && strNE(result, "")) {
599 setlocale(LC_CTYPE, result);
600 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
602 _setlocale_debug_string(LC_CTYPE, result, "not captured")));
605 # ifdef USE_LOCALE_COLLATE
606 result = PerlEnv_getenv("LC_COLLATE");
607 if (result && strNE(result, "")) {
608 setlocale(LC_COLLATE, result);
609 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
611 _setlocale_debug_string(LC_COLLATE, result, "not captured")));
614 # ifdef USE_LOCALE_MONETARY
615 result = PerlEnv_getenv("LC_MONETARY");
616 if (result && strNE(result, "")) {
617 setlocale(LC_MONETARY, result);
618 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
620 _setlocale_debug_string(LC_MONETARY, result, "not captured")));
623 # ifdef USE_LOCALE_NUMERIC
624 result = PerlEnv_getenv("LC_NUMERIC");
625 if (result && strNE(result, "")) {
626 setlocale(LC_NUMERIC, result);
627 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
629 _setlocale_debug_string(LC_NUMERIC, result, "not captured")));
632 # ifdef USE_LOCALE_MESSAGES
633 result = PerlEnv_getenv("LC_MESSAGES");
634 if (result && strNE(result, "")) {
635 setlocale(LC_MESSAGES, result);
636 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
638 _setlocale_debug_string(LC_MESSAGES, result, "not captured")));
642 result = setlocale(LC_ALL, NULL);
643 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
645 _setlocale_debug_string(LC_ALL, NULL, result)));
654 * Initialize locale awareness.
657 Perl_init_i18nl10n(pTHX_ int printwarn)
661 * 0 if not to output warning when setup locale is bad
662 * 1 if to output warning based on value of PERL_BADLANG
663 * >1 if to output regardless of PERL_BADLANG
666 * 1 = set ok or not applicable,
667 * 0 = fallback to a locale of lower priority
668 * -1 = fallback to all locales failed, not even to the C locale
670 * Under -DDEBUGGING, if the environment variable PERL_DEBUG_LOCALE_INIT is
671 * set, debugging information is output.
673 * This looks more complicated than it is, mainly due to the #ifdefs.
675 * We try to set LC_ALL to the value determined by the environment. If
676 * there is no LC_ALL on this platform, we try the individual categories we
677 * know about. If this works, we are done.
679 * But if it doesn't work, we have to do something else. We search the
680 * environment variables ourselves instead of relying on the system to do
681 * it. We look at, in order, LC_ALL, LANG, a system default locale (if we
682 * think there is one), and the ultimate fallback "C". This is all done in
683 * the same loop as above to avoid duplicating code, but it makes things
684 * more complex. After the original failure, we add the fallback
685 * possibilities to the list of locales to try, and iterate the loop
686 * through them all until one succeeds.
688 * On Ultrix, the locale MUST come from the environment, so there is
689 * preliminary code to set it. I (khw) am not sure that it is necessary,
690 * and that this couldn't be folded into the loop, but barring any real
691 * platforms to test on, it's staying as-is
693 * A slight complication is that in embedded Perls, the locale may already
694 * be set-up, and we don't want to get it from the normal environment
695 * variables. This is handled by having a special environment variable
696 * indicate we're in this situation. We simply set setlocale's 2nd
697 * parameter to be a NULL instead of "". That indicates to setlocale that
698 * it is not to change anything, but to return the current value,
699 * effectively initializing perl's db to what the locale already is.
701 * We play the same trick with NULL if a LC_ALL succeeds. We call
702 * setlocale() on the individual categores with NULL to get their existing
703 * values for our db, instead of trying to change them.
708 #if defined(USE_LOCALE)
709 #ifdef USE_LOCALE_CTYPE
710 char *curctype = NULL;
711 #endif /* USE_LOCALE_CTYPE */
712 #ifdef USE_LOCALE_COLLATE
713 char *curcoll = NULL;
714 #endif /* USE_LOCALE_COLLATE */
715 #ifdef USE_LOCALE_NUMERIC
717 #endif /* USE_LOCALE_NUMERIC */
719 const char * const language = savepv(PerlEnv_getenv("LANGUAGE"));
722 /* NULL uses the existing already set up locale */
723 const char * const setlocale_init = (PerlEnv_getenv("PERL_SKIP_LOCALE_INIT"))
727 const bool debug = (PerlEnv_getenv("PERL_DEBUG_LOCALE_INIT"))
730 # define DEBUG_LOCALE_INIT(category, locale, result) \
733 PerlIO_printf(Perl_debug_log, \
735 __FILE__, __LINE__, \
736 _setlocale_debug_string(category, \
742 # define DEBUG_LOCALE_INIT(a,b,c)
744 const char* trial_locales[5]; /* 5 = 1 each for "", LC_ALL, LANG, "", C */
745 unsigned int trial_locales_count;
746 const char * const lc_all = savepv(PerlEnv_getenv("LC_ALL"));
747 const char * const lang = savepv(PerlEnv_getenv("LANG"));
748 bool setlocale_failure = FALSE;
752 /* A later getenv() could zap this, so only use here */
753 const char * const bad_lang_use_once = PerlEnv_getenv("PERL_BADLANG");
755 const bool locwarn = (printwarn > 1
757 && (! bad_lang_use_once
759 /* disallow with "" or "0" */
761 && strNE("0", bad_lang_use_once)))));
763 char * sl_result; /* return from setlocale() */
766 /* In some systems you can find out the system default locale
767 * and use that as the fallback locale. */
768 # define SYSTEM_DEFAULT_LOCALE
770 #ifdef SYSTEM_DEFAULT_LOCALE
771 const char *system_default_locale = NULL;
774 #ifndef LOCALE_ENVIRON_REQUIRED
775 PERL_UNUSED_VAR(done);
776 PERL_UNUSED_VAR(locale_param);
780 * Ultrix setlocale(..., "") fails if there are no environment
781 * variables from which to get a locale name.
786 sl_result = my_setlocale(LC_ALL, setlocale_init);
787 DEBUG_LOCALE_INIT(LC_ALL, setlocale_init, sl_result);
791 setlocale_failure = TRUE;
793 if (! setlocale_failure) {
794 # ifdef USE_LOCALE_CTYPE
795 locale_param = (! done && (lang || PerlEnv_getenv("LC_CTYPE")))
798 curctype = my_setlocale(LC_CTYPE, locale_param);
799 DEBUG_LOCALE_INIT(LC_CTYPE, locale_param, sl_result);
801 setlocale_failure = TRUE;
803 curctype = savepv(curctype);
804 # endif /* USE_LOCALE_CTYPE */
805 # ifdef USE_LOCALE_COLLATE
806 locale_param = (! done && (lang || PerlEnv_getenv("LC_COLLATE")))
809 curcoll = my_setlocale(LC_COLLATE, locale_param);
810 DEBUG_LOCALE_INIT(LC_COLLATE, locale_param, sl_result);
812 setlocale_failure = TRUE;
814 curcoll = savepv(curcoll);
815 # endif /* USE_LOCALE_COLLATE */
816 # ifdef USE_LOCALE_NUMERIC
817 locale_param = (! done && (lang || PerlEnv_getenv("LC_NUMERIC")))
820 curnum = my_setlocale(LC_NUMERIC, locale_param);
821 DEBUG_LOCALE_INIT(LC_NUMERIC, locale_param, sl_result);
823 setlocale_failure = TRUE;
825 curnum = savepv(curnum);
826 # endif /* USE_LOCALE_NUMERIC */
827 # ifdef USE_LOCALE_MESSAGES
828 locale_param = (! done && (lang || PerlEnv_getenv("LC_MESSAGES")))
831 sl_result = my_setlocale(LC_MESSAGES, locale_param);
832 DEBUG_LOCALE_INIT(LC_MESSAGES, locale_param, sl_result);
834 setlocale_failure = TRUE;
836 # endif /* USE_LOCALE_MESSAGES */
837 # ifdef USE_LOCALE_MONETARY
838 locale_param = (! done && (lang || PerlEnv_getenv("LC_MONETARY")))
841 sl_result = my_setlocale(LC_MONETARY, locale_param);
842 DEBUG_LOCALE_INIT(LC_MONETARY, locale_param, sl_result);
844 setlocale_failure = TRUE;
846 # endif /* USE_LOCALE_MONETARY */
851 #endif /* !LOCALE_ENVIRON_REQUIRED */
853 /* We try each locale in the list until we get one that works, or exhaust
854 * the list. Normally the loop is executed just once. But if setting the
855 * locale fails, inside the loop we add fallback trials to the array and so
856 * will execute the loop multiple times */
857 trial_locales[0] = setlocale_init;
858 trial_locales_count = 1;
859 for (i= 0; i < trial_locales_count; i++) {
860 const char * trial_locale = trial_locales[i];
864 /* XXX This is to preserve old behavior for LOCALE_ENVIRON_REQUIRED
865 * when i==0, but I (khw) don't think that behavior makes much
867 setlocale_failure = FALSE;
869 #ifdef SYSTEM_DEFAULT_LOCALE
871 /* On Windows machines, an entry of "" after the 0th means to use
872 * the system default locale, which we now proceed to get. */
873 if (strEQ(trial_locale, "")) {
876 /* Note that this may change the locale, but we are going to do
877 * that anyway just below */
878 system_default_locale = setlocale(LC_ALL, "");
879 DEBUG_LOCALE_INIT(LC_ALL, "", system_default_locale);
881 /* Skip if invalid or it's already on the list of locales to
883 if (! system_default_locale) {
886 for (j = 0; j < trial_locales_count; j++) {
887 if (strEQ(system_default_locale, trial_locales[j])) {
892 trial_locale = system_default_locale;
895 #endif /* SYSTEM_DEFAULT_LOCALE */
899 sl_result = my_setlocale(LC_ALL, trial_locale);
900 DEBUG_LOCALE_INIT(LC_ALL, trial_locale, sl_result);
902 setlocale_failure = TRUE;
905 /* Since LC_ALL succeeded, it should have changed all the other
906 * categories it can to its value; so we massage things so that the
907 * setlocales below just return their category's current values.
908 * This adequately handles the case in NetBSD where LC_COLLATE may
909 * not be defined for a locale, and setting it individually will
910 * fail, whereas setting LC_ALL suceeds, leaving LC_COLLATE set to
911 * the POSIX locale. */
916 if (!setlocale_failure) {
917 #ifdef USE_LOCALE_CTYPE
919 curctype = my_setlocale(LC_CTYPE, trial_locale);
920 DEBUG_LOCALE_INIT(LC_CTYPE, trial_locale, curctype);
922 setlocale_failure = TRUE;
924 curctype = savepv(curctype);
925 #endif /* USE_LOCALE_CTYPE */
926 #ifdef USE_LOCALE_COLLATE
928 curcoll = my_setlocale(LC_COLLATE, trial_locale);
929 DEBUG_LOCALE_INIT(LC_COLLATE, trial_locale, curcoll);
931 setlocale_failure = TRUE;
933 curcoll = savepv(curcoll);
934 #endif /* USE_LOCALE_COLLATE */
935 #ifdef USE_LOCALE_NUMERIC
937 curnum = my_setlocale(LC_NUMERIC, trial_locale);
938 DEBUG_LOCALE_INIT(LC_NUMERIC, trial_locale, curnum);
940 setlocale_failure = TRUE;
942 curnum = savepv(curnum);
943 #endif /* USE_LOCALE_NUMERIC */
944 #ifdef USE_LOCALE_MESSAGES
945 sl_result = my_setlocale(LC_MESSAGES, trial_locale);
946 DEBUG_LOCALE_INIT(LC_MESSAGES, trial_locale, sl_result);
948 setlocale_failure = TRUE;
949 #endif /* USE_LOCALE_MESSAGES */
950 #ifdef USE_LOCALE_MONETARY
951 sl_result = my_setlocale(LC_MONETARY, trial_locale);
952 DEBUG_LOCALE_INIT(LC_MONETARY, trial_locale, sl_result);
954 setlocale_failure = TRUE;
955 #endif /* USE_LOCALE_MONETARY */
957 if (! setlocale_failure) { /* Success */
962 /* Here, something failed; will need to try a fallback. */
968 if (locwarn) { /* Output failure info only on the first one */
971 PerlIO_printf(Perl_error_log,
972 "perl: warning: Setting locale failed.\n");
976 PerlIO_printf(Perl_error_log,
977 "perl: warning: Setting locale failed for the categories:\n\t");
978 # ifdef USE_LOCALE_CTYPE
980 PerlIO_printf(Perl_error_log, "LC_CTYPE ");
981 # endif /* USE_LOCALE_CTYPE */
982 # ifdef USE_LOCALE_COLLATE
984 PerlIO_printf(Perl_error_log, "LC_COLLATE ");
985 # endif /* USE_LOCALE_COLLATE */
986 # ifdef USE_LOCALE_NUMERIC
988 PerlIO_printf(Perl_error_log, "LC_NUMERIC ");
989 # endif /* USE_LOCALE_NUMERIC */
990 PerlIO_printf(Perl_error_log, "and possibly others\n");
994 PerlIO_printf(Perl_error_log,
995 "perl: warning: Please check that your locale settings:\n");
998 PerlIO_printf(Perl_error_log,
999 "\tLANGUAGE = %c%s%c,\n",
1000 language ? '"' : '(',
1001 language ? language : "unset",
1002 language ? '"' : ')');
1005 PerlIO_printf(Perl_error_log,
1006 "\tLC_ALL = %c%s%c,\n",
1008 lc_all ? lc_all : "unset",
1009 lc_all ? '"' : ')');
1011 #if defined(USE_ENVIRON_ARRAY)
1014 for (e = environ; *e; e++) {
1015 if (strnEQ(*e, "LC_", 3)
1016 && strnNE(*e, "LC_ALL=", 7)
1017 && (p = strchr(*e, '=')))
1018 PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
1019 (int)(p - *e), *e, p + 1);
1023 PerlIO_printf(Perl_error_log,
1024 "\t(possibly more locale environment variables)\n");
1027 PerlIO_printf(Perl_error_log,
1028 "\tLANG = %c%s%c\n",
1030 lang ? lang : "unset",
1033 PerlIO_printf(Perl_error_log,
1034 " are supported and installed on your system.\n");
1037 /* Calculate what fallback locales to try. We have avoided this
1038 * until we have to, because failure is quite unlikely. This will
1039 * usually change the upper bound of the loop we are in.
1041 * Since the system's default way of setting the locale has not
1042 * found one that works, We use Perl's defined ordering: LC_ALL,
1043 * LANG, and the C locale. We don't try the same locale twice, so
1044 * don't add to the list if already there. (On POSIX systems, the
1045 * LC_ALL element will likely be a repeat of the 0th element "",
1046 * but there's no harm done by doing it explicitly.
1048 * Note that this tries the LC_ALL environment variable even on
1049 * systems which have no LC_ALL locale setting. This may or may
1050 * not have been originally intentional, but there's no real need
1051 * to change the behavior. */
1053 for (j = 0; j < trial_locales_count; j++) {
1054 if (strEQ(lc_all, trial_locales[j])) {
1058 trial_locales[trial_locales_count++] = lc_all;
1063 for (j = 0; j < trial_locales_count; j++) {
1064 if (strEQ(lang, trial_locales[j])) {
1068 trial_locales[trial_locales_count++] = lang;
1072 #if defined(WIN32) && defined(LC_ALL)
1073 /* For Windows, we also try the system default locale before "C".
1074 * (If there exists a Windows without LC_ALL we skip this because
1075 * it gets too complicated. For those, the "C" is the next
1076 * fallback possibility). The "" is the same as the 0th element of
1077 * the array, but the code at the loop above knows to treat it
1078 * differently when not the 0th */
1079 trial_locales[trial_locales_count++] = "";
1082 for (j = 0; j < trial_locales_count; j++) {
1083 if (strEQ("C", trial_locales[j])) {
1087 trial_locales[trial_locales_count++] = "C";
1090 } /* end of first time through the loop */
1096 } /* end of looping through the trial locales */
1098 if (ok < 1) { /* If we tried to fallback */
1100 if (! setlocale_failure) { /* fallback succeeded */
1101 msg = "Falling back to";
1103 else { /* fallback failed */
1105 /* We dropped off the end of the loop, so have to decrement i to
1106 * get back to the value the last time through */
1110 msg = "Failed to fall back to";
1112 /* To continue, we should use whatever values we've got */
1113 #ifdef USE_LOCALE_CTYPE
1115 curctype = savepv(setlocale(LC_CTYPE, NULL));
1116 DEBUG_LOCALE_INIT(LC_CTYPE, NULL, curctype);
1117 #endif /* USE_LOCALE_CTYPE */
1118 #ifdef USE_LOCALE_COLLATE
1120 curcoll = savepv(setlocale(LC_COLLATE, NULL));
1121 DEBUG_LOCALE_INIT(LC_COLLATE, NULL, curcoll);
1122 #endif /* USE_LOCALE_COLLATE */
1123 #ifdef USE_LOCALE_NUMERIC
1125 curnum = savepv(setlocale(LC_NUMERIC, NULL));
1126 DEBUG_LOCALE_INIT(LC_NUMERIC, NULL, curnum);
1127 #endif /* USE_LOCALE_NUMERIC */
1131 const char * description;
1132 const char * name = "";
1133 if (strEQ(trial_locales[i], "C")) {
1134 description = "the standard locale";
1137 #ifdef SYSTEM_DEFAULT_LOCALE
1138 else if (strEQ(trial_locales[i], "")) {
1139 description = "the system default locale";
1140 if (system_default_locale) {
1141 name = system_default_locale;
1144 #endif /* SYSTEM_DEFAULT_LOCALE */
1146 description = "a fallback locale";
1147 name = trial_locales[i];
1149 if (name && strNE(name, "")) {
1150 PerlIO_printf(Perl_error_log,
1151 "perl: warning: %s %s (\"%s\").\n", msg, description, name);
1154 PerlIO_printf(Perl_error_log,
1155 "perl: warning: %s %s.\n", msg, description);
1158 } /* End of tried to fallback */
1160 #ifdef USE_LOCALE_CTYPE
1161 new_ctype(curctype);
1162 #endif /* USE_LOCALE_CTYPE */
1164 #ifdef USE_LOCALE_COLLATE
1165 new_collate(curcoll);
1166 #endif /* USE_LOCALE_COLLATE */
1168 #ifdef USE_LOCALE_NUMERIC
1169 new_numeric(curnum);
1170 #endif /* USE_LOCALE_NUMERIC */
1172 #if defined(USE_PERLIO) && defined(USE_LOCALE_CTYPE)
1173 /* Set PL_utf8locale to TRUE if using PerlIO _and_ the current LC_CTYPE
1174 * locale is UTF-8. If PL_utf8locale and PL_unicode (set by -C or by
1175 * $ENV{PERL_UNICODE}) are true, perl.c:S_parse_body() will turn on the
1176 * PerlIO :utf8 layer on STDIN, STDOUT, STDERR, _and_ the default open
1178 PL_utf8locale = _is_cur_LC_category_utf8(LC_CTYPE);
1180 /* Set PL_unicode to $ENV{PERL_UNICODE} if using PerlIO.
1181 This is an alternative to using the -C command line switch
1182 (the -C if present will override this). */
1184 const char *p = PerlEnv_getenv("PERL_UNICODE");
1185 PL_unicode = p ? parse_unicode_opts(&p) : 0;
1186 if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
1191 #ifdef USE_LOCALE_CTYPE
1193 #endif /* USE_LOCALE_CTYPE */
1194 #ifdef USE_LOCALE_COLLATE
1196 #endif /* USE_LOCALE_COLLATE */
1197 #ifdef USE_LOCALE_NUMERIC
1199 #endif /* USE_LOCALE_NUMERIC */
1208 #else /* !USE_LOCALE */
1209 PERL_UNUSED_ARG(printwarn);
1210 #endif /* USE_LOCALE */
1216 #ifdef USE_LOCALE_COLLATE
1219 * mem_collxfrm() is a bit like strxfrm() but with two important
1220 * differences. First, it handles embedded NULs. Second, it allocates
1221 * a bit more memory than needed for the transformed data itself.
1222 * The real transformed data begins at offset sizeof(collationix).
1223 * Please see sv_collxfrm() to see how this is used.
1227 Perl_mem_collxfrm(pTHX_ const char *s, STRLEN len, STRLEN *xlen)
1230 STRLEN xAlloc, xin, xout; /* xalloc is a reserved word in VC */
1232 PERL_ARGS_ASSERT_MEM_COLLXFRM;
1234 /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
1235 /* the +1 is for the terminating NUL. */
1237 xAlloc = sizeof(PL_collation_ix) + PL_collxfrm_base + (PL_collxfrm_mult * len) + 1;
1238 Newx(xbuf, xAlloc, char);
1242 *(U32*)xbuf = PL_collation_ix;
1243 xout = sizeof(PL_collation_ix);
1244 for (xin = 0; xin < len; ) {
1248 xused = strxfrm(xbuf + xout, s + xin, xAlloc - xout);
1249 if (xused >= PERL_INT_MAX)
1251 if ((STRLEN)xused < xAlloc - xout)
1253 xAlloc = (2 * xAlloc) + 1;
1254 Renew(xbuf, xAlloc, char);
1259 xin += strlen(s + xin) + 1;
1262 /* Embedded NULs are understood but silently skipped
1263 * because they make no sense in locale collation. */
1267 *xlen = xout - sizeof(PL_collation_ix);
1276 #endif /* USE_LOCALE_COLLATE */
1281 Perl__is_cur_LC_category_utf8(pTHX_ int category)
1283 /* Returns TRUE if the current locale for 'category' is UTF-8; FALSE
1284 * otherwise. 'category' may not be LC_ALL. If the platform doesn't have
1285 * nl_langinfo(), nor MB_CUR_MAX, this employs a heuristic, which hence
1286 * could give the wrong result. The result will very likely be correct for
1287 * languages that have commonly used non-ASCII characters, but for notably
1288 * English, it comes down to if the locale's name ends in something like
1289 * "UTF-8". It errs on the side of not being a UTF-8 locale. */
1291 char *save_input_locale = NULL;
1295 assert(category != LC_ALL);
1298 /* First dispose of the trivial cases */
1299 save_input_locale = setlocale(category, NULL);
1300 if (! save_input_locale) {
1301 DEBUG_L(PerlIO_printf(Perl_debug_log,
1302 "Could not find current locale for category %d\n",
1304 return FALSE; /* XXX maybe should croak */
1306 save_input_locale = stdize_locale(savepv(save_input_locale));
1307 if (isNAME_C_OR_POSIX(save_input_locale)) {
1308 DEBUG_L(PerlIO_printf(Perl_debug_log,
1309 "Current locale for category %d is %s\n",
1310 category, save_input_locale));
1311 Safefree(save_input_locale);
1315 #if defined(USE_LOCALE_CTYPE) \
1316 && (defined(MB_CUR_MAX) || (defined(HAS_NL_LANGINFO) && defined(CODESET)))
1318 { /* Next try nl_langinfo or MB_CUR_MAX if available */
1320 char *save_ctype_locale = NULL;
1323 if (category != LC_CTYPE) { /* These work only on LC_CTYPE */
1325 /* Get the current LC_CTYPE locale */
1326 save_ctype_locale = setlocale(LC_CTYPE, NULL);
1327 if (! save_ctype_locale) {
1328 DEBUG_L(PerlIO_printf(Perl_debug_log,
1329 "Could not find current locale for LC_CTYPE\n"));
1330 goto cant_use_nllanginfo;
1332 save_ctype_locale = stdize_locale(savepv(save_ctype_locale));
1334 /* If LC_CTYPE and the desired category use the same locale, this
1335 * means that finding the value for LC_CTYPE is the same as finding
1336 * the value for the desired category. Otherwise, switch LC_CTYPE
1337 * to the desired category's locale */
1338 if (strEQ(save_ctype_locale, save_input_locale)) {
1339 Safefree(save_ctype_locale);
1340 save_ctype_locale = NULL;
1342 else if (! setlocale(LC_CTYPE, save_input_locale)) {
1343 DEBUG_L(PerlIO_printf(Perl_debug_log,
1344 "Could not change LC_CTYPE locale to %s\n",
1345 save_input_locale));
1346 Safefree(save_ctype_locale);
1347 goto cant_use_nllanginfo;
1351 DEBUG_L(PerlIO_printf(Perl_debug_log, "Current LC_CTYPE locale=%s\n",
1352 save_input_locale));
1354 /* Here the current LC_CTYPE is set to the locale of the category whose
1355 * information is desired. This means that nl_langinfo() and MB_CUR_MAX
1356 * should give the correct results */
1358 # if defined(HAS_NL_LANGINFO) && defined(CODESET)
1360 char *codeset = nl_langinfo(CODESET);
1361 if (codeset && strNE(codeset, "")) {
1362 codeset = savepv(codeset);
1364 /* If we switched LC_CTYPE, switch back */
1365 if (save_ctype_locale) {
1366 setlocale(LC_CTYPE, save_ctype_locale);
1367 Safefree(save_ctype_locale);
1370 is_utf8 = foldEQ(codeset, STR_WITH_LEN("UTF-8"))
1371 || foldEQ(codeset, STR_WITH_LEN("UTF8"));
1373 DEBUG_L(PerlIO_printf(Perl_debug_log,
1374 "\tnllanginfo returned CODESET '%s'; ?UTF8 locale=%d\n",
1377 Safefree(save_input_locale);
1385 /* Here, either we don't have nl_langinfo, or it didn't return a
1386 * codeset. Try MB_CUR_MAX */
1388 /* Standard UTF-8 needs at least 4 bytes to represent the maximum
1389 * Unicode code point. Since UTF-8 is the only non-single byte
1390 * encoding we handle, we just say any such encoding is UTF-8, and if
1391 * turns out to be wrong, other things will fail */
1392 is_utf8 = MB_CUR_MAX >= 4;
1394 DEBUG_L(PerlIO_printf(Perl_debug_log,
1395 "\tMB_CUR_MAX=%d; ?UTF8 locale=%d\n",
1396 (int) MB_CUR_MAX, is_utf8));
1398 Safefree(save_input_locale);
1402 /* ... But, most system that have MB_CUR_MAX will also have mbtowc(),
1403 * since they are both in the C99 standard. We can feed a known byte
1404 * string to the latter function, and check that it gives the expected
1408 PERL_UNUSED_RESULT(mbtowc(&wc, NULL, 0));/* Reset any shift state */
1410 if ((size_t)mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8))
1411 != strlen(HYPHEN_UTF8)
1412 || wc != (wchar_t) 0x2010)
1415 DEBUG_L(PerlIO_printf(Perl_debug_log, "\thyphen=U+%x\n", (unsigned int)wc));
1416 DEBUG_L(PerlIO_printf(Perl_debug_log,
1417 "\treturn from mbtowc=%d; errno=%d; ?UTF8 locale=0\n",
1418 mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8)), errno));
1423 /* If we switched LC_CTYPE, switch back */
1424 if (save_ctype_locale) {
1425 setlocale(LC_CTYPE, save_ctype_locale);
1426 Safefree(save_ctype_locale);
1433 cant_use_nllanginfo:
1435 #else /* nl_langinfo should work if available, so don't bother compiling this
1436 fallback code. The final fallback of looking at the name is
1437 compiled, and will be executed if nl_langinfo fails */
1439 /* nl_langinfo not available or failed somehow. Next try looking at the
1440 * currency symbol to see if it disambiguates things. Often that will be
1441 * in the native script, and if the symbol isn't in UTF-8, we know that the
1442 * locale isn't. If it is non-ASCII UTF-8, we infer that the locale is
1443 * too, as the odds of a non-UTF8 string being valid UTF-8 are quite small
1446 #ifdef HAS_LOCALECONV
1447 # ifdef USE_LOCALE_MONETARY
1449 char *save_monetary_locale = NULL;
1450 bool only_ascii = FALSE;
1451 bool is_utf8 = FALSE;
1454 /* Like above for LC_CTYPE, we first set LC_MONETARY to the locale of
1455 * the desired category, if it isn't that locale already */
1457 if (category != LC_MONETARY) {
1459 save_monetary_locale = setlocale(LC_MONETARY, NULL);
1460 if (! save_monetary_locale) {
1461 DEBUG_L(PerlIO_printf(Perl_debug_log,
1462 "Could not find current locale for LC_MONETARY\n"));
1463 goto cant_use_monetary;
1465 save_monetary_locale = stdize_locale(savepv(save_monetary_locale));
1467 if (strEQ(save_monetary_locale, save_input_locale)) {
1468 Safefree(save_monetary_locale);
1469 save_monetary_locale = NULL;
1471 else if (! setlocale(LC_MONETARY, save_input_locale)) {
1472 DEBUG_L(PerlIO_printf(Perl_debug_log,
1473 "Could not change LC_MONETARY locale to %s\n",
1474 save_input_locale));
1475 Safefree(save_monetary_locale);
1476 goto cant_use_monetary;
1480 /* Here the current LC_MONETARY is set to the locale of the category
1481 * whose information is desired. */
1485 || ! lc->currency_symbol
1486 || is_invariant_string((U8 *) lc->currency_symbol, 0))
1488 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));
1492 is_utf8 = is_utf8_string((U8 *) lc->currency_symbol, 0);
1495 /* If we changed it, restore LC_MONETARY to its original locale */
1496 if (save_monetary_locale) {
1497 setlocale(LC_MONETARY, save_monetary_locale);
1498 Safefree(save_monetary_locale);
1503 /* It isn't a UTF-8 locale if the symbol is not legal UTF-8;
1504 * otherwise assume the locale is UTF-8 if and only if the symbol
1505 * is non-ascii UTF-8. */
1506 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?Currency symbol for %s is UTF-8=%d\n",
1507 save_input_locale, is_utf8));
1508 Safefree(save_input_locale);
1514 # endif /* USE_LOCALE_MONETARY */
1515 #endif /* HAS_LOCALECONV */
1517 #if defined(HAS_STRFTIME) && defined(USE_LOCALE_TIME)
1519 /* Still haven't found a non-ASCII string to disambiguate UTF-8 or not. Try
1520 * the names of the months and weekdays, timezone, and am/pm indicator */
1522 char *save_time_locale = NULL;
1524 bool is_dst = FALSE;
1528 char * formatted_time;
1531 /* Like above for LC_MONETARY, we set LC_TIME to the locale of the
1532 * desired category, if it isn't that locale already */
1534 if (category != LC_TIME) {
1536 save_time_locale = setlocale(LC_TIME, NULL);
1537 if (! save_time_locale) {
1538 DEBUG_L(PerlIO_printf(Perl_debug_log,
1539 "Could not find current locale for LC_TIME\n"));
1542 save_time_locale = stdize_locale(savepv(save_time_locale));
1544 if (strEQ(save_time_locale, save_input_locale)) {
1545 Safefree(save_time_locale);
1546 save_time_locale = NULL;
1548 else if (! setlocale(LC_TIME, save_input_locale)) {
1549 DEBUG_L(PerlIO_printf(Perl_debug_log,
1550 "Could not change LC_TIME locale to %s\n",
1551 save_input_locale));
1552 Safefree(save_time_locale);
1557 /* Here the current LC_TIME is set to the locale of the category
1558 * whose information is desired. Look at all the days of the week and
1559 * month names, and the timezone and am/pm indicator for UTF-8 variant
1560 * characters. The first such a one found will tell us if the locale
1561 * is UTF-8 or not */
1563 for (i = 0; i < 7 + 12; i++) { /* 7 days; 12 months */
1564 formatted_time = my_strftime("%A %B %Z %p",
1565 0, 0, hour, dom, month, 112, 0, 0, is_dst);
1566 if (! formatted_time || is_invariant_string((U8 *) formatted_time, 0)) {
1568 /* Here, we didn't find a non-ASCII. Try the next time through
1569 * with the complemented dst and am/pm, and try with the next
1570 * weekday. After we have gotten all weekdays, try the next
1573 hour = (hour + 12) % 24;
1581 /* Here, we have a non-ASCII. Return TRUE is it is valid UTF8;
1582 * false otherwise. But first, restore LC_TIME to its original
1583 * locale if we changed it */
1584 if (save_time_locale) {
1585 setlocale(LC_TIME, save_time_locale);
1586 Safefree(save_time_locale);
1589 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?time-related strings for %s are UTF-8=%d\n",
1591 is_utf8_string((U8 *) formatted_time, 0)));
1592 Safefree(save_input_locale);
1593 return is_utf8_string((U8 *) formatted_time, 0);
1596 /* Falling off the end of the loop indicates all the names were just
1597 * ASCII. Go on to the next test. If we changed it, restore LC_TIME
1598 * to its original locale */
1599 if (save_time_locale) {
1600 setlocale(LC_TIME, save_time_locale);
1601 Safefree(save_time_locale);
1603 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));
1609 #if 0 && defined(USE_LOCALE_MESSAGES) && defined(HAS_SYS_ERRLIST)
1611 /* This code is ifdefd out because it was found to not be necessary in testing
1612 * on our dromedary test machine, which has over 700 locales. There, this
1613 * added no value to looking at the currency symbol and the time strings. I
1614 * left it in so as to avoid rewriting it if real-world experience indicates
1615 * that dromedary is an outlier. Essentially, instead of returning abpve if we
1616 * haven't found illegal utf8, we continue on and examine all the strerror()
1617 * messages on the platform for utf8ness. If all are ASCII, we still don't
1618 * know the answer; but otherwise we have a pretty good indication of the
1619 * utf8ness. The reason this doesn't help much is that the messages may not
1620 * have been translated into the locale. The currency symbol and time strings
1621 * are much more likely to have been translated. */
1624 bool is_utf8 = FALSE;
1625 bool non_ascii = FALSE;
1626 char *save_messages_locale = NULL;
1627 const char * errmsg = NULL;
1629 /* Like above, we set LC_MESSAGES to the locale of the desired
1630 * category, if it isn't that locale already */
1632 if (category != LC_MESSAGES) {
1634 save_messages_locale = setlocale(LC_MESSAGES, NULL);
1635 if (! save_messages_locale) {
1636 DEBUG_L(PerlIO_printf(Perl_debug_log,
1637 "Could not find current locale for LC_MESSAGES\n"));
1638 goto cant_use_messages;
1640 save_messages_locale = stdize_locale(savepv(save_messages_locale));
1642 if (strEQ(save_messages_locale, save_input_locale)) {
1643 Safefree(save_messages_locale);
1644 save_messages_locale = NULL;
1646 else if (! setlocale(LC_MESSAGES, save_input_locale)) {
1647 DEBUG_L(PerlIO_printf(Perl_debug_log,
1648 "Could not change LC_MESSAGES locale to %s\n",
1649 save_input_locale));
1650 Safefree(save_messages_locale);
1651 goto cant_use_messages;
1655 /* Here the current LC_MESSAGES is set to the locale of the category
1656 * whose information is desired. Look through all the messages. We
1657 * can't use Strerror() here because it may expand to code that
1658 * segfaults in miniperl */
1660 for (e = 0; e <= sys_nerr; e++) {
1662 errmsg = sys_errlist[e];
1663 if (errno || !errmsg) {
1666 errmsg = savepv(errmsg);
1667 if (! is_invariant_string((U8 *) errmsg, 0)) {
1669 is_utf8 = is_utf8_string((U8 *) errmsg, 0);
1675 /* And, if we changed it, restore LC_MESSAGES to its original locale */
1676 if (save_messages_locale) {
1677 setlocale(LC_MESSAGES, save_messages_locale);
1678 Safefree(save_messages_locale);
1683 /* Any non-UTF-8 message means not a UTF-8 locale; if all are valid,
1684 * any non-ascii means it is one; otherwise we assume it isn't */
1685 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?error messages for %s are UTF-8=%d\n",
1688 Safefree(save_input_locale);
1692 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));
1698 #endif /* the code that is compiled when no nl_langinfo */
1700 #ifndef EBCDIC /* On os390, even if the name ends with "UTF-8', it isn't a
1702 /* As a last resort, look at the locale name to see if it matches
1703 * qr/UTF -? * 8 /ix, or some other common locale names. This "name", the
1704 * return of setlocale(), is actually defined to be opaque, so we can't
1705 * really rely on the absence of various substrings in the name to indicate
1706 * its UTF-8ness, but if it has UTF8 in the name, it is extremely likely to
1707 * be a UTF-8 locale. Similarly for the other common names */
1709 final_pos = strlen(save_input_locale) - 1;
1710 if (final_pos >= 3) {
1711 char *name = save_input_locale;
1713 /* Find next 'U' or 'u' and look from there */
1714 while ((name += strcspn(name, "Uu") + 1)
1715 <= save_input_locale + final_pos - 2)
1717 if (!isALPHA_FOLD_NE(*name, 't')
1718 || isALPHA_FOLD_NE(*(name + 1), 'f'))
1723 if (*(name) == '-') {
1724 if ((name > save_input_locale + final_pos - 1)) {
1729 if (*(name) == '8') {
1730 DEBUG_L(PerlIO_printf(Perl_debug_log,
1731 "Locale %s ends with UTF-8 in name\n",
1732 save_input_locale));
1733 Safefree(save_input_locale);
1737 DEBUG_L(PerlIO_printf(Perl_debug_log,
1738 "Locale %s doesn't end with UTF-8 in name\n",
1739 save_input_locale));
1744 /* http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756.aspx */
1746 && *(save_input_locale + final_pos - 0) == '1'
1747 && *(save_input_locale + final_pos - 1) == '0'
1748 && *(save_input_locale + final_pos - 2) == '0'
1749 && *(save_input_locale + final_pos - 3) == '5'
1750 && *(save_input_locale + final_pos - 4) == '6')
1752 DEBUG_L(PerlIO_printf(Perl_debug_log,
1753 "Locale %s ends with 10056 in name, is UTF-8 locale\n",
1754 save_input_locale));
1755 Safefree(save_input_locale);
1760 /* Other common encodings are the ISO 8859 series, which aren't UTF-8. But
1761 * since we are about to return FALSE anyway, there is no point in doing
1762 * this extra work */
1764 if (instr(save_input_locale, "8859")) {
1765 DEBUG_L(PerlIO_printf(Perl_debug_log,
1766 "Locale %s has 8859 in name, not UTF-8 locale\n",
1767 save_input_locale));
1768 Safefree(save_input_locale);
1773 DEBUG_L(PerlIO_printf(Perl_debug_log,
1774 "Assuming locale %s is not a UTF-8 locale\n",
1775 save_input_locale));
1776 Safefree(save_input_locale);
1784 Perl__is_in_locale_category(pTHX_ const bool compiling, const int category)
1787 /* Internal function which returns if we are in the scope of a pragma that
1788 * enables the locale category 'category'. 'compiling' should indicate if
1789 * this is during the compilation phase (TRUE) or not (FALSE). */
1791 const COP * const cop = (compiling) ? &PL_compiling : PL_curcop;
1793 SV *categories = cop_hints_fetch_pvs(cop, "locale", 0);
1794 if (! categories || categories == &PL_sv_placeholder) {
1798 /* The pseudo-category 'not_characters' is -1, so just add 1 to each to get
1799 * a valid unsigned */
1800 assert(category >= -1);
1801 return cBOOL(SvUV(categories) & (1U << (category + 1)));
1805 Perl_my_strerror(pTHX_ const int errnum) {
1807 /* Uses C locale for the error text unless within scope of 'use locale' for
1810 #ifdef USE_LOCALE_MESSAGES
1811 if (! IN_LC(LC_MESSAGES)) {
1812 char * save_locale = setlocale(LC_MESSAGES, NULL);
1813 if (! isNAME_C_OR_POSIX(save_locale)) {
1816 /* The next setlocale likely will zap this, so create a copy */
1817 save_locale = savepv(save_locale);
1819 setlocale(LC_MESSAGES, "C");
1821 /* This points to the static space in Strerror, with all its
1823 errstr = Strerror(errnum);
1825 setlocale(LC_MESSAGES, save_locale);
1826 Safefree(save_locale);
1832 return Strerror(errnum);
1837 =head1 Locale-related functions and macros
1839 =for apidoc sync_locale
1841 Changing the program's locale should be avoided by XS code. Nevertheless,
1842 certain non-Perl libraries called from XS, such as C<Gtk> do so. When this
1843 happens, Perl needs to be told that the locale has changed. Use this function
1844 to do so, before returning to Perl.
1850 Perl_sync_locale(pTHX)
1853 #ifdef USE_LOCALE_CTYPE
1854 new_ctype(setlocale(LC_CTYPE, NULL));
1855 #endif /* USE_LOCALE_CTYPE */
1857 #ifdef USE_LOCALE_COLLATE
1858 new_collate(setlocale(LC_COLLATE, NULL));
1861 #ifdef USE_LOCALE_NUMERIC
1862 set_numeric_local(); /* Switch from "C" to underlying LC_NUMERIC */
1863 new_numeric(setlocale(LC_NUMERIC, NULL));
1864 #endif /* USE_LOCALE_NUMERIC */
1868 #if defined(DEBUGGING) && defined(USE_LOCALE)
1871 Perl__setlocale_debug_string(const int category, /* category number,
1873 const char* const locale, /* locale name */
1875 /* return value from setlocale() when attempting to
1876 * set 'category' to 'locale' */
1877 const char* const retval)
1879 /* Returns a pointer to a NUL-terminated string in static storage with
1880 * added text about the info passed in. This is not thread safe and will
1881 * be overwritten by the next call, so this should be used just to
1882 * formulate a string to immediately print or savepv() on. */
1884 /* initialise to a non-null value to keep it out of BSS and so keep
1885 * -DPERL_GLOBAL_STRUCT_PRIVATE happy */
1886 static char ret[128] = "x";
1888 my_strlcpy(ret, "setlocale(", sizeof(ret));
1892 my_snprintf(ret, sizeof(ret), "%s? %d", ret, category);
1896 my_strlcat(ret, "LC_ALL", sizeof(ret));
1901 my_strlcat(ret, "LC_CTYPE", sizeof(ret));
1906 my_strlcat(ret, "LC_NUMERIC", sizeof(ret));
1911 my_strlcat(ret, "LC_COLLATE", sizeof(ret));
1916 my_strlcat(ret, "LC_TIME", sizeof(ret));
1921 my_strlcat(ret, "LC_MONETARY", sizeof(ret));
1926 my_strlcat(ret, "LC_MESSAGES", sizeof(ret));
1931 my_strlcat(ret, ", ", sizeof(ret));
1934 my_strlcat(ret, "\"", sizeof(ret));
1935 my_strlcat(ret, locale, sizeof(ret));
1936 my_strlcat(ret, "\"", sizeof(ret));
1939 my_strlcat(ret, "NULL", sizeof(ret));
1942 my_strlcat(ret, ") returned ", sizeof(ret));
1945 my_strlcat(ret, "\"", sizeof(ret));
1946 my_strlcat(ret, retval, sizeof(ret));
1947 my_strlcat(ret, "\"", sizeof(ret));
1950 my_strlcat(ret, "NULL", sizeof(ret));
1953 assert(strlen(ret) < sizeof(ret));
1962 * ex: set ts=8 sts=4 sw=4 et: