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 code generally doesn't pay
27 * any 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. And, LC_MESSAGES is
33 * switched to the C locale for outputting the message unless within the scope
38 #define PERL_IN_LOCALE_C
39 #include "perl_langinfo.h"
44 /* If the environment says to, we can output debugging information during
45 * initialization. This is done before option parsing, and before any thread
46 * creation, so can be a file-level static */
47 #if ! defined(DEBUGGING) || defined(PERL_GLOBAL_STRUCT)
48 # define debug_initialization 0
49 # define DEBUG_INITIALIZATION_set(v)
51 static bool debug_initialization = FALSE;
52 # define DEBUG_INITIALIZATION_set(v) (debug_initialization = v)
55 /* strlen() of a literal string constant. We might want this more general,
56 * but using it in just this file for now. A problem with more generality is
57 * the compiler warnings about comparing unlike signs */
58 #define STRLENs(s) (sizeof("" s "") - 1)
60 /* Is the C string input 'name' "C" or "POSIX"? If so, and 'name' is the
61 * return of setlocale(), then this is extremely likely to be the C or POSIX
62 * locale. However, the output of setlocale() is documented to be opaque, but
63 * the odds are extremely small that it would return these two strings for some
64 * other locale. Note that VMS in these two locales includes many non-ASCII
65 * characters as controls and punctuation (below are hex bytes):
67 * punct: A1-A3 A5 A7-AB B0-B3 B5-B7 B9-BD BF-CF D1-DD DF-EF F1-FD
68 * Oddly, none there are listed as alphas, though some represent alphabetics
69 * http://www.nntp.perl.org/group/perl.perl5.porters/2013/02/msg198753.html */
70 #define isNAME_C_OR_POSIX(name) \
72 && (( *(name) == 'C' && (*(name + 1)) == '\0') \
73 || strEQ((name), "POSIX")))
77 /* This code keeps a LRU cache of the UTF-8ness of the locales it has so-far
78 * looked up. This is in the form of a C string: */
80 #define UTF8NESS_SEP "\v"
81 #define UTF8NESS_PREFIX "\f"
83 /* So, the string looks like:
85 * \vC\a0\vPOSIX\a0\vam_ET\a0\vaf_ZA.utf8\a1\ven_US.UTF-8\a1\0
87 * where the digit 0 after the \a indicates that the locale starting just
88 * after the preceding \v is not UTF-8, and the digit 1 mean it is. */
90 STATIC_ASSERT_DECL(STRLENs(UTF8NESS_SEP) == 1);
91 STATIC_ASSERT_DECL(STRLENs(UTF8NESS_PREFIX) == 1);
93 #define C_and_POSIX_utf8ness UTF8NESS_SEP "C" UTF8NESS_PREFIX "0" \
94 UTF8NESS_SEP "POSIX" UTF8NESS_PREFIX "0"
96 /* The cache is initialized to C_and_POSIX_utf8ness at start up. These are
97 * kept there always. The remining portion of the cache is LRU, with the
98 * oldest looked-up locale at the tail end */
101 S_stdize_locale(pTHX_ char *locs)
103 /* Standardize the locale name from a string returned by 'setlocale',
104 * possibly modifying that string.
106 * The typical return value of setlocale() is either
107 * (1) "xx_YY" if the first argument of setlocale() is not LC_ALL
108 * (2) "xa_YY xb_YY ..." if the first argument of setlocale() is LC_ALL
109 * (the space-separated values represent the various sublocales,
110 * in some unspecified order). This is not handled by this function.
112 * In some platforms it has a form like "LC_SOMETHING=Lang_Country.866\n",
113 * which is harmful for further use of the string in setlocale(). This
114 * function removes the trailing new line and everything up through the '='
117 const char * const s = strchr(locs, '=');
120 PERL_ARGS_ASSERT_STDIZE_LOCALE;
123 const char * const t = strchr(s, '.');
126 const char * const u = strchr(t, '\n');
127 if (u && (u[1] == 0)) {
128 const STRLEN len = u - s;
129 Move(s + 1, locs, len, char);
137 Perl_croak(aTHX_ "Can't fix broken locale name \"%s\"", locs);
142 /* Two parallel arrays; first the locale categories Perl uses on this system;
143 * the second array is their names. These arrays are in mostly arbitrary
146 const int categories[] = {
148 # ifdef USE_LOCALE_NUMERIC
151 # ifdef USE_LOCALE_CTYPE
154 # ifdef USE_LOCALE_COLLATE
157 # ifdef USE_LOCALE_TIME
160 # ifdef USE_LOCALE_MESSAGES
163 # ifdef USE_LOCALE_MONETARY
166 # ifdef USE_LOCALE_ADDRESS
169 # ifdef USE_LOCALE_IDENTIFICATION
172 # ifdef USE_LOCALE_MEASUREMENT
175 # ifdef USE_LOCALE_PAPER
178 # ifdef USE_LOCALE_TELEPHONE
184 -1 /* Placeholder because C doesn't allow a
185 trailing comma, and it would get complicated
186 with all the #ifdef's */
189 /* The top-most real element is LC_ALL */
191 const char * category_names[] = {
193 # ifdef USE_LOCALE_NUMERIC
196 # ifdef USE_LOCALE_CTYPE
199 # ifdef USE_LOCALE_COLLATE
202 # ifdef USE_LOCALE_TIME
205 # ifdef USE_LOCALE_MESSAGES
208 # ifdef USE_LOCALE_MONETARY
211 # ifdef USE_LOCALE_ADDRESS
214 # ifdef USE_LOCALE_IDENTIFICATION
217 # ifdef USE_LOCALE_MEASUREMENT
220 # ifdef USE_LOCALE_PAPER
223 # ifdef USE_LOCALE_TELEPHONE
229 NULL /* Placeholder */
234 /* On systems with LC_ALL, it is kept in the highest index position. (-2
235 * to account for the final unused placeholder element.) */
236 # define NOMINAL_LC_ALL_INDEX (C_ARRAY_LENGTH(categories) - 2)
240 /* On systems without LC_ALL, we pretend it is there, one beyond the real
241 * top element, hence in the unused placeholder element. */
242 # define NOMINAL_LC_ALL_INDEX (C_ARRAY_LENGTH(categories) - 1)
246 /* Pretending there is an LC_ALL element just above allows us to avoid most
247 * special cases. Most loops through these arrays in the code below are
248 * written like 'for (i = 0; i < NOMINAL_LC_ALL_INDEX; i++)'. They will work
249 * on either type of system. But the code must be written to not access the
250 * element at 'LC_ALL_INDEX' except on platforms that have it. This can be
251 * checked for at compile time by using the #define LC_ALL_INDEX which is only
252 * defined if we do have LC_ALL. */
255 S_category_name(const int category)
261 if (category == LC_ALL) {
267 for (i = 0; i < NOMINAL_LC_ALL_INDEX; i++) {
268 if (category == categories[i]) {
269 return category_names[i];
274 const char suffix[] = " (unknown)";
276 Size_t length = sizeof(suffix) + 1;
285 /* Calculate the number of digits */
291 Newx(unknown, length, char);
292 my_snprintf(unknown, length, "%d%s", category, suffix);
298 /* Now create LC_foo_INDEX #defines for just those categories on this system */
299 # ifdef USE_LOCALE_NUMERIC
300 # define LC_NUMERIC_INDEX 0
301 # define _DUMMY_NUMERIC LC_NUMERIC_INDEX
303 # define _DUMMY_NUMERIC -1
305 # ifdef USE_LOCALE_CTYPE
306 # define LC_CTYPE_INDEX _DUMMY_NUMERIC + 1
307 # define _DUMMY_CTYPE LC_CTYPE_INDEX
309 # define _DUMMY_CTYPE _DUMMY_NUMERIC
311 # ifdef USE_LOCALE_COLLATE
312 # define LC_COLLATE_INDEX _DUMMY_CTYPE + 1
313 # define _DUMMY_COLLATE LC_COLLATE_INDEX
315 # define _DUMMY_COLLATE _DUMMY_COLLATE
317 # ifdef USE_LOCALE_TIME
318 # define LC_TIME_INDEX _DUMMY_COLLATE + 1
319 # define _DUMMY_TIME LC_TIME_INDEX
321 # define _DUMMY_TIME _DUMMY_COLLATE
323 # ifdef USE_LOCALE_MESSAGES
324 # define LC_MESSAGES_INDEX _DUMMY_TIME + 1
325 # define _DUMMY_MESSAGES LC_MESSAGES_INDEX
327 # define _DUMMY_MESSAGES _DUMMY_TIME
329 # ifdef USE_LOCALE_MONETARY
330 # define LC_MONETARY_INDEX _DUMMY_MESSAGES + 1
331 # define _DUMMY_MONETARY LC_MONETARY_INDEX
333 # define _DUMMY_MONETARY _DUMMY_MESSAGES
335 # ifdef USE_LOCALE_ADDRESS
336 # define LC_ADDRESS_INDEX _DUMMY_MONETARY + 1
337 # define _DUMMY_ADDRESS LC_ADDRESS_INDEX
339 # define _DUMMY_ADDRESS _DUMMY_MONETARY
341 # ifdef USE_LOCALE_IDENTIFICATION
342 # define LC_IDENTIFICATION_INDEX _DUMMY_ADDRESS + 1
343 # define _DUMMY_IDENTIFICATION LC_IDENTIFICATION_INDEX
345 # define _DUMMY_IDENTIFICATION _DUMMY_ADDRESS
347 # ifdef USE_LOCALE_MEASUREMENT
348 # define LC_MEASUREMENT_INDEX _DUMMY_IDENTIFICATION + 1
349 # define _DUMMY_MEASUREMENT LC_MEASUREMENT_INDEX
351 # define _DUMMY_MEASUREMENT _DUMMY_IDENTIFICATION
353 # ifdef USE_LOCALE_PAPER
354 # define LC_PAPER_INDEX _DUMMY_MEASUREMENT + 1
355 # define _DUMMY_PAPER LC_PAPER_INDEX
357 # define _DUMMY_PAPER _DUMMY_MEASUREMENT
359 # ifdef USE_LOCALE_TELEPHONE
360 # define LC_TELEPHONE_INDEX _DUMMY_PAPER + 1
361 # define _DUMMY_TELEPHONE LC_TELEPHONE_INDEX
363 # define _DUMMY_TELEPHONE _DUMMY_PAPER
366 # define LC_ALL_INDEX _DUMMY_TELEPHONE + 1
368 #endif /* ifdef USE_LOCALE */
370 /* Windows requres a customized base-level setlocale() */
372 # define my_setlocale(cat, locale) win32_setlocale(cat, locale)
374 # define my_setlocale(cat, locale) setlocale(cat, locale)
377 /* Just placeholders for now. "_c" is intended to be called when the category
378 * is a constant known at compile time; "_r", not known until run time */
379 # define do_setlocale_c(category, locale) my_setlocale(category, locale)
380 # define do_setlocale_r(category, locale) my_setlocale(category, locale)
383 S_set_numeric_radix(pTHX_ const bool use_locale)
385 /* If 'use_locale' is FALSE, set to use a dot for the radix character. If
386 * TRUE, use the radix character derived from the current locale */
388 #if defined(USE_LOCALE_NUMERIC) && ( defined(HAS_LOCALECONV) \
389 || defined(HAS_NL_LANGINFO))
391 /* We only set up the radix SV if we are to use a locale radix ... */
393 const char * radix = my_nl_langinfo(PERL_RADIXCHAR, FALSE);
394 /* FALSE => already in dest locale */
395 /* ... and the character being used isn't a dot */
396 if (strNE(radix, ".")) {
397 const U8 * first_variant;
399 if (PL_numeric_radix_sv) {
400 sv_setpv(PL_numeric_radix_sv, radix);
403 PL_numeric_radix_sv = newSVpv(radix, 0);
406 /* If there is a byte variant under UTF-8, and if the remainder of
407 * the string starting there is valid UTF-8, and we are in a UTF-8
408 * locale, then mark the radix as being in UTF-8 */
409 if ( ! is_utf8_invariant_string_loc(
410 (U8 *) SvPVX(PL_numeric_radix_sv),
411 SvCUR(PL_numeric_radix_sv),
413 && is_utf8_string(first_variant,
414 SvCUR(PL_numeric_radix_sv)
415 - ((char *) first_variant
416 - SvPVX(PL_numeric_radix_sv)))
417 && _is_cur_LC_category_utf8(LC_NUMERIC))
419 SvUTF8_on(PL_numeric_radix_sv);
425 SvREFCNT_dec(PL_numeric_radix_sv);
426 PL_numeric_radix_sv = NULL;
432 if (DEBUG_L_TEST || debug_initialization) {
433 PerlIO_printf(Perl_debug_log, "Locale radix is '%s', ?UTF-8=%d\n",
434 (PL_numeric_radix_sv)
435 ? SvPVX(PL_numeric_radix_sv)
437 (PL_numeric_radix_sv)
438 ? cBOOL(SvUTF8(PL_numeric_radix_sv))
443 #endif /* USE_LOCALE_NUMERIC and can find the radix char */
449 Perl_new_numeric(pTHX_ const char *newnum)
452 #ifndef USE_LOCALE_NUMERIC
454 PERL_UNUSED_ARG(newnum);
458 /* Called after each libc setlocale() call affecting LC_NUMERIC, to tell
459 * core Perl this and that 'newnum' is the name of the new locale.
460 * It installs this locale as the current underlying default.
462 * The default locale and the C locale can be toggled between by use of the
463 * set_numeric_underlying() and set_numeric_standard() functions, which
464 * should probably not be called directly, but only via macros like
465 * SET_NUMERIC_STANDARD() in perl.h.
467 * The toggling is necessary mainly so that a non-dot radix decimal point
468 * character can be output, while allowing internal calculations to use a
471 * This sets several interpreter-level variables:
472 * PL_numeric_name The underlying locale's name: a copy of 'newnum'
473 * PL_numeric_underlying A boolean indicating if the toggled state is such
474 * that the current locale is the program's underlying
476 * PL_numeric_standard An int indicating if the toggled state is such
477 * that the current locale is the C locale or
478 * indistinguishable from the C locale. If non-zero, it
479 * is in C; if > 1, it means it may not be toggled away
481 * PL_numeric_underlying_is_standard A bool kept by this function
482 * indicating that the underlying locale and the standard
483 * C locale are indistinguishable for the purposes of
484 * LC_NUMERIC. This happens when both of the above two
485 * variables are true at the same time. (Toggling is a
486 * no-op under these circumstances.) This variable is
487 * used to avoid having to recalculate.
488 * Any code changing the locale (outside this file) should use
489 * POSIX::setlocale, which calls this function. Therefore this function
490 * should be called directly only from this file and from
491 * POSIX::setlocale() */
496 Safefree(PL_numeric_name);
497 PL_numeric_name = NULL;
498 PL_numeric_standard = TRUE;
499 PL_numeric_underlying = TRUE;
500 PL_numeric_underlying_is_standard = TRUE;
504 save_newnum = stdize_locale(savepv(newnum));
505 PL_numeric_underlying = TRUE;
506 PL_numeric_standard = isNAME_C_OR_POSIX(save_newnum);
508 /* If its name isn't C nor POSIX, it could still be indistinguishable from
510 if (! PL_numeric_standard) {
511 PL_numeric_standard = cBOOL(strEQ(".", my_nl_langinfo(PERL_RADIXCHAR,
512 FALSE /* Don't toggle locale */ ))
513 && strEQ("", my_nl_langinfo(PERL_THOUSEP,
517 /* Save the new name if it isn't the same as the previous one, if any */
518 if (! PL_numeric_name || strNE(PL_numeric_name, save_newnum)) {
519 Safefree(PL_numeric_name);
520 PL_numeric_name = save_newnum;
523 Safefree(save_newnum);
526 PL_numeric_underlying_is_standard = PL_numeric_standard;
528 if (DEBUG_L_TEST || debug_initialization) {
529 PerlIO_printf(Perl_debug_log, "Called new_numeric with %s, PL_numeric_name=%s\n", newnum, PL_numeric_name);
532 /* Keep LC_NUMERIC in the C locale. This is for XS modules, so they don't
533 * have to worry about the radix being a non-dot. (Core operations that
534 * need the underlying locale change to it temporarily). */
535 set_numeric_standard();
537 #endif /* USE_LOCALE_NUMERIC */
542 Perl_set_numeric_standard(pTHX)
545 #ifdef USE_LOCALE_NUMERIC
547 /* Toggle the LC_NUMERIC locale to C. Most code should use the macros like
548 * SET_NUMERIC_STANDARD() in perl.h instead of calling this directly. The
549 * macro avoids calling this routine if toggling isn't necessary according
550 * to our records (which could be wrong if some XS code has changed the
551 * locale behind our back) */
553 do_setlocale_c(LC_NUMERIC, "C");
554 PL_numeric_standard = TRUE;
555 PL_numeric_underlying = PL_numeric_underlying_is_standard;
556 set_numeric_radix(0);
560 if (DEBUG_L_TEST || debug_initialization) {
561 PerlIO_printf(Perl_debug_log,
562 "LC_NUMERIC locale now is standard C\n");
566 #endif /* USE_LOCALE_NUMERIC */
571 Perl_set_numeric_underlying(pTHX)
574 #ifdef USE_LOCALE_NUMERIC
576 /* Toggle the LC_NUMERIC locale to the current underlying default. Most
577 * code should use the macros like SET_NUMERIC_UNDERLYING() in perl.h
578 * instead of calling this directly. The macro avoids calling this routine
579 * if toggling isn't necessary according to our records (which could be
580 * wrong if some XS code has changed the locale behind our back) */
582 do_setlocale_c(LC_NUMERIC, PL_numeric_name);
583 PL_numeric_standard = PL_numeric_underlying_is_standard;
584 PL_numeric_underlying = TRUE;
585 set_numeric_radix(! PL_numeric_standard);
589 if (DEBUG_L_TEST || debug_initialization) {
590 PerlIO_printf(Perl_debug_log,
591 "LC_NUMERIC locale now is %s\n",
596 #endif /* USE_LOCALE_NUMERIC */
601 * Set up for a new ctype locale.
604 S_new_ctype(pTHX_ const char *newctype)
607 #ifndef USE_LOCALE_CTYPE
609 PERL_ARGS_ASSERT_NEW_CTYPE;
610 PERL_UNUSED_ARG(newctype);
615 /* Called after each libc setlocale() call affecting LC_CTYPE, to tell
616 * core Perl this and that 'newctype' is the name of the new locale.
618 * This function sets up the folding arrays for all 256 bytes, assuming
619 * that tofold() is tolc() since fold case is not a concept in POSIX,
621 * Any code changing the locale (outside this file) should use
622 * POSIX::setlocale, which calls this function. Therefore this function
623 * should be called directly only from this file and from
624 * POSIX::setlocale() */
629 PERL_ARGS_ASSERT_NEW_CTYPE;
631 /* We will replace any bad locale warning with 1) nothing if the new one is
632 * ok; or 2) a new warning for the bad new locale */
633 if (PL_warn_locale) {
634 SvREFCNT_dec_NN(PL_warn_locale);
635 PL_warn_locale = NULL;
638 PL_in_utf8_CTYPE_locale = _is_cur_LC_category_utf8(LC_CTYPE);
640 /* A UTF-8 locale gets standard rules. But note that code still has to
641 * handle this specially because of the three problematic code points */
642 if (PL_in_utf8_CTYPE_locale) {
643 Copy(PL_fold_latin1, PL_fold_locale, 256, U8);
646 /* Assume enough space for every character being bad. 4 spaces each
647 * for the 94 printable characters that are output like "'x' "; and 5
648 * spaces each for "'\\' ", "'\t' ", and "'\n' "; plus a terminating
650 char bad_chars_list[ (94 * 4) + (3 * 5) + 1 ];
652 /* Don't check for problems if we are suppressing the warnings */
653 bool check_for_problems = ckWARN_d(WARN_LOCALE)
654 || UNLIKELY(DEBUG_L_TEST);
655 bool multi_byte_locale = FALSE; /* Assume is a single-byte locale
657 unsigned int bad_count = 0; /* Count of bad characters */
659 for (i = 0; i < 256; i++) {
661 PL_fold_locale[i] = (U8) tolower(i);
663 PL_fold_locale[i] = (U8) toupper(i);
665 PL_fold_locale[i] = (U8) i;
667 /* If checking for locale problems, see if the native ASCII-range
668 * printables plus \n and \t are in their expected categories in
669 * the new locale. If not, this could mean big trouble, upending
670 * Perl's and most programs' assumptions, like having a
671 * metacharacter with special meaning become a \w. Fortunately,
672 * it's very rare to find locales that aren't supersets of ASCII
673 * nowadays. It isn't a problem for most controls to be changed
674 * into something else; we check only \n and \t, though perhaps \r
675 * could be an issue as well. */
676 if ( check_for_problems
677 && (isGRAPH_A(i) || isBLANK_A(i) || i == '\n'))
679 if ( cBOOL(isalnum(i)) != cBOOL(isALPHANUMERIC(i))
680 || cBOOL(isalpha(i)) != cBOOL(isALPHA_A(i))
681 || cBOOL(isdigit(i)) != cBOOL(isDIGIT_A(i))
682 || cBOOL(isgraph(i)) != cBOOL(isGRAPH_A(i))
683 || cBOOL(islower(i)) != cBOOL(isLOWER_A(i))
684 || cBOOL(isprint(i)) != cBOOL(isPRINT_A(i))
685 || cBOOL(ispunct(i)) != cBOOL(isPUNCT_A(i))
686 || cBOOL(isspace(i)) != cBOOL(isSPACE_A(i))
687 || cBOOL(isupper(i)) != cBOOL(isUPPER_A(i))
688 || cBOOL(isxdigit(i))!= cBOOL(isXDIGIT_A(i))
689 || tolower(i) != (int) toLOWER_A(i)
690 || toupper(i) != (int) toUPPER_A(i)
691 || (i == '\n' && ! isCNTRL_LC(i)))
693 if (bad_count) { /* Separate multiple entries with a
695 bad_chars_list[bad_count++] = ' ';
697 bad_chars_list[bad_count++] = '\'';
699 bad_chars_list[bad_count++] = (char) i;
702 bad_chars_list[bad_count++] = '\\';
704 bad_chars_list[bad_count++] = 'n';
708 bad_chars_list[bad_count++] = 't';
711 bad_chars_list[bad_count++] = '\'';
712 bad_chars_list[bad_count] = '\0';
719 /* We only handle single-byte locales (outside of UTF-8 ones; so if
720 * this locale requires more than one byte, there are going to be
722 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
723 "%s:%d: check_for_problems=%d, MB_CUR_MAX=%d\n",
724 __FILE__, __LINE__, check_for_problems, (int) MB_CUR_MAX));
726 if (check_for_problems && MB_CUR_MAX > 1
728 /* Some platforms return MB_CUR_MAX > 1 for even the "C"
729 * locale. Just assume that the implementation for them (plus
730 * for POSIX) is correct and the > 1 value is spurious. (Since
731 * these are specially handled to never be considered UTF-8
732 * locales, as long as this is the only problem, everything
733 * should work fine */
734 && strNE(newctype, "C") && strNE(newctype, "POSIX"))
736 multi_byte_locale = TRUE;
741 if (bad_count || multi_byte_locale) {
742 PL_warn_locale = Perl_newSVpvf(aTHX_
743 "Locale '%s' may not work well.%s%s%s\n",
746 ? " Some characters in it are not recognized by"
750 ? "\nThe following characters (and maybe others)"
751 " may not have the same meaning as the Perl"
752 " program expects:\n"
758 /* If we are actually in the scope of the locale or are debugging,
759 * output the message now. If not in that scope, we save the
760 * message to be output at the first operation using this locale,
761 * if that actually happens. Most programs don't use locales, so
762 * they are immune to bad ones. */
763 if (IN_LC(LC_CTYPE) || UNLIKELY(DEBUG_L_TEST)) {
765 /* We have to save 'newctype' because the setlocale() just
766 * below may destroy it. The next setlocale() further down
767 * should restore it properly so that the intermediate change
768 * here is transparent to this function's caller */
769 const char * const badlocale = savepv(newctype);
771 do_setlocale_c(LC_CTYPE, "C");
773 /* The '0' below suppresses a bogus gcc compiler warning */
774 Perl_warner(aTHX_ packWARN(WARN_LOCALE), SvPVX(PL_warn_locale), 0);
776 do_setlocale_c(LC_CTYPE, badlocale);
779 if (IN_LC(LC_CTYPE)) {
780 SvREFCNT_dec_NN(PL_warn_locale);
781 PL_warn_locale = NULL;
787 #endif /* USE_LOCALE_CTYPE */
792 Perl__warn_problematic_locale()
795 #ifdef USE_LOCALE_CTYPE
799 /* Internal-to-core function that outputs the message in PL_warn_locale,
800 * and then NULLS it. Should be called only through the macro
801 * _CHECK_AND_WARN_PROBLEMATIC_LOCALE */
803 if (PL_warn_locale) {
804 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
805 SvPVX(PL_warn_locale),
806 0 /* dummy to avoid compiler warning */ );
807 SvREFCNT_dec_NN(PL_warn_locale);
808 PL_warn_locale = NULL;
816 S_new_collate(pTHX_ const char *newcoll)
819 #ifndef USE_LOCALE_COLLATE
821 PERL_UNUSED_ARG(newcoll);
826 /* Called after each libc setlocale() call affecting LC_COLLATE, to tell
827 * core Perl this and that 'newcoll' is the name of the new locale.
829 * The design of locale collation is that every locale change is given an
830 * index 'PL_collation_ix'. The first time a string particpates in an
831 * operation that requires collation while locale collation is active, it
832 * is given PERL_MAGIC_collxfrm magic (via sv_collxfrm_flags()). That
833 * magic includes the collation index, and the transformation of the string
834 * by strxfrm(), q.v. That transformation is used when doing comparisons,
835 * instead of the string itself. If a string changes, the magic is
836 * cleared. The next time the locale changes, the index is incremented,
837 * and so we know during a comparison that the transformation is not
838 * necessarily still valid, and so is recomputed. Note that if the locale
839 * changes enough times, the index could wrap (a U32), and it is possible
840 * that a transformation would improperly be considered valid, leading to
844 if (PL_collation_name) {
846 Safefree(PL_collation_name);
847 PL_collation_name = NULL;
849 PL_collation_standard = TRUE;
850 is_standard_collation:
851 PL_collxfrm_base = 0;
852 PL_collxfrm_mult = 2;
853 PL_in_utf8_COLLATE_locale = FALSE;
854 PL_strxfrm_NUL_replacement = '\0';
855 PL_strxfrm_max_cp = 0;
859 /* If this is not the same locale as currently, set the new one up */
860 if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
862 Safefree(PL_collation_name);
863 PL_collation_name = stdize_locale(savepv(newcoll));
864 PL_collation_standard = isNAME_C_OR_POSIX(newcoll);
865 if (PL_collation_standard) {
866 goto is_standard_collation;
869 PL_in_utf8_COLLATE_locale = _is_cur_LC_category_utf8(LC_COLLATE);
870 PL_strxfrm_NUL_replacement = '\0';
871 PL_strxfrm_max_cp = 0;
873 /* A locale collation definition includes primary, secondary, tertiary,
874 * etc. weights for each character. To sort, the primary weights are
875 * used, and only if they compare equal, then the secondary weights are
876 * used, and only if they compare equal, then the tertiary, etc.
878 * strxfrm() works by taking the input string, say ABC, and creating an
879 * output transformed string consisting of first the primary weights,
880 * A¹B¹C¹ followed by the secondary ones, A²B²C²; and then the
881 * tertiary, etc, yielding A¹B¹C¹ A²B²C² A³B³C³ .... Some characters
882 * may not have weights at every level. In our example, let's say B
883 * doesn't have a tertiary weight, and A doesn't have a secondary
884 * weight. The constructed string is then going to be
885 * A¹B¹C¹ B²C² A³C³ ....
886 * This has the desired effect that strcmp() will look at the secondary
887 * or tertiary weights only if the strings compare equal at all higher
888 * priority weights. The spaces shown here, like in
890 * are not just for readability. In the general case, these must
891 * actually be bytes, which we will call here 'separator weights'; and
892 * they must be smaller than any other weight value, but since these
893 * are C strings, only the terminating one can be a NUL (some
894 * implementations may include a non-NUL separator weight just before
895 * the NUL). Implementations tend to reserve 01 for the separator
896 * weights. They are needed so that a shorter string's secondary
897 * weights won't be misconstrued as primary weights of a longer string,
898 * etc. By making them smaller than any other weight, the shorter
899 * string will sort first. (Actually, if all secondary weights are
900 * smaller than all primary ones, there is no need for a separator
901 * weight between those two levels, etc.)
903 * The length of the transformed string is roughly a linear function of
904 * the input string. It's not exactly linear because some characters
905 * don't have weights at all levels. When we call strxfrm() we have to
906 * allocate some memory to hold the transformed string. The
907 * calculations below try to find coefficients 'm' and 'b' for this
908 * locale so that m*x + b equals how much space we need, given the size
909 * of the input string in 'x'. If we calculate too small, we increase
910 * the size as needed, and call strxfrm() again, but it is better to
911 * get it right the first time to avoid wasted expensive string
912 * transformations. */
915 /* We use the string below to find how long the tranformation of it
916 * is. Almost all locales are supersets of ASCII, or at least the
917 * ASCII letters. We use all of them, half upper half lower,
918 * because if we used fewer, we might hit just the ones that are
919 * outliers in a particular locale. Most of the strings being
920 * collated will contain a preponderance of letters, and even if
921 * they are above-ASCII, they are likely to have the same number of
922 * weight levels as the ASCII ones. It turns out that digits tend
923 * to have fewer levels, and some punctuation has more, but those
924 * are relatively sparse in text, and khw believes this gives a
925 * reasonable result, but it could be changed if experience so
927 const char longer[] = "ABCDEFGHIJKLMnopqrstuvwxyz";
928 char * x_longer; /* Transformed 'longer' */
929 Size_t x_len_longer; /* Length of 'x_longer' */
931 char * x_shorter; /* We also transform a substring of 'longer' */
932 Size_t x_len_shorter;
934 /* _mem_collxfrm() is used get the transformation (though here we
935 * are interested only in its length). It is used because it has
936 * the intelligence to handle all cases, but to work, it needs some
937 * values of 'm' and 'b' to get it started. For the purposes of
938 * this calculation we use a very conservative estimate of 'm' and
939 * 'b'. This assumes a weight can be multiple bytes, enough to
940 * hold any UV on the platform, and there are 5 levels, 4 weight
941 * bytes, and a trailing NUL. */
942 PL_collxfrm_base = 5;
943 PL_collxfrm_mult = 5 * sizeof(UV);
945 /* Find out how long the transformation really is */
946 x_longer = _mem_collxfrm(longer,
950 /* We avoid converting to UTF-8 in the
951 * called function by telling it the
952 * string is in UTF-8 if the locale is a
953 * UTF-8 one. Since the string passed
954 * here is invariant under UTF-8, we can
955 * claim it's UTF-8 even though it isn't.
957 PL_in_utf8_COLLATE_locale);
960 /* Find out how long the transformation of a substring of 'longer'
961 * is. Together the lengths of these transformations are
962 * sufficient to calculate 'm' and 'b'. The substring is all of
963 * 'longer' except the first character. This minimizes the chances
964 * of being swayed by outliers */
965 x_shorter = _mem_collxfrm(longer + 1,
968 PL_in_utf8_COLLATE_locale);
971 /* If the results are nonsensical for this simple test, the whole
972 * locale definition is suspect. Mark it so that locale collation
973 * is not active at all for it. XXX Should we warn? */
974 if ( x_len_shorter == 0
976 || x_len_shorter >= x_len_longer)
978 PL_collxfrm_mult = 0;
979 PL_collxfrm_base = 0;
982 SSize_t base; /* Temporary */
984 /* We have both: m * strlen(longer) + b = x_len_longer
985 * m * strlen(shorter) + b = x_len_shorter;
986 * subtracting yields:
987 * m * (strlen(longer) - strlen(shorter))
988 * = x_len_longer - x_len_shorter
989 * But we have set things up so that 'shorter' is 1 byte smaller
990 * than 'longer'. Hence:
991 * m = x_len_longer - x_len_shorter
993 * But if something went wrong, make sure the multiplier is at
996 if (x_len_longer > x_len_shorter) {
997 PL_collxfrm_mult = (STRLEN) x_len_longer - x_len_shorter;
1000 PL_collxfrm_mult = 1;
1005 * but in case something has gone wrong, make sure it is
1007 base = x_len_longer - PL_collxfrm_mult * (sizeof(longer) - 1);
1012 /* Add 1 for the trailing NUL */
1013 PL_collxfrm_base = base + 1;
1018 if (DEBUG_L_TEST || debug_initialization) {
1019 PerlIO_printf(Perl_debug_log,
1020 "%s:%d: ?UTF-8 locale=%d; x_len_shorter=%zu, "
1022 " collate multipler=%zu, collate base=%zu\n",
1024 PL_in_utf8_COLLATE_locale,
1025 x_len_shorter, x_len_longer,
1026 PL_collxfrm_mult, PL_collxfrm_base);
1033 #endif /* USE_LOCALE_COLLATE */
1040 S_win32_setlocale(pTHX_ int category, const char* locale)
1042 /* This, for Windows, emulates POSIX setlocale() behavior. There is no
1043 * difference between the two unless the input locale is "", which normally
1044 * means on Windows to get the machine default, which is set via the
1045 * computer's "Regional and Language Options" (or its current equivalent).
1046 * In POSIX, it instead means to find the locale from the user's
1047 * environment. This routine changes the Windows behavior to first look in
1048 * the environment, and, if anything is found, use that instead of going to
1049 * the machine default. If there is no environment override, the machine
1050 * default is used, by calling the real setlocale() with "".
1052 * The POSIX behavior is to use the LC_ALL variable if set; otherwise to
1053 * use the particular category's variable if set; otherwise to use the LANG
1056 bool override_LC_ALL = FALSE;
1060 if (locale && strEQ(locale, "")) {
1064 locale = PerlEnv_getenv("LC_ALL");
1066 if (category == LC_ALL) {
1067 override_LC_ALL = TRUE;
1073 for (i = 0; i < NOMINAL_LC_ALL_INDEX; i++) {
1074 if (category == categories[i]) {
1075 locale = PerlEnv_getenv(category_names[i]);
1080 locale = PerlEnv_getenv("LANG");
1096 result = setlocale(category, locale);
1097 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n", __FILE__, __LINE__,
1098 setlocale_debug_string(category, locale, result)));
1100 if (! override_LC_ALL) {
1104 /* Here the input category was LC_ALL, and we have set it to what is in the
1105 * LANG variable or the system default if there is no LANG. But these have
1106 * lower priority than the other LC_foo variables, so override it for each
1107 * one that is set. (If they are set to "", it means to use the same thing
1108 * we just set LC_ALL to, so can skip) */
1110 for (i = 0; i < LC_ALL_INDEX; i++) {
1111 result = PerlEnv_getenv(category_names[i]);
1112 if (result && strNE(result, "")) {
1113 setlocale(categories[i], result);
1114 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
1116 setlocale_debug_string(categories[i], result, "not captured")));
1120 result = setlocale(LC_ALL, NULL);
1121 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
1123 setlocale_debug_string(LC_ALL, NULL, result)));
1131 Perl_setlocale(int category, const char * locale)
1133 /* This wraps POSIX::setlocale() */
1139 #ifdef USE_LOCALE_NUMERIC
1141 /* A NULL locale means only query what the current one is. We have the
1142 * LC_NUMERIC name saved, because we are normally switched into the C
1143 * locale for it. For an LC_ALL query, switch back to get the correct
1144 * results. All other categories don't require special handling */
1145 if (locale == NULL) {
1146 if (category == LC_NUMERIC) {
1147 return savepv(PL_numeric_name);
1152 else if (category == LC_ALL && ! PL_numeric_underlying) {
1154 SET_NUMERIC_UNDERLYING();
1163 /* Save retval since subsequent setlocale() calls may overwrite it. */
1164 retval = savepv(do_setlocale_r(category, locale));
1166 DEBUG_L(PerlIO_printf(Perl_debug_log,
1167 "%s:%d: %s\n", __FILE__, __LINE__,
1168 setlocale_debug_string(category, locale, retval)));
1170 /* Should never happen that a query would return an error, but be
1171 * sure and reset to C locale */
1173 SET_NUMERIC_STANDARD();
1179 /* If locale == NULL, we are just querying the state, but may have switched
1180 * to NUMERIC_UNDERLYING. Switch back before returning. */
1181 if (locale == NULL) {
1182 SET_NUMERIC_STANDARD();
1186 /* Now that have switched locales, we have to update our records to
1191 #ifdef USE_LOCALE_CTYPE
1198 #ifdef USE_LOCALE_COLLATE
1201 new_collate(retval);
1205 #ifdef USE_LOCALE_NUMERIC
1208 new_numeric(retval);
1216 /* LC_ALL updates all the things we care about. The values may not
1217 * be the same as 'retval', as the locale "" may have set things
1220 # ifdef USE_LOCALE_CTYPE
1222 newlocale = do_setlocale_c(LC_CTYPE, NULL);
1223 new_ctype(newlocale);
1225 # endif /* USE_LOCALE_CTYPE */
1226 # ifdef USE_LOCALE_COLLATE
1228 newlocale = do_setlocale_c(LC_COLLATE, NULL);
1229 new_collate(newlocale);
1232 # ifdef USE_LOCALE_NUMERIC
1234 newlocale = do_setlocale_c(LC_NUMERIC, NULL);
1235 new_numeric(newlocale);
1237 # endif /* USE_LOCALE_NUMERIC */
1249 PERL_STATIC_INLINE const char *
1250 S_save_to_buffer(const char * string, char **buf, Size_t *buf_size, const Size_t offset)
1252 /* Copy the NUL-terminated 'string' to 'buf' + 'offset'. 'buf' has size 'buf_size',
1253 * growing it if necessary */
1255 const Size_t string_size = strlen(string) + offset + 1;
1257 PERL_ARGS_ASSERT_SAVE_TO_BUFFER;
1259 if (*buf_size == 0) {
1260 Newx(*buf, string_size, char);
1261 *buf_size = string_size;
1263 else if (string_size > *buf_size) {
1264 Renew(*buf, string_size, char);
1265 *buf_size = string_size;
1268 Copy(string, *buf + offset, string_size - offset, char);
1274 =head1 Locale-related functions and macros
1276 =for apidoc Perl_langinfo
1278 This is an (almost ª) drop-in replacement for the system C<L<nl_langinfo(3)>>,
1279 taking the same C<item> parameter values, and returning the same information.
1280 But it is more thread-safe than regular C<nl_langinfo()>, and hides the quirks
1281 of Perl's locale handling from your code, and can be used on systems that lack
1282 a native C<nl_langinfo>.
1290 It delivers the correct results for the C<RADIXCHAR> and C<THOUSESEP> items,
1291 without you having to write extra code. The reason for the extra code would be
1292 because these are from the C<LC_NUMERIC> locale category, which is normally
1293 kept set to the C locale by Perl, no matter what the underlying locale is
1294 supposed to be, and so to get the expected results, you have to temporarily
1295 toggle into the underlying locale, and later toggle back. (You could use
1296 plain C<nl_langinfo> and C<L</STORE_LC_NUMERIC_FORCE_TO_UNDERLYING>> for this
1297 but then you wouldn't get the other advantages of C<Perl_langinfo()>; not
1298 keeping C<LC_NUMERIC> in the C locale would break a lot of CPAN, which is
1299 expecting the radix (decimal point) character to be a dot.)
1303 Depending on C<item>, it works on systems that don't have C<nl_langinfo>, hence
1304 makes your code more portable. Of the fifty-some possible items specified by
1305 the POSIX 2008 standard,
1306 L<http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/langinfo.h.html>,
1307 only two are completely unimplemented. It uses various techniques to recover
1308 the other items, including calling C<L<localeconv(3)>>, and C<L<strftime(3)>>,
1309 both of which are specified in C89, so should be always be available. Later
1310 C<strftime()> versions have additional capabilities; C<""> is returned for
1311 those not available on your system.
1313 The details for those items which may differ from what this emulation returns
1314 and what a native C<nl_langinfo()> would return are:
1322 Unimplemented, so returns C<"">.
1332 Only the values for English are returned. C<YESSTR> and C<NOSTR> have been
1333 removed from POSIX 2008, and are retained for backwards compatibility. Your
1334 platform's C<nl_langinfo> may not support them.
1338 Always evaluates to C<%x>, the locale's appropriate date representation.
1342 Always evaluates to C<%X>, the locale's appropriate time representation.
1346 Always evaluates to C<%c>, the locale's appropriate date and time
1351 The return may be incorrect for those rare locales where the currency symbol
1352 replaces the radix character.
1353 Send email to L<mailto:perlbug@perl.org> if you have examples of it needing
1354 to work differently.
1358 Currently this gives the same results as Linux does.
1359 Send email to L<mailto:perlbug@perl.org> if you have examples of it needing
1360 to work differently.
1366 =item C<ERA_D_T_FMT>
1370 These are derived by using C<strftime()>, and not all versions of that function
1371 know about them. C<""> is returned for these on such systems.
1375 When using C<Perl_langinfo> on systems that don't have a native
1376 C<nl_langinfo()>, you must
1378 #include "perl_langinfo.h"
1380 before the C<perl.h> C<#include>. You can replace your C<langinfo.h>
1381 C<#include> with this one. (Doing it this way keeps out the symbols that plain
1382 C<langinfo.h> imports into the namespace for code that doesn't need it.)
1384 You also should not use the bare C<langinfo.h> item names, but should preface
1385 them with C<PERL_>, so use C<PERL_RADIXCHAR> instead of plain C<RADIXCHAR>.
1386 The C<PERL_I<foo>> versions will also work for this function on systems that do
1387 have a native C<nl_langinfo>.
1391 It is thread-friendly, returning its result in a buffer that won't be
1392 overwritten by another thread, so you don't have to code for that possibility.
1393 The buffer can be overwritten by the next call to C<nl_langinfo> or
1394 C<Perl_langinfo> in the same thread.
1398 ª It returns S<C<const char *>>, whereas plain C<nl_langinfo()> returns S<C<char
1399 *>>, but you are (only by documentation) forbidden to write into the buffer.
1400 By declaring this C<const>, the compiler enforces this restriction. The extra
1401 C<const> is why this isn't an unequivocal drop-in replacement for
1406 The original impetus for C<Perl_langinfo()> was so that code that needs to
1407 find out the current currency symbol, floating point radix character, or digit
1408 grouping separator can use, on all systems, the simpler and more
1409 thread-friendly C<nl_langinfo> API instead of C<L<localeconv(3)>> which is a
1410 pain to make thread-friendly. For other fields returned by C<localeconv>, it
1411 is better to use the methods given in L<perlcall> to call
1412 L<C<POSIX::localeconv()>|POSIX/localeconv>, which is thread-friendly.
1419 #ifdef HAS_NL_LANGINFO
1420 Perl_langinfo(const nl_item item)
1422 Perl_langinfo(const int item)
1425 return my_nl_langinfo(item, TRUE);
1429 #ifdef HAS_NL_LANGINFO
1430 S_my_nl_langinfo(const nl_item item, bool toggle)
1432 S_my_nl_langinfo(const int item, bool toggle)
1437 /* We only need to toggle into the underlying LC_NUMERIC locale for these
1438 * two items, and only if not already there */
1439 if (toggle && (( item != PERL_RADIXCHAR && item != PERL_THOUSEP)
1440 || PL_numeric_underlying))
1445 #if defined(HAS_NL_LANGINFO) /* nl_langinfo() is available. */
1446 #if ! defined(HAS_POSIX_2008_LOCALE)
1448 /* Here, use plain nl_langinfo(), switching to the underlying LC_NUMERIC
1449 * for those items dependent on it. This must be copied to a buffer before
1450 * switching back, as some systems destroy the buffer when setlocale() is
1456 DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
1459 STORE_LC_NUMERIC_FORCE_TO_UNDERLYING();
1462 save_to_buffer(nl_langinfo(item), &PL_langinfo_buf,
1463 &PL_langinfo_bufsize, 0);
1466 RESTORE_LC_NUMERIC();
1472 # else /* Use nl_langinfo_l(), avoiding both a mutex and changing the locale */
1475 bool do_free = FALSE;
1476 locale_t cur = uselocale((locale_t) 0);
1478 if (cur == LC_GLOBAL_LOCALE) {
1479 cur = duplocale(LC_GLOBAL_LOCALE);
1484 cur = newlocale(LC_NUMERIC_MASK, PL_numeric_name, cur);
1488 save_to_buffer(nl_langinfo_l(item, cur),
1489 &PL_langinfo_buf, &PL_langinfo_bufsize, 0);
1497 if (strEQ(PL_langinfo_buf, "")) {
1498 if (item == PERL_YESSTR) {
1501 if (item == PERL_NOSTR) {
1506 return PL_langinfo_buf;
1508 #else /* Below, emulate nl_langinfo as best we can */
1512 # ifdef HAS_LOCALECONV
1514 const struct lconv* lc;
1515 DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
1518 # ifdef HAS_STRFTIME
1521 bool return_format = FALSE; /* Return the %format, not the value */
1522 const char * format;
1526 /* We copy the results to a per-thread buffer, even if not
1527 * multi-threaded. This is in part to simplify this code, and partly
1528 * because we need a buffer anyway for strftime(), and partly because a
1529 * call of localeconv() could otherwise wipe out the buffer, and the
1530 * programmer would not be expecting this, as this is a nl_langinfo()
1531 * substitute after all, so s/he might be thinking their localeconv()
1532 * is safe until another localeconv() call. */
1536 const char * retval;
1538 /* These 2 are unimplemented */
1540 case PERL_ERA: /* For use with strftime() %E modifier */
1545 /* We use only an English set, since we don't know any more */
1546 case PERL_YESEXPR: return "^[+1yY]";
1547 case PERL_YESSTR: return "yes";
1548 case PERL_NOEXPR: return "^[-0nN]";
1549 case PERL_NOSTR: return "no";
1551 # ifdef HAS_LOCALECONV
1557 /* We don't bother with localeconv_l() because any system that
1558 * has it is likely to also have nl_langinfo() */
1562 || ! lc->currency_symbol
1563 || strEQ("", lc->currency_symbol))
1569 /* Leave the first spot empty to be filled in below */
1570 save_to_buffer(lc->currency_symbol, &PL_langinfo_buf,
1571 &PL_langinfo_bufsize, 1);
1572 if (lc->mon_decimal_point && strEQ(lc->mon_decimal_point, ""))
1573 { /* khw couldn't figure out how the localedef specifications
1574 would show that the $ should replace the radix; this is
1575 just a guess as to how it might work.*/
1576 *PL_langinfo_buf = '.';
1578 else if (lc->p_cs_precedes) {
1579 *PL_langinfo_buf = '-';
1582 *PL_langinfo_buf = '+';
1588 case PERL_RADIXCHAR:
1594 STORE_LC_NUMERIC_FORCE_TO_UNDERLYING();
1602 retval = (item == PERL_RADIXCHAR)
1604 : lc->thousands_sep;
1610 save_to_buffer(retval, &PL_langinfo_buf,
1611 &PL_langinfo_bufsize, 0);
1614 RESTORE_LC_NUMERIC();
1622 # ifdef HAS_STRFTIME
1624 /* These are defined by C89, so we assume that strftime supports
1625 * them, and so are returned unconditionally; they may not be what
1626 * the locale actually says, but should give good enough results
1627 * for someone using them as formats (as opposed to trying to parse
1628 * them to figure out what the locale says). The other format
1629 * items are actually tested to verify they work on the platform */
1630 case PERL_D_FMT: return "%x";
1631 case PERL_T_FMT: return "%X";
1632 case PERL_D_T_FMT: return "%c";
1634 /* These formats are only available in later strfmtime's */
1635 case PERL_ERA_D_FMT: case PERL_ERA_T_FMT: case PERL_ERA_D_T_FMT:
1636 case PERL_T_FMT_AMPM:
1638 /* The rest can be gotten from most versions of strftime(). */
1639 case PERL_ABDAY_1: case PERL_ABDAY_2: case PERL_ABDAY_3:
1640 case PERL_ABDAY_4: case PERL_ABDAY_5: case PERL_ABDAY_6:
1642 case PERL_ALT_DIGITS:
1643 case PERL_AM_STR: case PERL_PM_STR:
1644 case PERL_ABMON_1: case PERL_ABMON_2: case PERL_ABMON_3:
1645 case PERL_ABMON_4: case PERL_ABMON_5: case PERL_ABMON_6:
1646 case PERL_ABMON_7: case PERL_ABMON_8: case PERL_ABMON_9:
1647 case PERL_ABMON_10: case PERL_ABMON_11: case PERL_ABMON_12:
1648 case PERL_DAY_1: case PERL_DAY_2: case PERL_DAY_3: case PERL_DAY_4:
1649 case PERL_DAY_5: case PERL_DAY_6: case PERL_DAY_7:
1650 case PERL_MON_1: case PERL_MON_2: case PERL_MON_3: case PERL_MON_4:
1651 case PERL_MON_5: case PERL_MON_6: case PERL_MON_7: case PERL_MON_8:
1652 case PERL_MON_9: case PERL_MON_10: case PERL_MON_11:
1657 init_tm(&tm); /* Precaution against core dumps */
1661 tm.tm_year = 2017 - 1900;
1668 "panic: %s: %d: switch case: %d problem",
1669 __FILE__, __LINE__, item);
1670 NOT_REACHED; /* NOTREACHED */
1672 case PERL_PM_STR: tm.tm_hour = 18;
1677 case PERL_ABDAY_7: tm.tm_wday++;
1678 case PERL_ABDAY_6: tm.tm_wday++;
1679 case PERL_ABDAY_5: tm.tm_wday++;
1680 case PERL_ABDAY_4: tm.tm_wday++;
1681 case PERL_ABDAY_3: tm.tm_wday++;
1682 case PERL_ABDAY_2: tm.tm_wday++;
1687 case PERL_DAY_7: tm.tm_wday++;
1688 case PERL_DAY_6: tm.tm_wday++;
1689 case PERL_DAY_5: tm.tm_wday++;
1690 case PERL_DAY_4: tm.tm_wday++;
1691 case PERL_DAY_3: tm.tm_wday++;
1692 case PERL_DAY_2: tm.tm_wday++;
1697 case PERL_ABMON_12: tm.tm_mon++;
1698 case PERL_ABMON_11: tm.tm_mon++;
1699 case PERL_ABMON_10: tm.tm_mon++;
1700 case PERL_ABMON_9: tm.tm_mon++;
1701 case PERL_ABMON_8: tm.tm_mon++;
1702 case PERL_ABMON_7: tm.tm_mon++;
1703 case PERL_ABMON_6: tm.tm_mon++;
1704 case PERL_ABMON_5: tm.tm_mon++;
1705 case PERL_ABMON_4: tm.tm_mon++;
1706 case PERL_ABMON_3: tm.tm_mon++;
1707 case PERL_ABMON_2: tm.tm_mon++;
1712 case PERL_MON_12: tm.tm_mon++;
1713 case PERL_MON_11: tm.tm_mon++;
1714 case PERL_MON_10: tm.tm_mon++;
1715 case PERL_MON_9: tm.tm_mon++;
1716 case PERL_MON_8: tm.tm_mon++;
1717 case PERL_MON_7: tm.tm_mon++;
1718 case PERL_MON_6: tm.tm_mon++;
1719 case PERL_MON_5: tm.tm_mon++;
1720 case PERL_MON_4: tm.tm_mon++;
1721 case PERL_MON_3: tm.tm_mon++;
1722 case PERL_MON_2: tm.tm_mon++;
1727 case PERL_T_FMT_AMPM:
1729 return_format = TRUE;
1732 case PERL_ERA_D_FMT:
1734 return_format = TRUE;
1737 case PERL_ERA_T_FMT:
1739 return_format = TRUE;
1742 case PERL_ERA_D_T_FMT:
1744 return_format = TRUE;
1747 case PERL_ALT_DIGITS:
1749 format = "%Ow"; /* Find the alternate digit for 0 */
1753 /* We can't use my_strftime() because it doesn't look at
1755 while (0 == strftime(PL_langinfo_buf, PL_langinfo_bufsize,
1758 /* A zero return means one of:
1759 * a) there wasn't enough space in PL_langinfo_buf
1760 * b) the format, like a plain %p, returns empty
1761 * c) it was an illegal format, though some
1762 * implementations of strftime will just return the
1763 * illegal format as a plain character sequence.
1765 * To quickly test for case 'b)', try again but precede
1766 * the format with a plain character. If that result is
1767 * still empty, the problem is either 'a)' or 'c)' */
1769 Size_t format_size = strlen(format) + 1;
1770 Size_t mod_size = format_size + 1;
1774 Newx(mod_format, mod_size, char);
1775 Newx(temp_result, PL_langinfo_bufsize, char);
1777 my_strlcpy(mod_format + 1, format, mod_size);
1778 len = strftime(temp_result,
1779 PL_langinfo_bufsize,
1781 Safefree(mod_format);
1782 Safefree(temp_result);
1784 /* If 'len' is non-zero, it means that we had a case like
1785 * %p which means the current locale doesn't use a.m. or
1786 * p.m., and that is valid */
1789 /* Here, still didn't work. If we get well beyond a
1790 * reasonable size, bail out to prevent an infinite
1793 if (PL_langinfo_bufsize > 100 * format_size) {
1794 *PL_langinfo_buf = '\0';
1797 /* Double the buffer size to retry; Add 1 in case
1798 * original was 0, so we aren't stuck at 0. */
1799 PL_langinfo_bufsize *= 2;
1800 PL_langinfo_bufsize++;
1801 Renew(PL_langinfo_buf, PL_langinfo_bufsize, char);
1809 /* Here, we got a result.
1811 * If the item is 'ALT_DIGITS', PL_langinfo_buf contains the
1812 * alternate format for wday 0. If the value is the same as
1813 * the normal 0, there isn't an alternate, so clear the buffer.
1815 if ( item == PERL_ALT_DIGITS
1816 && strEQ(PL_langinfo_buf, "0"))
1818 *PL_langinfo_buf = '\0';
1821 /* ALT_DIGITS is problematic. Experiments on it showed that
1822 * strftime() did not always work properly when going from
1823 * alt-9 to alt-10. Only a few locales have this item defined,
1824 * and in all of them on Linux that khw was able to find,
1825 * nl_langinfo() merely returned the alt-0 character, possibly
1826 * doubled. Most Unicode digits are in blocks of 10
1827 * consecutive code points, so that is sufficient information
1828 * for those scripts, as we can infer alt-1, alt-2, .... But
1829 * for a Japanese locale, a CJK ideographic 0 is returned, and
1830 * the CJK digits are not in code point order, so you can't
1831 * really infer anything. The localedef for this locale did
1832 * specify the succeeding digits, so that strftime() works
1833 * properly on them, without needing to infer anything. But
1834 * the nl_langinfo() return did not give sufficient information
1835 * for the caller to understand what's going on. So until
1836 * there is evidence that it should work differently, this
1837 * returns the alt-0 string for ALT_DIGITS.
1839 * wday was chosen because its range is all a single digit.
1840 * Things like tm_sec have two digits as the minimum: '00' */
1844 /* If to return the format, not the value, overwrite the buffer
1845 * with it. But some strftime()s will keep the original format
1846 * if illegal, so change those to "" */
1847 if (return_format) {
1848 if (strEQ(PL_langinfo_buf, format)) {
1849 *PL_langinfo_buf = '\0';
1852 save_to_buffer(format, &PL_langinfo_buf,
1853 &PL_langinfo_bufsize, 0);
1864 return PL_langinfo_buf;
1871 * Initialize locale awareness.
1874 Perl_init_i18nl10n(pTHX_ int printwarn)
1878 * 0 if not to output warning when setup locale is bad
1879 * 1 if to output warning based on value of PERL_BADLANG
1880 * >1 if to output regardless of PERL_BADLANG
1883 * 1 = set ok or not applicable,
1884 * 0 = fallback to a locale of lower priority
1885 * -1 = fallback to all locales failed, not even to the C locale
1887 * Under -DDEBUGGING, if the environment variable PERL_DEBUG_LOCALE_INIT is
1888 * set, debugging information is output.
1890 * This looks more complicated than it is, mainly due to the #ifdefs.
1892 * We try to set LC_ALL to the value determined by the environment. If
1893 * there is no LC_ALL on this platform, we try the individual categories we
1894 * know about. If this works, we are done.
1896 * But if it doesn't work, we have to do something else. We search the
1897 * environment variables ourselves instead of relying on the system to do
1898 * it. We look at, in order, LC_ALL, LANG, a system default locale (if we
1899 * think there is one), and the ultimate fallback "C". This is all done in
1900 * the same loop as above to avoid duplicating code, but it makes things
1901 * more complex. The 'trial_locales' array is initialized with just one
1902 * element; it causes the behavior described in the paragraph above this to
1903 * happen. If that fails, we add elements to 'trial_locales', and do extra
1904 * loop iterations to cause the behavior described in this paragraph.
1906 * On Ultrix, the locale MUST come from the environment, so there is
1907 * preliminary code to set it. I (khw) am not sure that it is necessary,
1908 * and that this couldn't be folded into the loop, but barring any real
1909 * platforms to test on, it's staying as-is
1911 * A slight complication is that in embedded Perls, the locale may already
1912 * be set-up, and we don't want to get it from the normal environment
1913 * variables. This is handled by having a special environment variable
1914 * indicate we're in this situation. We simply set setlocale's 2nd
1915 * parameter to be a NULL instead of "". That indicates to setlocale that
1916 * it is not to change anything, but to return the current value,
1917 * effectively initializing perl's db to what the locale already is.
1919 * We play the same trick with NULL if a LC_ALL succeeds. We call
1920 * setlocale() on the individual categores with NULL to get their existing
1921 * values for our db, instead of trying to change them.
1928 PERL_UNUSED_ARG(printwarn);
1930 #else /* USE_LOCALE */
1933 const char * const language = savepv(PerlEnv_getenv("LANGUAGE"));
1937 /* NULL uses the existing already set up locale */
1938 const char * const setlocale_init = (PerlEnv_getenv("PERL_SKIP_LOCALE_INIT"))
1941 const char* trial_locales[5]; /* 5 = 1 each for "", LC_ALL, LANG, "", C */
1942 unsigned int trial_locales_count;
1943 const char * const lc_all = savepv(PerlEnv_getenv("LC_ALL"));
1944 const char * const lang = savepv(PerlEnv_getenv("LANG"));
1945 bool setlocale_failure = FALSE;
1948 /* A later getenv() could zap this, so only use here */
1949 const char * const bad_lang_use_once = PerlEnv_getenv("PERL_BADLANG");
1951 const bool locwarn = (printwarn > 1
1953 && ( ! bad_lang_use_once
1955 /* disallow with "" or "0" */
1957 && strNE("0", bad_lang_use_once)))));
1959 /* setlocale() return vals; not copied so must be looked at immediately */
1960 const char * sl_result[NOMINAL_LC_ALL_INDEX + 1];
1962 /* current locale for given category; should have been copied so aren't
1964 const char * curlocales[NOMINAL_LC_ALL_INDEX + 1];
1968 /* In some systems you can find out the system default locale
1969 * and use that as the fallback locale. */
1970 # define SYSTEM_DEFAULT_LOCALE
1972 # ifdef SYSTEM_DEFAULT_LOCALE
1974 const char *system_default_locale = NULL;
1979 # define DEBUG_LOCALE_INIT(a,b,c)
1982 DEBUG_INITIALIZATION_set(cBOOL(PerlEnv_getenv("PERL_DEBUG_LOCALE_INIT")));
1984 # define DEBUG_LOCALE_INIT(category, locale, result) \
1986 if (debug_initialization) { \
1987 PerlIO_printf(Perl_debug_log, \
1989 __FILE__, __LINE__, \
1990 setlocale_debug_string(category, \
1996 /* Make sure the parallel arrays are properly set up */
1997 # ifdef USE_LOCALE_NUMERIC
1998 assert(categories[LC_NUMERIC_INDEX] == LC_NUMERIC);
1999 assert(strEQ(category_names[LC_NUMERIC_INDEX], "LC_NUMERIC"));
2001 # ifdef USE_LOCALE_CTYPE
2002 assert(categories[LC_CTYPE_INDEX] == LC_CTYPE);
2003 assert(strEQ(category_names[LC_CTYPE_INDEX], "LC_CTYPE"));
2005 # ifdef USE_LOCALE_COLLATE
2006 assert(categories[LC_COLLATE_INDEX] == LC_COLLATE);
2007 assert(strEQ(category_names[LC_COLLATE_INDEX], "LC_COLLATE"));
2009 # ifdef USE_LOCALE_TIME
2010 assert(categories[LC_TIME_INDEX] == LC_TIME);
2011 assert(strEQ(category_names[LC_TIME_INDEX], "LC_TIME"));
2013 # ifdef USE_LOCALE_MESSAGES
2014 assert(categories[LC_MESSAGES_INDEX] == LC_MESSAGES);
2015 assert(strEQ(category_names[LC_MESSAGES_INDEX], "LC_MESSAGES"));
2017 # ifdef USE_LOCALE_MONETARY
2018 assert(categories[LC_MONETARY_INDEX] == LC_MONETARY);
2019 assert(strEQ(category_names[LC_MONETARY_INDEX], "LC_MONETARY"));
2021 # ifdef USE_LOCALE_ADDRESS
2022 assert(categories[LC_ADDRESS_INDEX] == LC_ADDRESS);
2023 assert(strEQ(category_names[LC_ADDRESS_INDEX], "LC_ADDRESS"));
2025 # ifdef USE_LOCALE_IDENTIFICATION
2026 assert(categories[LC_IDENTIFICATION_INDEX] == LC_IDENTIFICATION);
2027 assert(strEQ(category_names[LC_IDENTIFICATION_INDEX], "LC_IDENTIFICATION"));
2029 # ifdef USE_LOCALE_MEASUREMENT
2030 assert(categories[LC_MEASUREMENT_INDEX] == LC_MEASUREMENT);
2031 assert(strEQ(category_names[LC_MEASUREMENT_INDEX], "LC_MEASUREMENT"));
2033 # ifdef USE_LOCALE_PAPER
2034 assert(categories[LC_PAPER_INDEX] == LC_PAPER);
2035 assert(strEQ(category_names[LC_PAPER_INDEX], "LC_PAPER"));
2037 # ifdef USE_LOCALE_TELEPHONE
2038 assert(categories[LC_TELEPHONE_INDEX] == LC_TELEPHONE);
2039 assert(strEQ(category_names[LC_TELEPHONE_INDEX], "LC_TELEPHONE"));
2042 assert(categories[LC_ALL_INDEX] == LC_ALL);
2043 assert(strEQ(category_names[LC_ALL_INDEX], "LC_ALL"));
2044 assert(NOMINAL_LC_ALL_INDEX == LC_ALL_INDEX);
2046 # endif /* DEBUGGING */
2048 /* Initialize the cache of the program's UTF-8ness for the always known
2049 * locales C and POSIX */
2050 my_strlcpy(PL_locale_utf8ness, C_and_POSIX_utf8ness,
2051 sizeof(PL_locale_utf8ness));
2053 # ifdef LOCALE_ENVIRON_REQUIRED
2056 * Ultrix setlocale(..., "") fails if there are no environment
2057 * variables from which to get a locale name.
2061 # error Ultrix without LC_ALL not implemented
2067 sl_result[LC_ALL_INDEX] = do_setlocale_c(LC_ALL, setlocale_init);
2068 DEBUG_LOCALE_INIT(LC_ALL, setlocale_init, sl_result[LC_ALL_INDEX]);
2069 if (sl_result[LC_ALL_INDEX])
2072 setlocale_failure = TRUE;
2074 if (! setlocale_failure) {
2075 const char * locale_param;
2076 for (i = 0; i < LC_ALL_INDEX; i++) {
2077 locale_param = (! done && (lang || PerlEnv_getenv(category_names[i])))
2080 sl_result[i] = do_setlocale_r(categories[i], locale_param);
2081 if (! sl_result[i]) {
2082 setlocale_failure = TRUE;
2084 DEBUG_LOCALE_INIT(categories[i], locale_param, sl_result[i]);
2089 # endif /* LC_ALL */
2090 # endif /* LOCALE_ENVIRON_REQUIRED */
2092 /* We try each locale in the list until we get one that works, or exhaust
2093 * the list. Normally the loop is executed just once. But if setting the
2094 * locale fails, inside the loop we add fallback trials to the array and so
2095 * will execute the loop multiple times */
2096 trial_locales[0] = setlocale_init;
2097 trial_locales_count = 1;
2099 for (i= 0; i < trial_locales_count; i++) {
2100 const char * trial_locale = trial_locales[i];
2104 /* XXX This is to preserve old behavior for LOCALE_ENVIRON_REQUIRED
2105 * when i==0, but I (khw) don't think that behavior makes much
2107 setlocale_failure = FALSE;
2109 # ifdef SYSTEM_DEFAULT_LOCALE
2110 # ifdef WIN32 /* Note that assumes Win32 has LC_ALL */
2112 /* On Windows machines, an entry of "" after the 0th means to use
2113 * the system default locale, which we now proceed to get. */
2114 if (strEQ(trial_locale, "")) {
2117 /* Note that this may change the locale, but we are going to do
2118 * that anyway just below */
2119 system_default_locale = do_setlocale_c(LC_ALL, "");
2120 DEBUG_LOCALE_INIT(LC_ALL, "", system_default_locale);
2122 /* Skip if invalid or if it's already on the list of locales to
2124 if (! system_default_locale) {
2125 goto next_iteration;
2127 for (j = 0; j < trial_locales_count; j++) {
2128 if (strEQ(system_default_locale, trial_locales[j])) {
2129 goto next_iteration;
2133 trial_locale = system_default_locale;
2136 # error SYSTEM_DEFAULT_LOCALE only implemented for Win32
2138 # endif /* SYSTEM_DEFAULT_LOCALE */
2144 sl_result[LC_ALL_INDEX] = do_setlocale_c(LC_ALL, trial_locale);
2145 DEBUG_LOCALE_INIT(LC_ALL, trial_locale, sl_result[LC_ALL_INDEX]);
2146 if (! sl_result[LC_ALL_INDEX]) {
2147 setlocale_failure = TRUE;
2150 /* Since LC_ALL succeeded, it should have changed all the other
2151 * categories it can to its value; so we massage things so that the
2152 * setlocales below just return their category's current values.
2153 * This adequately handles the case in NetBSD where LC_COLLATE may
2154 * not be defined for a locale, and setting it individually will
2155 * fail, whereas setting LC_ALL succeeds, leaving LC_COLLATE set to
2156 * the POSIX locale. */
2157 trial_locale = NULL;
2160 # endif /* LC_ALL */
2162 if (! setlocale_failure) {
2164 for (j = 0; j < NOMINAL_LC_ALL_INDEX; j++) {
2166 = savepv(do_setlocale_r(categories[j], trial_locale));
2167 if (! curlocales[j]) {
2168 setlocale_failure = TRUE;
2170 DEBUG_LOCALE_INIT(categories[j], trial_locale, curlocales[j]);
2173 if (! setlocale_failure) { /* All succeeded */
2174 break; /* Exit trial_locales loop */
2178 /* Here, something failed; will need to try a fallback. */
2184 if (locwarn) { /* Output failure info only on the first one */
2188 PerlIO_printf(Perl_error_log,
2189 "perl: warning: Setting locale failed.\n");
2191 # else /* !LC_ALL */
2193 PerlIO_printf(Perl_error_log,
2194 "perl: warning: Setting locale failed for the categories:\n\t");
2196 for (j = 0; j < NOMINAL_LC_ALL_INDEX; j++) {
2197 if (! curlocales[j]) {
2198 PerlIO_printf(Perl_error_log, category_names[j]);
2201 Safefree(curlocales[j]);
2205 # endif /* LC_ALL */
2207 PerlIO_printf(Perl_error_log,
2208 "perl: warning: Please check that your locale settings:\n");
2212 PerlIO_printf(Perl_error_log,
2213 "\tLANGUAGE = %c%s%c,\n",
2214 language ? '"' : '(',
2215 language ? language : "unset",
2216 language ? '"' : ')');
2219 PerlIO_printf(Perl_error_log,
2220 "\tLC_ALL = %c%s%c,\n",
2222 lc_all ? lc_all : "unset",
2223 lc_all ? '"' : ')');
2225 # if defined(USE_ENVIRON_ARRAY)
2230 /* Look through the environment for any variables of the
2231 * form qr/ ^ LC_ [A-Z]+ = /x, except LC_ALL which was
2232 * already handled above. These are assumed to be locale
2233 * settings. Output them and their values. */
2234 for (e = environ; *e; e++) {
2235 const STRLEN prefix_len = sizeof("LC_") - 1;
2238 if ( strBEGINs(*e, "LC_")
2239 && ! strBEGINs(*e, "LC_ALL=")
2240 && (uppers_len = strspn(*e + prefix_len,
2241 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
2242 && ((*e)[prefix_len + uppers_len] == '='))
2244 PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
2245 (int) (prefix_len + uppers_len), *e,
2246 *e + prefix_len + uppers_len + 1);
2253 PerlIO_printf(Perl_error_log,
2254 "\t(possibly more locale environment variables)\n");
2258 PerlIO_printf(Perl_error_log,
2259 "\tLANG = %c%s%c\n",
2261 lang ? lang : "unset",
2264 PerlIO_printf(Perl_error_log,
2265 " are supported and installed on your system.\n");
2268 /* Calculate what fallback locales to try. We have avoided this
2269 * until we have to, because failure is quite unlikely. This will
2270 * usually change the upper bound of the loop we are in.
2272 * Since the system's default way of setting the locale has not
2273 * found one that works, We use Perl's defined ordering: LC_ALL,
2274 * LANG, and the C locale. We don't try the same locale twice, so
2275 * don't add to the list if already there. (On POSIX systems, the
2276 * LC_ALL element will likely be a repeat of the 0th element "",
2277 * but there's no harm done by doing it explicitly.
2279 * Note that this tries the LC_ALL environment variable even on
2280 * systems which have no LC_ALL locale setting. This may or may
2281 * not have been originally intentional, but there's no real need
2282 * to change the behavior. */
2284 for (j = 0; j < trial_locales_count; j++) {
2285 if (strEQ(lc_all, trial_locales[j])) {
2289 trial_locales[trial_locales_count++] = lc_all;
2294 for (j = 0; j < trial_locales_count; j++) {
2295 if (strEQ(lang, trial_locales[j])) {
2299 trial_locales[trial_locales_count++] = lang;
2303 # if defined(WIN32) && defined(LC_ALL)
2305 /* For Windows, we also try the system default locale before "C".
2306 * (If there exists a Windows without LC_ALL we skip this because
2307 * it gets too complicated. For those, the "C" is the next
2308 * fallback possibility). The "" is the same as the 0th element of
2309 * the array, but the code at the loop above knows to treat it
2310 * differently when not the 0th */
2311 trial_locales[trial_locales_count++] = "";
2315 for (j = 0; j < trial_locales_count; j++) {
2316 if (strEQ("C", trial_locales[j])) {
2320 trial_locales[trial_locales_count++] = "C";
2323 } /* end of first time through the loop */
2331 } /* end of looping through the trial locales */
2333 if (ok < 1) { /* If we tried to fallback */
2335 if (! setlocale_failure) { /* fallback succeeded */
2336 msg = "Falling back to";
2338 else { /* fallback failed */
2341 /* We dropped off the end of the loop, so have to decrement i to
2342 * get back to the value the last time through */
2346 msg = "Failed to fall back to";
2348 /* To continue, we should use whatever values we've got */
2350 for (j = 0; j < NOMINAL_LC_ALL_INDEX; j++) {
2351 Safefree(curlocales[j]);
2352 curlocales[j] = savepv(do_setlocale_r(categories[j], NULL));
2353 DEBUG_LOCALE_INIT(categories[j], NULL, curlocales[j]);
2358 const char * description;
2359 const char * name = "";
2360 if (strEQ(trial_locales[i], "C")) {
2361 description = "the standard locale";
2365 # ifdef SYSTEM_DEFAULT_LOCALE
2367 else if (strEQ(trial_locales[i], "")) {
2368 description = "the system default locale";
2369 if (system_default_locale) {
2370 name = system_default_locale;
2374 # endif /* SYSTEM_DEFAULT_LOCALE */
2377 description = "a fallback locale";
2378 name = trial_locales[i];
2380 if (name && strNE(name, "")) {
2381 PerlIO_printf(Perl_error_log,
2382 "perl: warning: %s %s (\"%s\").\n", msg, description, name);
2385 PerlIO_printf(Perl_error_log,
2386 "perl: warning: %s %s.\n", msg, description);
2389 } /* End of tried to fallback */
2391 /* Done with finding the locales; update our records */
2393 # ifdef USE_LOCALE_CTYPE
2395 new_ctype(curlocales[LC_CTYPE_INDEX]);
2398 # ifdef USE_LOCALE_COLLATE
2400 new_collate(curlocales[LC_COLLATE_INDEX]);
2403 # ifdef USE_LOCALE_NUMERIC
2405 new_numeric(curlocales[LC_NUMERIC_INDEX]);
2409 for (i = 0; i < NOMINAL_LC_ALL_INDEX; i++) {
2411 # if defined(USE_ITHREADS)
2413 /* This caches whether each category's locale is UTF-8 or not. This
2414 * may involve changing the locale. It is ok to do this at
2415 * initialization time before any threads have started, but not later.
2416 * Caching means that if the program heeds our dictate not to change
2417 * locales in threaded applications, this data will remain valid, and
2418 * it may get queried without changing locales. If the environment is
2419 * such that all categories have the same locale, this isn't needed, as
2420 * the code will not change the locale; but this handles the uncommon
2421 * case where the environment has disparate locales for the categories
2423 (void) _is_cur_LC_category_utf8(categories[i]);
2427 Safefree(curlocales[i]);
2430 # if defined(USE_PERLIO) && defined(USE_LOCALE_CTYPE)
2432 /* Set PL_utf8locale to TRUE if using PerlIO _and_ the current LC_CTYPE
2433 * locale is UTF-8. The call to new_ctype() just above has already
2434 * calculated the latter value and saved it in PL_in_utf8_CTYPE_locale. If
2435 * both PL_utf8locale and PL_unicode (set by -C or by $ENV{PERL_UNICODE})
2436 * are true, perl.c:S_parse_body() will turn on the PerlIO :utf8 layer on
2437 * STDIN, STDOUT, STDERR, _and_ the default open discipline. */
2438 PL_utf8locale = PL_in_utf8_CTYPE_locale;
2440 /* Set PL_unicode to $ENV{PERL_UNICODE} if using PerlIO.
2441 This is an alternative to using the -C command line switch
2442 (the -C if present will override this). */
2444 const char *p = PerlEnv_getenv("PERL_UNICODE");
2445 PL_unicode = p ? parse_unicode_opts(&p) : 0;
2446 if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
2460 #endif /* USE_LOCALE */
2463 /* So won't continue to output stuff */
2464 DEBUG_INITIALIZATION_set(FALSE);
2471 #ifdef USE_LOCALE_COLLATE
2474 Perl__mem_collxfrm(pTHX_ const char *input_string,
2475 STRLEN len, /* Length of 'input_string' */
2476 STRLEN *xlen, /* Set to length of returned string
2477 (not including the collation index
2479 bool utf8 /* Is the input in UTF-8? */
2483 /* _mem_collxfrm() is a bit like strxfrm() but with two important
2484 * differences. First, it handles embedded NULs. Second, it allocates a bit
2485 * more memory than needed for the transformed data itself. The real
2486 * transformed data begins at offset COLLXFRM_HDR_LEN. *xlen is set to
2487 * the length of that, and doesn't include the collation index size.
2488 * Please see sv_collxfrm() to see how this is used. */
2490 #define COLLXFRM_HDR_LEN sizeof(PL_collation_ix)
2492 char * s = (char *) input_string;
2493 STRLEN s_strlen = strlen(input_string);
2495 STRLEN xAlloc; /* xalloc is a reserved word in VC */
2496 STRLEN length_in_chars;
2497 bool first_time = TRUE; /* Cleared after first loop iteration */
2499 PERL_ARGS_ASSERT__MEM_COLLXFRM;
2501 /* Must be NUL-terminated */
2502 assert(*(input_string + len) == '\0');
2504 /* If this locale has defective collation, skip */
2505 if (PL_collxfrm_base == 0 && PL_collxfrm_mult == 0) {
2506 DEBUG_L(PerlIO_printf(Perl_debug_log,
2507 "_mem_collxfrm: locale's collation is defective\n"));
2511 /* Replace any embedded NULs with the control that sorts before any others.
2512 * This will give as good as possible results on strings that don't
2513 * otherwise contain that character, but otherwise there may be
2514 * less-than-perfect results with that character and NUL. This is
2515 * unavoidable unless we replace strxfrm with our own implementation. */
2516 if (UNLIKELY(s_strlen < len)) { /* Only execute if there is an embedded
2520 STRLEN sans_nuls_len;
2521 int try_non_controls;
2522 char this_replacement_char[] = "?\0"; /* Room for a two-byte string,
2523 making sure 2nd byte is NUL.
2525 STRLEN this_replacement_len;
2527 /* If we don't know what non-NUL control character sorts lowest for
2528 * this locale, find it */
2529 if (PL_strxfrm_NUL_replacement == '\0') {
2531 char * cur_min_x = NULL; /* The min_char's xfrm, (except it also
2532 includes the collation index
2535 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "Looking to replace NUL\n"));
2537 /* Unlikely, but it may be that no control will work to replace
2538 * NUL, in which case we instead look for any character. Controls
2539 * are preferred because collation order is, in general, context
2540 * sensitive, with adjoining characters affecting the order, and
2541 * controls are less likely to have such interactions, allowing the
2542 * NUL-replacement to stand on its own. (Another way to look at it
2543 * is to imagine what would happen if the NUL were replaced by a
2544 * combining character; it wouldn't work out all that well.) */
2545 for (try_non_controls = 0;
2546 try_non_controls < 2;
2549 /* Look through all legal code points (NUL isn't) */
2550 for (j = 1; j < 256; j++) {
2551 char * x; /* j's xfrm plus collation index */
2552 STRLEN x_len; /* length of 'x' */
2553 STRLEN trial_len = 1;
2554 char cur_source[] = { '\0', '\0' };
2556 /* Skip non-controls the first time through the loop. The
2557 * controls in a UTF-8 locale are the L1 ones */
2558 if (! try_non_controls && (PL_in_utf8_COLLATE_locale)
2565 /* Create a 1-char string of the current code point */
2566 cur_source[0] = (char) j;
2568 /* Then transform it */
2569 x = _mem_collxfrm(cur_source, trial_len, &x_len,
2570 0 /* The string is not in UTF-8 */);
2572 /* Ignore any character that didn't successfully transform.
2578 /* If this character's transformation is lower than
2579 * the current lowest, this one becomes the lowest */
2580 if ( cur_min_x == NULL
2581 || strLT(x + COLLXFRM_HDR_LEN,
2582 cur_min_x + COLLXFRM_HDR_LEN))
2584 PL_strxfrm_NUL_replacement = j;
2590 } /* end of loop through all 255 characters */
2592 /* Stop looking if found */
2597 /* Unlikely, but possible, if there aren't any controls that
2598 * work in the locale, repeat the loop, looking for any
2599 * character that works */
2600 DEBUG_L(PerlIO_printf(Perl_debug_log,
2601 "_mem_collxfrm: No control worked. Trying non-controls\n"));
2602 } /* End of loop to try first the controls, then any char */
2605 DEBUG_L(PerlIO_printf(Perl_debug_log,
2606 "_mem_collxfrm: Couldn't find any character to replace"
2607 " embedded NULs in locale %s with", PL_collation_name));
2611 DEBUG_L(PerlIO_printf(Perl_debug_log,
2612 "_mem_collxfrm: Replacing embedded NULs in locale %s with "
2613 "0x%02X\n", PL_collation_name, PL_strxfrm_NUL_replacement));
2615 Safefree(cur_min_x);
2616 } /* End of determining the character that is to replace NULs */
2618 /* If the replacement is variant under UTF-8, it must match the
2619 * UTF8-ness of the original */
2620 if ( ! UVCHR_IS_INVARIANT(PL_strxfrm_NUL_replacement) && utf8) {
2621 this_replacement_char[0] =
2622 UTF8_EIGHT_BIT_HI(PL_strxfrm_NUL_replacement);
2623 this_replacement_char[1] =
2624 UTF8_EIGHT_BIT_LO(PL_strxfrm_NUL_replacement);
2625 this_replacement_len = 2;
2628 this_replacement_char[0] = PL_strxfrm_NUL_replacement;
2629 /* this_replacement_char[1] = '\0' was done at initialization */
2630 this_replacement_len = 1;
2633 /* The worst case length for the replaced string would be if every
2634 * character in it is NUL. Multiply that by the length of each
2635 * replacement, and allow for a trailing NUL */
2636 sans_nuls_len = (len * this_replacement_len) + 1;
2637 Newx(sans_nuls, sans_nuls_len, char);
2640 /* Replace each NUL with the lowest collating control. Loop until have
2641 * exhausted all the NULs */
2642 while (s + s_strlen < e) {
2643 my_strlcat(sans_nuls, s, sans_nuls_len);
2645 /* Do the actual replacement */
2646 my_strlcat(sans_nuls, this_replacement_char, sans_nuls_len);
2648 /* Move past the input NUL */
2650 s_strlen = strlen(s);
2653 /* And add anything that trails the final NUL */
2654 my_strlcat(sans_nuls, s, sans_nuls_len);
2656 /* Switch so below we transform this modified string */
2659 } /* End of replacing NULs */
2661 /* Make sure the UTF8ness of the string and locale match */
2662 if (utf8 != PL_in_utf8_COLLATE_locale) {
2663 const char * const t = s; /* Temporary so we can later find where the
2666 /* Here they don't match. Change the string's to be what the locale is
2669 if (! utf8) { /* locale is UTF-8, but input isn't; upgrade the input */
2670 s = (char *) bytes_to_utf8((const U8 *) s, &len);
2673 else { /* locale is not UTF-8; but input is; downgrade the input */
2675 s = (char *) bytes_from_utf8((const U8 *) s, &len, &utf8);
2677 /* If the downgrade was successful we are done, but if the input
2678 * contains things that require UTF-8 to represent, have to do
2679 * damage control ... */
2680 if (UNLIKELY(utf8)) {
2682 /* What we do is construct a non-UTF-8 string with
2683 * 1) the characters representable by a single byte converted
2684 * to be so (if necessary);
2685 * 2) and the rest converted to collate the same as the
2686 * highest collating representable character. That makes
2687 * them collate at the end. This is similar to how we
2688 * handle embedded NULs, but we use the highest collating
2689 * code point instead of the smallest. Like the NUL case,
2690 * this isn't perfect, but is the best we can reasonably
2691 * do. Every above-255 code point will sort the same as
2692 * the highest-sorting 0-255 code point. If that code
2693 * point can combine in a sequence with some other code
2694 * points for weight calculations, us changing something to
2695 * be it can adversely affect the results. But in most
2696 * cases, it should work reasonably. And note that this is
2697 * really an illegal situation: using code points above 255
2698 * on a locale where only 0-255 are valid. If two strings
2699 * sort entirely equal, then the sort order for the
2700 * above-255 code points will be in code point order. */
2704 /* If we haven't calculated the code point with the maximum
2705 * collating order for this locale, do so now */
2706 if (! PL_strxfrm_max_cp) {
2709 /* The current transformed string that collates the
2710 * highest (except it also includes the prefixed collation
2712 char * cur_max_x = NULL;
2714 /* Look through all legal code points (NUL isn't) */
2715 for (j = 1; j < 256; j++) {
2718 char cur_source[] = { '\0', '\0' };
2720 /* Create a 1-char string of the current code point */
2721 cur_source[0] = (char) j;
2723 /* Then transform it */
2724 x = _mem_collxfrm(cur_source, 1, &x_len, FALSE);
2726 /* If something went wrong (which it shouldn't), just
2727 * ignore this code point */
2732 /* If this character's transformation is higher than
2733 * the current highest, this one becomes the highest */
2734 if ( cur_max_x == NULL
2735 || strGT(x + COLLXFRM_HDR_LEN,
2736 cur_max_x + COLLXFRM_HDR_LEN))
2738 PL_strxfrm_max_cp = j;
2747 DEBUG_L(PerlIO_printf(Perl_debug_log,
2748 "_mem_collxfrm: Couldn't find any character to"
2749 " replace above-Latin1 chars in locale %s with",
2750 PL_collation_name));
2754 DEBUG_L(PerlIO_printf(Perl_debug_log,
2755 "_mem_collxfrm: highest 1-byte collating character"
2756 " in locale %s is 0x%02X\n",
2758 PL_strxfrm_max_cp));
2760 Safefree(cur_max_x);
2763 /* Here we know which legal code point collates the highest.
2764 * We are ready to construct the non-UTF-8 string. The length
2765 * will be at least 1 byte smaller than the input string
2766 * (because we changed at least one 2-byte character into a
2767 * single byte), but that is eaten up by the trailing NUL */
2773 char * e = (char *) t + len;
2775 for (i = 0; i < len; i+= UTF8SKIP(t + i)) {
2777 if (UTF8_IS_INVARIANT(cur_char)) {
2780 else if (UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(t + i, e)) {
2781 s[d++] = EIGHT_BIT_UTF8_TO_NATIVE(cur_char, t[i+1]);
2783 else { /* Replace illegal cp with highest collating
2785 s[d++] = PL_strxfrm_max_cp;
2789 Renew(s, d, char); /* Free up unused space */
2794 /* Here, we have constructed a modified version of the input. It could
2795 * be that we already had a modified copy before we did this version.
2796 * If so, that copy is no longer needed */
2797 if (t != input_string) {
2802 length_in_chars = (utf8)
2803 ? utf8_length((U8 *) s, (U8 *) s + len)
2806 /* The first element in the output is the collation id, used by
2807 * sv_collxfrm(); then comes the space for the transformed string. The
2808 * equation should give us a good estimate as to how much is needed */
2809 xAlloc = COLLXFRM_HDR_LEN
2811 + (PL_collxfrm_mult * length_in_chars);
2812 Newx(xbuf, xAlloc, char);
2813 if (UNLIKELY(! xbuf)) {
2814 DEBUG_L(PerlIO_printf(Perl_debug_log,
2815 "_mem_collxfrm: Couldn't malloc %zu bytes\n", xAlloc));
2819 /* Store the collation id */
2820 *(U32*)xbuf = PL_collation_ix;
2822 /* Then the transformation of the input. We loop until successful, or we
2826 *xlen = strxfrm(xbuf + COLLXFRM_HDR_LEN, s, xAlloc - COLLXFRM_HDR_LEN);
2828 /* If the transformed string occupies less space than we told strxfrm()
2829 * was available, it means it successfully transformed the whole
2831 if (*xlen < xAlloc - COLLXFRM_HDR_LEN) {
2833 /* Some systems include a trailing NUL in the returned length.
2834 * Ignore it, using a loop in case multiple trailing NULs are
2837 && *(xbuf + COLLXFRM_HDR_LEN + (*xlen) - 1) == '\0')
2842 /* If the first try didn't get it, it means our prediction was low.
2843 * Modify the coefficients so that we predict a larger value in any
2844 * future transformations */
2846 STRLEN needed = *xlen + 1; /* +1 For trailing NUL */
2847 STRLEN computed_guess = PL_collxfrm_base
2848 + (PL_collxfrm_mult * length_in_chars);
2850 /* On zero-length input, just keep current slope instead of
2852 const STRLEN new_m = (length_in_chars != 0)
2853 ? needed / length_in_chars
2856 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2857 "%s: %d: initial size of %zu bytes for a length "
2858 "%zu string was insufficient, %zu needed\n",
2860 computed_guess, length_in_chars, needed));
2862 /* If slope increased, use it, but discard this result for
2863 * length 1 strings, as we can't be sure that it's a real slope
2865 if (length_in_chars > 1 && new_m > PL_collxfrm_mult) {
2869 STRLEN old_m = PL_collxfrm_mult;
2870 STRLEN old_b = PL_collxfrm_base;
2874 PL_collxfrm_mult = new_m;
2875 PL_collxfrm_base = 1; /* +1 For trailing NUL */
2876 computed_guess = PL_collxfrm_base
2877 + (PL_collxfrm_mult * length_in_chars);
2878 if (computed_guess < needed) {
2879 PL_collxfrm_base += needed - computed_guess;
2882 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2883 "%s: %d: slope is now %zu; was %zu, base "
2884 "is now %zu; was %zu\n",
2886 PL_collxfrm_mult, old_m,
2887 PL_collxfrm_base, old_b));
2889 else { /* Slope didn't change, but 'b' did */
2890 const STRLEN new_b = needed
2893 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2894 "%s: %d: base is now %zu; was %zu\n",
2896 new_b, PL_collxfrm_base));
2897 PL_collxfrm_base = new_b;
2904 if (UNLIKELY(*xlen >= PERL_INT_MAX)) {
2905 DEBUG_L(PerlIO_printf(Perl_debug_log,
2906 "_mem_collxfrm: Needed %zu bytes, max permissible is %u\n",
2907 *xlen, PERL_INT_MAX));
2911 /* A well-behaved strxfrm() returns exactly how much space it needs
2912 * (usually not including the trailing NUL) when it fails due to not
2913 * enough space being provided. Assume that this is the case unless
2914 * it's been proven otherwise */
2915 if (LIKELY(PL_strxfrm_is_behaved) && first_time) {
2916 xAlloc = *xlen + COLLXFRM_HDR_LEN + 1;
2918 else { /* Here, either:
2919 * 1) The strxfrm() has previously shown bad behavior; or
2920 * 2) It isn't the first time through the loop, which means
2921 * that the strxfrm() is now showing bad behavior, because
2922 * we gave it what it said was needed in the previous
2923 * iteration, and it came back saying it needed still more.
2924 * (Many versions of cygwin fit this. When the buffer size
2925 * isn't sufficient, they return the input size instead of
2926 * how much is needed.)
2927 * Increase the buffer size by a fixed percentage and try again.
2929 xAlloc += (xAlloc / 4) + 1;
2930 PL_strxfrm_is_behaved = FALSE;
2934 if (DEBUG_Lv_TEST || debug_initialization) {
2935 PerlIO_printf(Perl_debug_log,
2936 "_mem_collxfrm required more space than previously calculated"
2937 " for locale %s, trying again with new guess=%d+%zu\n",
2938 PL_collation_name, (int) COLLXFRM_HDR_LEN,
2939 xAlloc - COLLXFRM_HDR_LEN);
2946 Renew(xbuf, xAlloc, char);
2947 if (UNLIKELY(! xbuf)) {
2948 DEBUG_L(PerlIO_printf(Perl_debug_log,
2949 "_mem_collxfrm: Couldn't realloc %zu bytes\n", xAlloc));
2959 if (DEBUG_Lv_TEST || debug_initialization) {
2961 print_collxfrm_input_and_return(s, s + len, xlen, utf8);
2962 PerlIO_printf(Perl_debug_log, "Its xfrm is:");
2963 PerlIO_printf(Perl_debug_log, "%s\n",
2964 _byte_dump_string((U8 *) xbuf + COLLXFRM_HDR_LEN,
2970 /* Free up unneeded space; retain ehough for trailing NUL */
2971 Renew(xbuf, COLLXFRM_HDR_LEN + *xlen + 1, char);
2973 if (s != input_string) {
2981 if (s != input_string) {
2988 if (DEBUG_Lv_TEST || debug_initialization) {
2989 print_collxfrm_input_and_return(s, s + len, NULL, utf8);
3000 S_print_collxfrm_input_and_return(pTHX_
3001 const char * const s,
3002 const char * const e,
3003 const STRLEN * const xlen,
3007 PERL_ARGS_ASSERT_PRINT_COLLXFRM_INPUT_AND_RETURN;
3009 PerlIO_printf(Perl_debug_log, "_mem_collxfrm[%" UVuf "]: returning ",
3010 (UV)PL_collation_ix);
3012 PerlIO_printf(Perl_debug_log, "%zu", *xlen);
3015 PerlIO_printf(Perl_debug_log, "NULL");
3017 PerlIO_printf(Perl_debug_log, " for locale '%s', string='",
3019 print_bytes_for_locale(s, e, is_utf8);
3021 PerlIO_printf(Perl_debug_log, "'\n");
3025 S_print_bytes_for_locale(pTHX_
3026 const char * const s,
3027 const char * const e,
3031 bool prev_was_printable = TRUE;
3032 bool first_time = TRUE;
3034 PERL_ARGS_ASSERT_PRINT_BYTES_FOR_LOCALE;
3038 ? utf8_to_uvchr_buf((U8 *) t, e, NULL)
3041 if (! prev_was_printable) {
3042 PerlIO_printf(Perl_debug_log, " ");
3044 PerlIO_printf(Perl_debug_log, "%c", (U8) cp);
3045 prev_was_printable = TRUE;
3049 PerlIO_printf(Perl_debug_log, " ");
3051 PerlIO_printf(Perl_debug_log, "%02" UVXf, cp);
3052 prev_was_printable = FALSE;
3054 t += (is_utf8) ? UTF8SKIP(t) : 1;
3059 # endif /* #ifdef DEBUGGING */
3060 #endif /* USE_LOCALE_COLLATE */
3065 Perl__is_cur_LC_category_utf8(pTHX_ int category)
3067 /* Returns TRUE if the current locale for 'category' is UTF-8; FALSE
3068 * otherwise. 'category' may not be LC_ALL. If the platform doesn't have
3069 * nl_langinfo(), nor MB_CUR_MAX, this employs a heuristic, which hence
3070 * could give the wrong result. The result will very likely be correct for
3071 * languages that have commonly used non-ASCII characters, but for notably
3072 * English, it comes down to if the locale's name ends in something like
3073 * "UTF-8". It errs on the side of not being a UTF-8 locale. */
3075 /* Name of current locale corresponding to the input category */
3076 const char *save_input_locale = NULL;
3078 bool is_utf8 = FALSE; /* The return value */
3081 /* The variables below are for the cache of previous lookups using this
3082 * function. The cache is a C string, described at the definition for
3083 * 'C_and_POSIX_utf8ness'.
3085 * The first part of the cache is fixed, for the C and POSIX locales. The
3086 * varying part starts just after them. */
3087 char * utf8ness_cache = PL_locale_utf8ness + STRLENs(C_and_POSIX_utf8ness);
3089 Size_t utf8ness_cache_size; /* Size of the varying portion */
3090 Size_t input_name_len; /* Length in bytes of save_input_locale */
3091 Size_t input_name_len_with_overhead; /* plus extra chars used to store
3092 the name in the cache */
3093 char * delimited; /* The name plus the delimiters used to store
3095 char * name_pos; /* position of 'delimited' in the cache, or 0
3101 assert(category != LC_ALL);
3105 /* Get the desired category's locale */
3106 save_input_locale = do_setlocale_r(category, NULL);
3107 if (! save_input_locale) {
3109 "panic: %s: %d: Could not find current locale for %s\n",
3110 __FILE__, __LINE__, category_name(category));
3113 save_input_locale = stdize_locale(savepv(save_input_locale));
3114 DEBUG_L(PerlIO_printf(Perl_debug_log,
3115 "Current locale for %s is %s\n",
3116 category_name(category), save_input_locale));
3118 input_name_len = strlen(save_input_locale);
3120 /* In our cache, each name is accompanied by two delimiters and a single
3122 input_name_len_with_overhead = input_name_len + 3;
3124 /* Allocate and populate space for a copy of the name surrounded by the
3126 Newx(delimited, input_name_len_with_overhead, char);
3127 delimited[0] = UTF8NESS_SEP[0];
3128 Copy(save_input_locale, delimited + 1, input_name_len, char);
3129 delimited[input_name_len+1] = UTF8NESS_PREFIX[0];
3130 delimited[input_name_len+2] = '\0';
3132 /* And see if that is in the cache */
3133 name_pos = instr(PL_locale_utf8ness, delimited);
3135 is_utf8 = *(name_pos + input_name_len_with_overhead - 1) - '0';
3139 if (DEBUG_Lv_TEST || debug_initialization) {
3140 PerlIO_printf(Perl_debug_log, "UTF8ness for locale %s=%d, \n",
3141 save_input_locale, is_utf8);
3146 /* And, if not already in that position, move it to the beginning of
3147 * the non-constant portion of the list, since it is the most recently
3148 * used. (We don't have to worry about overflow, since just moving
3149 * existing names around) */
3150 if (name_pos > utf8ness_cache) {
3151 Move(utf8ness_cache,
3152 utf8ness_cache + input_name_len_with_overhead,
3153 name_pos - utf8ness_cache, char);
3156 input_name_len_with_overhead - 1, char);
3157 utf8ness_cache[input_name_len_with_overhead - 1] = is_utf8 + '0';
3160 Safefree(delimited);
3161 Safefree(save_input_locale);
3165 /* Here we don't have stored the utf8ness for the input locale. We have to
3168 # if defined(USE_LOCALE_CTYPE) \
3169 && (defined(MB_CUR_MAX) || (defined(HAS_NL_LANGINFO) && defined(CODESET)))
3171 { /* Next try nl_langinfo or MB_CUR_MAX if available */
3173 char *save_ctype_locale = NULL;
3175 if (category != LC_CTYPE) { /* These work only on LC_CTYPE */
3177 /* Get the current LC_CTYPE locale */
3178 save_ctype_locale = do_setlocale_c(LC_CTYPE, NULL);
3179 if (! save_ctype_locale) {
3180 DEBUG_L(PerlIO_printf(Perl_debug_log,
3181 "Could not find current locale for LC_CTYPE\n"));
3182 goto cant_use_nllanginfo;
3184 save_ctype_locale = stdize_locale(savepv(save_ctype_locale));
3186 /* If LC_CTYPE and the desired category use the same locale, this
3187 * means that finding the value for LC_CTYPE is the same as finding
3188 * the value for the desired category. Otherwise, switch LC_CTYPE
3189 * to the desired category's locale */
3190 if (strEQ(save_ctype_locale, save_input_locale)) {
3191 Safefree(save_ctype_locale);
3192 save_ctype_locale = NULL;
3194 else if (! do_setlocale_c(LC_CTYPE, save_input_locale)) {
3195 DEBUG_L(PerlIO_printf(Perl_debug_log,
3196 "Could not change LC_CTYPE locale to %s\n",
3197 save_input_locale));
3198 Safefree(save_ctype_locale);
3199 goto cant_use_nllanginfo;
3203 DEBUG_L(PerlIO_printf(Perl_debug_log, "Current LC_CTYPE locale=%s\n",
3204 save_input_locale));
3206 /* Here the current LC_CTYPE is set to the locale of the category whose
3207 * information is desired. This means that nl_langinfo() and MB_CUR_MAX
3208 * should give the correct results */
3210 # if defined(HAS_NL_LANGINFO) && defined(CODESET)
3212 { /* The task is easiest if the platform has this POSIX 2001 function */
3213 const char *codeset = my_nl_langinfo(PERL_CODESET, FALSE);
3214 /* FALSE => already in dest locale */
3216 DEBUG_L(PerlIO_printf(Perl_debug_log,
3217 "\tnllanginfo returned CODESET '%s'\n", codeset));
3219 if (codeset && strNE(codeset, "")) {
3220 /* If we switched LC_CTYPE, switch back */
3221 if (save_ctype_locale) {
3222 do_setlocale_c(LC_CTYPE, save_ctype_locale);
3223 Safefree(save_ctype_locale);
3226 /* If the implementation of foldEQ() somehow were
3227 * to change to not go byte-by-byte, this could
3228 * read past end of string, as only one length is
3229 * checked. But currently, a premature NUL will
3230 * compare false, and it will stop there */
3231 is_utf8 = cBOOL( foldEQ(codeset, STR_WITH_LEN("UTF-8"))
3232 || foldEQ(codeset, STR_WITH_LEN("UTF8")));
3234 DEBUG_L(PerlIO_printf(Perl_debug_log,
3235 "\tnllanginfo returned CODESET '%s'; ?UTF8 locale=%d\n",
3237 goto finish_and_return;
3244 /* Here, either we don't have nl_langinfo, or it didn't return a
3245 * codeset. Try MB_CUR_MAX */
3247 /* Standard UTF-8 needs at least 4 bytes to represent the maximum
3248 * Unicode code point. Since UTF-8 is the only non-single byte
3249 * encoding we handle, we just say any such encoding is UTF-8, and if
3250 * turns out to be wrong, other things will fail */
3251 is_utf8 = (unsigned) MB_CUR_MAX >= STRLENs(MAX_UNICODE_UTF8);
3253 DEBUG_L(PerlIO_printf(Perl_debug_log,
3254 "\tMB_CUR_MAX=%d; ?UTF8 locale=%d\n",
3255 (int) MB_CUR_MAX, is_utf8));
3257 Safefree(save_input_locale);
3261 /* ... But, most system that have MB_CUR_MAX will also have mbtowc(),
3262 * since they are both in the C99 standard. We can feed a known byte
3263 * string to the latter function, and check that it gives the expected
3269 PERL_UNUSED_RESULT(mbtowc(&wc, NULL, 0));/* Reset any shift state */
3271 len = mbtowc(&wc, STR_WITH_LEN(REPLACEMENT_CHARACTER_UTF8));
3274 if ( len != STRLENs(REPLACEMENT_CHARACTER_UTF8)
3275 || wc != (wchar_t) UNICODE_REPLACEMENT)
3278 DEBUG_L(PerlIO_printf(Perl_debug_log, "\replacement=U+%x\n",
3280 DEBUG_L(PerlIO_printf(Perl_debug_log,
3281 "\treturn from mbtowc=%d; errno=%d; ?UTF8 locale=0\n",
3288 /* If we switched LC_CTYPE, switch back */
3289 if (save_ctype_locale) {
3290 do_setlocale_c(LC_CTYPE, save_ctype_locale);
3291 Safefree(save_ctype_locale);
3294 goto finish_and_return;
3300 cant_use_nllanginfo:
3302 # else /* nl_langinfo should work if available, so don't bother compiling this
3303 fallback code. The final fallback of looking at the name is
3304 compiled, and will be executed if nl_langinfo fails */
3306 /* nl_langinfo not available or failed somehow. Next try looking at the
3307 * currency symbol to see if it disambiguates things. Often that will be
3308 * in the native script, and if the symbol isn't in UTF-8, we know that the
3309 * locale isn't. If it is non-ASCII UTF-8, we infer that the locale is
3310 * too, as the odds of a non-UTF8 string being valid UTF-8 are quite small
3313 # ifdef HAS_LOCALECONV
3314 # ifdef USE_LOCALE_MONETARY
3317 char *save_monetary_locale = NULL;
3318 bool only_ascii = FALSE;
3321 /* Like above for LC_CTYPE, we first set LC_MONETARY to the locale of
3322 * the desired category, if it isn't that locale already */
3324 if (category != LC_MONETARY) {
3326 save_monetary_locale = do_setlocale_c(LC_MONETARY, NULL);
3327 if (! save_monetary_locale) {
3328 DEBUG_L(PerlIO_printf(Perl_debug_log,
3329 "Could not find current locale for LC_MONETARY\n"));
3330 goto cant_use_monetary;
3332 save_monetary_locale = stdize_locale(savepv(save_monetary_locale));
3334 if (strEQ(save_monetary_locale, save_input_locale)) {
3335 Safefree(save_monetary_locale);
3336 save_monetary_locale = NULL;
3338 else if (! do_setlocale_c(LC_MONETARY, save_input_locale)) {
3339 DEBUG_L(PerlIO_printf(Perl_debug_log,
3340 "Could not change LC_MONETARY locale to %s\n",
3341 save_input_locale));
3342 Safefree(save_monetary_locale);
3343 goto cant_use_monetary;
3347 /* Here the current LC_MONETARY is set to the locale of the category
3348 * whose information is desired. */
3352 || ! lc->currency_symbol
3353 || is_utf8_invariant_string((U8 *) lc->currency_symbol, 0))
3355 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));
3359 is_utf8 = is_utf8_string((U8 *) lc->currency_symbol, 0);
3362 /* If we changed it, restore LC_MONETARY to its original locale */
3363 if (save_monetary_locale) {
3364 do_setlocale_c(LC_MONETARY, save_monetary_locale);
3365 Safefree(save_monetary_locale);
3370 /* It isn't a UTF-8 locale if the symbol is not legal UTF-8;
3371 * otherwise assume the locale is UTF-8 if and only if the symbol
3372 * is non-ascii UTF-8. */
3373 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?Currency symbol for %s is UTF-8=%d\n",
3374 save_input_locale, is_utf8));
3375 goto finish_and_return;
3380 # endif /* USE_LOCALE_MONETARY */
3381 # endif /* HAS_LOCALECONV */
3383 # if defined(HAS_STRFTIME) && defined(USE_LOCALE_TIME)
3385 /* Still haven't found a non-ASCII string to disambiguate UTF-8 or not. Try
3386 * the names of the months and weekdays, timezone, and am/pm indicator */
3388 char *save_time_locale = NULL;
3390 bool is_dst = FALSE;
3394 char * formatted_time;
3397 /* Like above for LC_MONETARY, we set LC_TIME to the locale of the
3398 * desired category, if it isn't that locale already */
3400 if (category != LC_TIME) {
3402 save_time_locale = do_setlocale_c(LC_TIME, NULL);
3403 if (! save_time_locale) {
3404 DEBUG_L(PerlIO_printf(Perl_debug_log,
3405 "Could not find current locale for LC_TIME\n"));
3408 save_time_locale = stdize_locale(savepv(save_time_locale));
3410 if (strEQ(save_time_locale, save_input_locale)) {
3411 Safefree(save_time_locale);
3412 save_time_locale = NULL;
3414 else if (! do_setlocale_c(LC_TIME, save_input_locale)) {
3415 DEBUG_L(PerlIO_printf(Perl_debug_log,
3416 "Could not change LC_TIME locale to %s\n",
3417 save_input_locale));
3418 Safefree(save_time_locale);
3423 /* Here the current LC_TIME is set to the locale of the category
3424 * whose information is desired. Look at all the days of the week and
3425 * month names, and the timezone and am/pm indicator for UTF-8 variant
3426 * characters. The first such a one found will tell us if the locale
3427 * is UTF-8 or not */
3429 for (i = 0; i < 7 + 12; i++) { /* 7 days; 12 months */
3430 formatted_time = my_strftime("%A %B %Z %p",
3431 0, 0, hour, dom, month, 2012 - 1900, 0, 0, is_dst);
3432 if ( ! formatted_time
3433 || is_utf8_invariant_string((U8 *) formatted_time, 0))
3436 /* Here, we didn't find a non-ASCII. Try the next time through
3437 * with the complemented dst and am/pm, and try with the next
3438 * weekday. After we have gotten all weekdays, try the next
3441 hour = (hour + 12) % 24;
3449 /* Here, we have a non-ASCII. Return TRUE is it is valid UTF8;
3450 * false otherwise. But first, restore LC_TIME to its original
3451 * locale if we changed it */
3452 if (save_time_locale) {
3453 do_setlocale_c(LC_TIME, save_time_locale);
3454 Safefree(save_time_locale);
3457 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?time-related strings for %s are UTF-8=%d\n",
3459 is_utf8_string((U8 *) formatted_time, 0)));
3460 is_utf8 = is_utf8_string((U8 *) formatted_time, 0);
3461 goto finish_and_return;
3464 /* Falling off the end of the loop indicates all the names were just
3465 * ASCII. Go on to the next test. If we changed it, restore LC_TIME
3466 * to its original locale */
3467 if (save_time_locale) {
3468 do_setlocale_c(LC_TIME, save_time_locale);
3469 Safefree(save_time_locale);
3471 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));
3477 # if 0 && defined(USE_LOCALE_MESSAGES) && defined(HAS_SYS_ERRLIST)
3479 /* This code is ifdefd out because it was found to not be necessary in testing
3480 * on our dromedary test machine, which has over 700 locales. There, this
3481 * added no value to looking at the currency symbol and the time strings. I
3482 * left it in so as to avoid rewriting it if real-world experience indicates
3483 * that dromedary is an outlier. Essentially, instead of returning abpve if we
3484 * haven't found illegal utf8, we continue on and examine all the strerror()
3485 * messages on the platform for utf8ness. If all are ASCII, we still don't
3486 * know the answer; but otherwise we have a pretty good indication of the
3487 * utf8ness. The reason this doesn't help much is that the messages may not
3488 * have been translated into the locale. The currency symbol and time strings
3489 * are much more likely to have been translated. */
3492 bool non_ascii = FALSE;
3493 char *save_messages_locale = NULL;
3494 const char * errmsg = NULL;
3496 /* Like above, we set LC_MESSAGES to the locale of the desired
3497 * category, if it isn't that locale already */
3499 if (category != LC_MESSAGES) {
3501 save_messages_locale = do_setlocale_c(LC_MESSAGES, NULL);
3502 if (! save_messages_locale) {
3503 DEBUG_L(PerlIO_printf(Perl_debug_log,
3504 "Could not find current locale for LC_MESSAGES\n"));
3505 goto cant_use_messages;
3507 save_messages_locale = stdize_locale(savepv(save_messages_locale));
3509 if (strEQ(save_messages_locale, save_input_locale)) {
3510 Safefree(save_messages_locale);
3511 save_messages_locale = NULL;
3513 else if (! do_setlocale_c(LC_MESSAGES, save_input_locale)) {
3514 DEBUG_L(PerlIO_printf(Perl_debug_log,
3515 "Could not change LC_MESSAGES locale to %s\n",
3516 save_input_locale));
3517 Safefree(save_messages_locale);
3518 goto cant_use_messages;
3522 /* Here the current LC_MESSAGES is set to the locale of the category
3523 * whose information is desired. Look through all the messages. We
3524 * can't use Strerror() here because it may expand to code that
3525 * segfaults in miniperl */
3527 for (e = 0; e <= sys_nerr; e++) {
3529 errmsg = sys_errlist[e];
3530 if (errno || !errmsg) {
3533 errmsg = savepv(errmsg);
3534 if (! is_utf8_invariant_string((U8 *) errmsg, 0)) {
3536 is_utf8 = is_utf8_string((U8 *) errmsg, 0);
3542 /* And, if we changed it, restore LC_MESSAGES to its original locale */
3543 if (save_messages_locale) {
3544 do_setlocale_c(LC_MESSAGES, save_messages_locale);
3545 Safefree(save_messages_locale);
3550 /* Any non-UTF-8 message means not a UTF-8 locale; if all are valid,
3551 * any non-ascii means it is one; otherwise we assume it isn't */
3552 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?error messages for %s are UTF-8=%d\n",
3555 goto finish_and_return;
3558 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));
3563 # endif /* the code that is compiled when no nl_langinfo */
3565 # ifndef EBCDIC /* On os390, even if the name ends with "UTF-8', it isn't a
3568 /* As a last resort, look at the locale name to see if it matches
3569 * qr/UTF -? * 8 /ix, or some other common locale names. This "name", the
3570 * return of setlocale(), is actually defined to be opaque, so we can't
3571 * really rely on the absence of various substrings in the name to indicate
3572 * its UTF-8ness, but if it has UTF8 in the name, it is extremely likely to
3573 * be a UTF-8 locale. Similarly for the other common names */
3575 final_pos = strlen(save_input_locale) - 1;
3576 if (final_pos >= 3) {
3577 const char *name = save_input_locale;
3579 /* Find next 'U' or 'u' and look from there */
3580 while ((name += strcspn(name, "Uu") + 1)
3581 <= save_input_locale + final_pos - 2)
3583 if ( isALPHA_FOLD_NE(*name, 't')
3584 || isALPHA_FOLD_NE(*(name + 1), 'f'))
3589 if (*(name) == '-') {
3590 if ((name > save_input_locale + final_pos - 1)) {
3595 if (*(name) == '8') {
3596 DEBUG_L(PerlIO_printf(Perl_debug_log,
3597 "Locale %s ends with UTF-8 in name\n",
3598 save_input_locale));
3600 goto finish_and_return;
3603 DEBUG_L(PerlIO_printf(Perl_debug_log,
3604 "Locale %s doesn't end with UTF-8 in name\n",
3605 save_input_locale));
3610 /* http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756.aspx */
3611 if (memENDs(save_input_locale, final_pos, "65001")) {
3612 DEBUG_L(PerlIO_printf(Perl_debug_log,
3613 "Locale %s ends with 65001 in name, is UTF-8 locale\n",
3614 save_input_locale));
3616 goto finish_and_return;
3622 /* Other common encodings are the ISO 8859 series, which aren't UTF-8. But
3623 * since we are about to return FALSE anyway, there is no point in doing
3624 * this extra work */
3627 if (instr(save_input_locale, "8859")) {
3628 DEBUG_L(PerlIO_printf(Perl_debug_log,
3629 "Locale %s has 8859 in name, not UTF-8 locale\n",
3630 save_input_locale));
3632 goto finish_and_return;
3636 DEBUG_L(PerlIO_printf(Perl_debug_log,
3637 "Assuming locale %s is not a UTF-8 locale\n",
3638 save_input_locale));
3643 /* Cache this result so we don't have to go through all this next time. */
3644 utf8ness_cache_size = sizeof(PL_locale_utf8ness)
3645 - (utf8ness_cache - PL_locale_utf8ness);
3647 /* But we can't save it if it is too large for the total space available */
3648 if (LIKELY(input_name_len_with_overhead < utf8ness_cache_size)) {
3649 Size_t utf8ness_cache_len = strlen(utf8ness_cache);
3651 /* Here it can fit, but we may need to clear out the oldest cached
3652 * result(s) to do so. Check */
3653 if (utf8ness_cache_len + input_name_len_with_overhead
3654 >= utf8ness_cache_size)
3656 /* Here we have to clear something out to make room for this.
3657 * Start looking at the rightmost place where it could fit and find
3658 * the beginning of the entry that extends past that. */
3659 char * cutoff = (char *) my_memrchr(utf8ness_cache,
3662 - input_name_len_with_overhead);
3665 assert(cutoff >= utf8ness_cache);
3667 /* This and all subsequent entries must be removed */
3669 utf8ness_cache_len = strlen(utf8ness_cache);
3672 /* Make space for the new entry */
3673 Move(utf8ness_cache,
3674 utf8ness_cache + input_name_len_with_overhead,
3675 utf8ness_cache_len + 1 /* Incl. trailing NUL */, char);
3678 Copy(delimited, utf8ness_cache, input_name_len_with_overhead - 1, char);
3679 utf8ness_cache[input_name_len_with_overhead - 1] = is_utf8 + '0';
3681 if ((PL_locale_utf8ness[strlen(PL_locale_utf8ness)-1]
3682 & (PERL_UINTMAX_T) ~1) != '0')
3685 "panic: %s: %d: Corrupt utf8ness_cache=%s\nlen=%u,"
3686 " inserted_name=%s, its_len=%u\n",
3688 PL_locale_utf8ness, strlen(PL_locale_utf8ness),
3689 delimited, input_name_len_with_overhead);
3695 if (DEBUG_Lv_TEST || debug_initialization) {
3696 PerlIO_printf(Perl_debug_log,
3697 "PL_locale_utf8ness is now %s; returning %d\n",
3698 PL_locale_utf8ness, is_utf8);
3703 Safefree(delimited);
3704 Safefree(save_input_locale);
3712 Perl__is_in_locale_category(pTHX_ const bool compiling, const int category)
3715 /* Internal function which returns if we are in the scope of a pragma that
3716 * enables the locale category 'category'. 'compiling' should indicate if
3717 * this is during the compilation phase (TRUE) or not (FALSE). */
3719 const COP * const cop = (compiling) ? &PL_compiling : PL_curcop;
3721 SV *categories = cop_hints_fetch_pvs(cop, "locale", 0);
3722 if (! categories || categories == &PL_sv_placeholder) {
3726 /* The pseudo-category 'not_characters' is -1, so just add 1 to each to get
3727 * a valid unsigned */
3728 assert(category >= -1);
3729 return cBOOL(SvUV(categories) & (1U << (category + 1)));
3733 Perl_my_strerror(pTHX_ const int errnum)
3735 /* Returns a mortalized copy of the text of the error message associated
3736 * with 'errnum'. It uses the current locale's text unless the platform
3737 * doesn't have the LC_MESSAGES category or we are not being called from
3738 * within the scope of 'use locale'. In the former case, it uses whatever
3739 * strerror returns; in the latter case it uses the text from the C locale.
3741 * The function just calls strerror(), but temporarily switches, if needed,
3742 * to the C locale */
3747 #ifndef USE_LOCALE_MESSAGES
3749 /* If platform doesn't have messages category, we don't do any switching to
3750 * the C locale; we just use whatever strerror() returns */
3752 errstr = savepv(Strerror(errnum));
3754 #else /* Has locale messages */
3756 const bool within_locale_scope = IN_LC(LC_MESSAGES);
3758 # if defined(HAS_POSIX_2008_LOCALE) && defined(HAS_STRERROR_L)
3760 /* This function is trivial if we don't have to worry about thread safety
3761 * and have strerror_l(), as it handles the switch of locales so we don't
3762 * have to deal with that. We don't have to worry about thread safety if
3763 * this is an unthreaded build, or if strerror_r() is also available. Both
3764 * it and strerror_l() are thread-safe. Plain strerror() isn't thread
3765 * safe. But on threaded builds when strerror_r() is available, the
3766 * apparent call to strerror() below is actually a macro that
3767 * behind-the-scenes calls strerror_r().
3770 # if ! defined(USE_ITHREADS) || defined(HAS_STRERROR_R)
3772 if (within_locale_scope) {
3773 errstr = savepv(strerror(errnum));
3776 errstr = savepv(strerror_l(errnum, PL_C_locale_obj));
3781 /* Here we have strerror_l(), but not strerror_r() and we are on a
3782 * threaded-build. We use strerror_l() for everything, constructing a
3783 * locale to pass to it if necessary */
3785 bool do_free = FALSE;
3786 locale_t locale_to_use;
3788 if (within_locale_scope) {
3789 locale_to_use = uselocale((locale_t) 0);
3790 if (locale_to_use == LC_GLOBAL_LOCALE) {
3791 locale_to_use = duplocale(LC_GLOBAL_LOCALE);
3795 else { /* Use C locale if not within 'use locale' scope */
3796 locale_to_use = PL_C_locale_obj;
3799 errstr = savepv(strerror_l(errnum, locale_to_use));
3802 freelocale(locale_to_use);
3806 # else /* Doesn't have strerror_l() */
3808 # ifdef USE_POSIX_2008_LOCALE
3810 locale_t save_locale = NULL;
3814 const char * save_locale = NULL;
3815 bool locale_is_C = FALSE;
3817 /* We have a critical section to prevent another thread from changing the
3818 * locale out from under us (or zapping the buffer returned from
3824 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3825 "my_strerror called with errnum %d\n", errnum));
3826 if (! within_locale_scope) {
3829 # ifdef USE_POSIX_2008_LOCALE /* Use the thread-safe locale functions */
3831 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3832 "Not within locale scope, about to call"
3833 " uselocale(0x%p)\n", PL_C_locale_obj));
3834 save_locale = uselocale(PL_C_locale_obj);
3835 if (! save_locale) {
3836 DEBUG_L(PerlIO_printf(Perl_debug_log,
3837 "uselocale failed, errno=%d\n", errno));
3840 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3841 "uselocale returned 0x%p\n", save_locale));
3844 # else /* Not thread-safe build */
3846 save_locale = do_setlocale_c(LC_MESSAGES, NULL);
3847 if (! save_locale) {
3848 DEBUG_L(PerlIO_printf(Perl_debug_log,
3849 "setlocale failed, errno=%d\n", errno));
3852 locale_is_C = isNAME_C_OR_POSIX(save_locale);
3854 /* Switch to the C locale if not already in it */
3855 if (! locale_is_C) {
3857 /* The setlocale() just below likely will zap 'save_locale', so
3859 save_locale = savepv(save_locale);
3860 do_setlocale_c(LC_MESSAGES, "C");
3866 } /* end of ! within_locale_scope */
3868 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s: %d: WITHIN locale scope\n",
3869 __FILE__, __LINE__));
3872 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3873 "Any locale change has been done; about to call Strerror\n"));
3874 errstr = savepv(Strerror(errnum));
3876 if (! within_locale_scope) {
3879 # ifdef USE_POSIX_2008_LOCALE
3881 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3882 "%s: %d: not within locale scope, restoring the locale\n",
3883 __FILE__, __LINE__));
3884 if (save_locale && ! uselocale(save_locale)) {
3885 DEBUG_L(PerlIO_printf(Perl_debug_log,
3886 "uselocale restore failed, errno=%d\n", errno));
3892 if (save_locale && ! locale_is_C) {
3893 if (! do_setlocale_c(LC_MESSAGES, save_locale)) {
3894 DEBUG_L(PerlIO_printf(Perl_debug_log,
3895 "setlocale restore failed, errno=%d\n", errno));
3897 Safefree(save_locale);
3904 # endif /* End of doesn't have strerror_l */
3905 #endif /* End of does have locale messages */
3909 if (DEBUG_Lv_TEST) {
3910 PerlIO_printf(Perl_debug_log, "Strerror returned; saving a copy: '");
3911 print_bytes_for_locale(errstr, errstr + strlen(errstr), 0);
3912 PerlIO_printf(Perl_debug_log, "'\n");
3923 =for apidoc sync_locale
3925 Changing the program's locale should be avoided by XS code. Nevertheless,
3926 certain non-Perl libraries called from XS, such as C<Gtk> do so. When this
3927 happens, Perl needs to be told that the locale has changed. Use this function
3928 to do so, before returning to Perl.
3934 Perl_sync_locale(pTHX)
3938 #ifdef USE_LOCALE_CTYPE
3940 newlocale = do_setlocale_c(LC_CTYPE, NULL);
3941 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3942 "%s:%d: %s\n", __FILE__, __LINE__,
3943 setlocale_debug_string(LC_CTYPE, NULL, newlocale)));
3944 new_ctype(newlocale);
3946 #endif /* USE_LOCALE_CTYPE */
3947 #ifdef USE_LOCALE_COLLATE
3949 newlocale = do_setlocale_c(LC_COLLATE, NULL);
3950 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3951 "%s:%d: %s\n", __FILE__, __LINE__,
3952 setlocale_debug_string(LC_COLLATE, NULL, newlocale)));
3953 new_collate(newlocale);
3956 #ifdef USE_LOCALE_NUMERIC
3958 newlocale = do_setlocale_c(LC_NUMERIC, NULL);
3959 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3960 "%s:%d: %s\n", __FILE__, __LINE__,
3961 setlocale_debug_string(LC_NUMERIC, NULL, newlocale)));
3962 new_numeric(newlocale);
3964 #endif /* USE_LOCALE_NUMERIC */
3968 #if defined(DEBUGGING) && defined(USE_LOCALE)
3971 S_setlocale_debug_string(const int category, /* category number,
3973 const char* const locale, /* locale name */
3975 /* return value from setlocale() when attempting to
3976 * set 'category' to 'locale' */
3977 const char* const retval)
3979 /* Returns a pointer to a NUL-terminated string in static storage with
3980 * added text about the info passed in. This is not thread safe and will
3981 * be overwritten by the next call, so this should be used just to
3982 * formulate a string to immediately print or savepv() on. */
3984 /* initialise to a non-null value to keep it out of BSS and so keep
3985 * -DPERL_GLOBAL_STRUCT_PRIVATE happy */
3986 static char ret[128] = "If you can read this, thank your buggy C"
3987 " library strlcpy(), and change your hints file"
3990 my_strlcpy(ret, "setlocale(", sizeof(ret));
3991 my_strlcat(ret, category_name(category), sizeof(ret));
3992 my_strlcat(ret, ", ", sizeof(ret));
3995 my_strlcat(ret, "\"", sizeof(ret));
3996 my_strlcat(ret, locale, sizeof(ret));
3997 my_strlcat(ret, "\"", sizeof(ret));
4000 my_strlcat(ret, "NULL", sizeof(ret));
4003 my_strlcat(ret, ") returned ", sizeof(ret));
4006 my_strlcat(ret, "\"", sizeof(ret));
4007 my_strlcat(ret, retval, sizeof(ret));
4008 my_strlcat(ret, "\"", sizeof(ret));
4011 my_strlcat(ret, "NULL", sizeof(ret));
4014 assert(strlen(ret) < sizeof(ret));
4023 * ex: set ts=8 sts=4 sw=4 et: