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"
48 /* If the environment says to, we can output debugging information during
49 * initialization. This is done before option parsing, and before any thread
50 * creation, so can be a file-level static */
51 #if ! defined(DEBUGGING) || defined(PERL_GLOBAL_STRUCT)
52 # define debug_initialization 0
53 # define DEBUG_INITIALIZATION_set(v)
55 static bool debug_initialization = FALSE;
56 # define DEBUG_INITIALIZATION_set(v) (debug_initialization = v)
60 /* Returns the Unix errno portion; ignoring any others. This is a macro here
61 * instead of putting it into perl.h, because unclear to khw what should be
63 #define GET_ERRNO saved_errno
65 /* strlen() of a literal string constant. We might want this more general,
66 * but using it in just this file for now. A problem with more generality is
67 * the compiler warnings about comparing unlike signs */
68 #define STRLENs(s) (sizeof("" s "") - 1)
70 /* Is the C string input 'name' "C" or "POSIX"? If so, and 'name' is the
71 * return of setlocale(), then this is extremely likely to be the C or POSIX
72 * locale. However, the output of setlocale() is documented to be opaque, but
73 * the odds are extremely small that it would return these two strings for some
74 * other locale. Note that VMS in these two locales includes many non-ASCII
75 * characters as controls and punctuation (below are hex bytes):
77 * punct: A1-A3 A5 A7-AB B0-B3 B5-B7 B9-BD BF-CF D1-DD DF-EF F1-FD
78 * Oddly, none there are listed as alphas, though some represent alphabetics
79 * http://www.nntp.perl.org/group/perl.perl5.porters/2013/02/msg198753.html */
80 #define isNAME_C_OR_POSIX(name) \
82 && (( *(name) == 'C' && (*(name + 1)) == '\0') \
83 || strEQ((name), "POSIX")))
87 /* This code keeps a LRU cache of the UTF-8ness of the locales it has so-far
88 * looked up. This is in the form of a C string: */
90 #define UTF8NESS_SEP "\v"
91 #define UTF8NESS_PREFIX "\f"
93 /* So, the string looks like:
95 * \vC\a0\vPOSIX\a0\vam_ET\a0\vaf_ZA.utf8\a1\ven_US.UTF-8\a1\0
97 * where the digit 0 after the \a indicates that the locale starting just
98 * after the preceding \v is not UTF-8, and the digit 1 mean it is. */
100 STATIC_ASSERT_DECL(STRLENs(UTF8NESS_SEP) == 1);
101 STATIC_ASSERT_DECL(STRLENs(UTF8NESS_PREFIX) == 1);
103 #define C_and_POSIX_utf8ness UTF8NESS_SEP "C" UTF8NESS_PREFIX "0" \
104 UTF8NESS_SEP "POSIX" UTF8NESS_PREFIX "0"
106 /* The cache is initialized to C_and_POSIX_utf8ness at start up. These are
107 * kept there always. The remining portion of the cache is LRU, with the
108 * oldest looked-up locale at the tail end */
111 S_stdize_locale(pTHX_ char *locs)
113 /* Standardize the locale name from a string returned by 'setlocale',
114 * possibly modifying that string.
116 * The typical return value of setlocale() is either
117 * (1) "xx_YY" if the first argument of setlocale() is not LC_ALL
118 * (2) "xa_YY xb_YY ..." if the first argument of setlocale() is LC_ALL
119 * (the space-separated values represent the various sublocales,
120 * in some unspecified order). This is not handled by this function.
122 * In some platforms it has a form like "LC_SOMETHING=Lang_Country.866\n",
123 * which is harmful for further use of the string in setlocale(). This
124 * function removes the trailing new line and everything up through the '='
127 const char * const s = strchr(locs, '=');
130 PERL_ARGS_ASSERT_STDIZE_LOCALE;
133 const char * const t = strchr(s, '.');
136 const char * const u = strchr(t, '\n');
137 if (u && (u[1] == 0)) {
138 const STRLEN len = u - s;
139 Move(s + 1, locs, len, char);
147 Perl_croak(aTHX_ "Can't fix broken locale name \"%s\"", locs);
152 /* Two parallel arrays; first the locale categories Perl uses on this system;
153 * the second array is their names. These arrays are in mostly arbitrary
156 const int categories[] = {
158 # ifdef USE_LOCALE_NUMERIC
161 # ifdef USE_LOCALE_CTYPE
164 # ifdef USE_LOCALE_COLLATE
167 # ifdef USE_LOCALE_TIME
170 # ifdef USE_LOCALE_MESSAGES
173 # ifdef USE_LOCALE_MONETARY
176 # ifdef USE_LOCALE_ADDRESS
179 # ifdef USE_LOCALE_IDENTIFICATION
182 # ifdef USE_LOCALE_MEASUREMENT
185 # ifdef USE_LOCALE_PAPER
188 # ifdef USE_LOCALE_TELEPHONE
194 -1 /* Placeholder because C doesn't allow a
195 trailing comma, and it would get complicated
196 with all the #ifdef's */
199 /* The top-most real element is LC_ALL */
201 const char * category_names[] = {
203 # ifdef USE_LOCALE_NUMERIC
206 # ifdef USE_LOCALE_CTYPE
209 # ifdef USE_LOCALE_COLLATE
212 # ifdef USE_LOCALE_TIME
215 # ifdef USE_LOCALE_MESSAGES
218 # ifdef USE_LOCALE_MONETARY
221 # ifdef USE_LOCALE_ADDRESS
224 # ifdef USE_LOCALE_IDENTIFICATION
227 # ifdef USE_LOCALE_MEASUREMENT
230 # ifdef USE_LOCALE_PAPER
233 # ifdef USE_LOCALE_TELEPHONE
239 NULL /* Placeholder */
244 /* On systems with LC_ALL, it is kept in the highest index position. (-2
245 * to account for the final unused placeholder element.) */
246 # define NOMINAL_LC_ALL_INDEX (C_ARRAY_LENGTH(categories) - 2)
250 /* On systems without LC_ALL, we pretend it is there, one beyond the real
251 * top element, hence in the unused placeholder element. */
252 # define NOMINAL_LC_ALL_INDEX (C_ARRAY_LENGTH(categories) - 1)
256 /* Pretending there is an LC_ALL element just above allows us to avoid most
257 * special cases. Most loops through these arrays in the code below are
258 * written like 'for (i = 0; i < NOMINAL_LC_ALL_INDEX; i++)'. They will work
259 * on either type of system. But the code must be written to not access the
260 * element at 'LC_ALL_INDEX' except on platforms that have it. This can be
261 * checked for at compile time by using the #define LC_ALL_INDEX which is only
262 * defined if we do have LC_ALL. */
265 S_category_name(const int category)
271 if (category == LC_ALL) {
277 for (i = 0; i < NOMINAL_LC_ALL_INDEX; i++) {
278 if (category == categories[i]) {
279 return category_names[i];
284 const char suffix[] = " (unknown)";
286 Size_t length = sizeof(suffix) + 1;
295 /* Calculate the number of digits */
301 Newx(unknown, length, char);
302 my_snprintf(unknown, length, "%d%s", category, suffix);
308 /* Now create LC_foo_INDEX #defines for just those categories on this system */
309 # ifdef USE_LOCALE_NUMERIC
310 # define LC_NUMERIC_INDEX 0
311 # define _DUMMY_NUMERIC LC_NUMERIC_INDEX
313 # define _DUMMY_NUMERIC -1
315 # ifdef USE_LOCALE_CTYPE
316 # define LC_CTYPE_INDEX _DUMMY_NUMERIC + 1
317 # define _DUMMY_CTYPE LC_CTYPE_INDEX
319 # define _DUMMY_CTYPE _DUMMY_NUMERIC
321 # ifdef USE_LOCALE_COLLATE
322 # define LC_COLLATE_INDEX _DUMMY_CTYPE + 1
323 # define _DUMMY_COLLATE LC_COLLATE_INDEX
325 # define _DUMMY_COLLATE _DUMMY_COLLATE
327 # ifdef USE_LOCALE_TIME
328 # define LC_TIME_INDEX _DUMMY_COLLATE + 1
329 # define _DUMMY_TIME LC_TIME_INDEX
331 # define _DUMMY_TIME _DUMMY_COLLATE
333 # ifdef USE_LOCALE_MESSAGES
334 # define LC_MESSAGES_INDEX _DUMMY_TIME + 1
335 # define _DUMMY_MESSAGES LC_MESSAGES_INDEX
337 # define _DUMMY_MESSAGES _DUMMY_TIME
339 # ifdef USE_LOCALE_MONETARY
340 # define LC_MONETARY_INDEX _DUMMY_MESSAGES + 1
341 # define _DUMMY_MONETARY LC_MONETARY_INDEX
343 # define _DUMMY_MONETARY _DUMMY_MESSAGES
345 # ifdef USE_LOCALE_ADDRESS
346 # define LC_ADDRESS_INDEX _DUMMY_MONETARY + 1
347 # define _DUMMY_ADDRESS LC_ADDRESS_INDEX
349 # define _DUMMY_ADDRESS _DUMMY_MONETARY
351 # ifdef USE_LOCALE_IDENTIFICATION
352 # define LC_IDENTIFICATION_INDEX _DUMMY_ADDRESS + 1
353 # define _DUMMY_IDENTIFICATION LC_IDENTIFICATION_INDEX
355 # define _DUMMY_IDENTIFICATION _DUMMY_ADDRESS
357 # ifdef USE_LOCALE_MEASUREMENT
358 # define LC_MEASUREMENT_INDEX _DUMMY_IDENTIFICATION + 1
359 # define _DUMMY_MEASUREMENT LC_MEASUREMENT_INDEX
361 # define _DUMMY_MEASUREMENT _DUMMY_IDENTIFICATION
363 # ifdef USE_LOCALE_PAPER
364 # define LC_PAPER_INDEX _DUMMY_MEASUREMENT + 1
365 # define _DUMMY_PAPER LC_PAPER_INDEX
367 # define _DUMMY_PAPER _DUMMY_MEASUREMENT
369 # ifdef USE_LOCALE_TELEPHONE
370 # define LC_TELEPHONE_INDEX _DUMMY_PAPER + 1
371 # define _DUMMY_TELEPHONE LC_TELEPHONE_INDEX
373 # define _DUMMY_TELEPHONE _DUMMY_PAPER
376 # define LC_ALL_INDEX _DUMMY_TELEPHONE + 1
378 #endif /* ifdef USE_LOCALE */
380 /* Windows requres a customized base-level setlocale() */
382 # define my_setlocale(cat, locale) win32_setlocale(cat, locale)
384 # define my_setlocale(cat, locale) setlocale(cat, locale)
387 /* Just placeholders for now. "_c" is intended to be called when the category
388 * is a constant known at compile time; "_r", not known until run time */
389 # define do_setlocale_c(category, locale) my_setlocale(category, locale)
390 # define do_setlocale_r(category, locale) my_setlocale(category, locale)
393 S_set_numeric_radix(pTHX_ const bool use_locale)
395 /* If 'use_locale' is FALSE, set to use a dot for the radix character. If
396 * TRUE, use the radix character derived from the current locale */
398 #if defined(USE_LOCALE_NUMERIC) && ( defined(HAS_LOCALECONV) \
399 || defined(HAS_NL_LANGINFO))
401 const char * radix = (use_locale)
402 ? my_nl_langinfo(PERL_RADIXCHAR, FALSE)
403 /* FALSE => already in dest locale */
406 sv_setpv(PL_numeric_radix_sv, radix);
408 /* If this is valid UTF-8 that isn't totally ASCII, and we are in
409 * a UTF-8 locale, then mark the radix as being in UTF-8 */
410 if (is_utf8_non_invariant_string((U8 *) SvPVX(PL_numeric_radix_sv),
411 SvCUR(PL_numeric_radix_sv))
412 && _is_cur_LC_category_utf8(LC_NUMERIC))
414 SvUTF8_on(PL_numeric_radix_sv);
419 if (DEBUG_L_TEST || debug_initialization) {
420 PerlIO_printf(Perl_debug_log, "Locale radix is '%s', ?UTF-8=%d\n",
421 SvPVX(PL_numeric_radix_sv),
422 cBOOL(SvUTF8(PL_numeric_radix_sv)));
426 #endif /* USE_LOCALE_NUMERIC and can find the radix char */
432 Perl_new_numeric(pTHX_ const char *newnum)
435 #ifndef USE_LOCALE_NUMERIC
437 PERL_UNUSED_ARG(newnum);
441 /* Called after each libc setlocale() call affecting LC_NUMERIC, to tell
442 * core Perl this and that 'newnum' is the name of the new locale.
443 * It installs this locale as the current underlying default.
445 * The default locale and the C locale can be toggled between by use of the
446 * set_numeric_underlying() and set_numeric_standard() functions, which
447 * should probably not be called directly, but only via macros like
448 * SET_NUMERIC_STANDARD() in perl.h.
450 * The toggling is necessary mainly so that a non-dot radix decimal point
451 * character can be output, while allowing internal calculations to use a
454 * This sets several interpreter-level variables:
455 * PL_numeric_name The underlying locale's name: a copy of 'newnum'
456 * PL_numeric_underlying A boolean indicating if the toggled state is such
457 * that the current locale is the program's underlying
459 * PL_numeric_standard An int indicating if the toggled state is such
460 * that the current locale is the C locale or
461 * indistinguishable from the C locale. If non-zero, it
462 * is in C; if > 1, it means it may not be toggled away
464 * PL_numeric_underlying_is_standard A bool kept by this function
465 * indicating that the underlying locale and the standard
466 * C locale are indistinguishable for the purposes of
467 * LC_NUMERIC. This happens when both of the above two
468 * variables are true at the same time. (Toggling is a
469 * no-op under these circumstances.) This variable is
470 * used to avoid having to recalculate.
471 * Any code changing the locale (outside this file) should use
472 * POSIX::setlocale, which calls this function. Therefore this function
473 * should be called directly only from this file and from
474 * POSIX::setlocale() */
479 Safefree(PL_numeric_name);
480 PL_numeric_name = NULL;
481 PL_numeric_standard = TRUE;
482 PL_numeric_underlying = TRUE;
483 PL_numeric_underlying_is_standard = TRUE;
487 save_newnum = stdize_locale(savepv(newnum));
488 PL_numeric_underlying = TRUE;
489 PL_numeric_standard = isNAME_C_OR_POSIX(save_newnum);
491 /* If its name isn't C nor POSIX, it could still be indistinguishable from
493 if (! PL_numeric_standard) {
494 PL_numeric_standard = cBOOL(strEQ(".", my_nl_langinfo(PERL_RADIXCHAR,
495 FALSE /* Don't toggle locale */ ))
496 && strEQ("", my_nl_langinfo(PERL_THOUSEP,
500 /* Save the new name if it isn't the same as the previous one, if any */
501 if (! PL_numeric_name || strNE(PL_numeric_name, save_newnum)) {
502 Safefree(PL_numeric_name);
503 PL_numeric_name = save_newnum;
506 Safefree(save_newnum);
509 PL_numeric_underlying_is_standard = PL_numeric_standard;
511 # ifdef HAS_POSIX_2008_LOCALE
513 PL_underlying_numeric_obj = newlocale(LC_NUMERIC_MASK,
515 PL_underlying_numeric_obj);
519 if (DEBUG_L_TEST || debug_initialization) {
520 PerlIO_printf(Perl_debug_log, "Called new_numeric with %s, PL_numeric_name=%s\n", newnum, PL_numeric_name);
523 /* Keep LC_NUMERIC in the C locale. This is for XS modules, so they don't
524 * have to worry about the radix being a non-dot. (Core operations that
525 * need the underlying locale change to it temporarily). */
526 set_numeric_standard();
528 #endif /* USE_LOCALE_NUMERIC */
533 Perl_set_numeric_standard(pTHX)
536 #ifdef USE_LOCALE_NUMERIC
538 /* Toggle the LC_NUMERIC locale to C. Most code should use the macros like
539 * SET_NUMERIC_STANDARD() in perl.h instead of calling this directly. The
540 * macro avoids calling this routine if toggling isn't necessary according
541 * to our records (which could be wrong if some XS code has changed the
542 * locale behind our back) */
544 do_setlocale_c(LC_NUMERIC, "C");
545 PL_numeric_standard = TRUE;
546 PL_numeric_underlying = PL_numeric_underlying_is_standard;
547 set_numeric_radix(0);
551 if (DEBUG_L_TEST || debug_initialization) {
552 PerlIO_printf(Perl_debug_log,
553 "LC_NUMERIC locale now is standard C\n");
557 #endif /* USE_LOCALE_NUMERIC */
562 Perl_set_numeric_underlying(pTHX)
565 #ifdef USE_LOCALE_NUMERIC
567 /* Toggle the LC_NUMERIC locale to the current underlying default. Most
568 * code should use the macros like SET_NUMERIC_UNDERLYING() in perl.h
569 * instead of calling this directly. The macro avoids calling this routine
570 * if toggling isn't necessary according to our records (which could be
571 * wrong if some XS code has changed the locale behind our back) */
573 do_setlocale_c(LC_NUMERIC, PL_numeric_name);
574 PL_numeric_standard = PL_numeric_underlying_is_standard;
575 PL_numeric_underlying = TRUE;
576 set_numeric_radix(! PL_numeric_standard);
580 if (DEBUG_L_TEST || debug_initialization) {
581 PerlIO_printf(Perl_debug_log,
582 "LC_NUMERIC locale now is %s\n",
587 #endif /* USE_LOCALE_NUMERIC */
592 * Set up for a new ctype locale.
595 S_new_ctype(pTHX_ const char *newctype)
598 #ifndef USE_LOCALE_CTYPE
600 PERL_ARGS_ASSERT_NEW_CTYPE;
601 PERL_UNUSED_ARG(newctype);
606 /* Called after each libc setlocale() call affecting LC_CTYPE, to tell
607 * core Perl this and that 'newctype' is the name of the new locale.
609 * This function sets up the folding arrays for all 256 bytes, assuming
610 * that tofold() is tolc() since fold case is not a concept in POSIX,
612 * Any code changing the locale (outside this file) should use
613 * POSIX::setlocale, which calls this function. Therefore this function
614 * should be called directly only from this file and from
615 * POSIX::setlocale() */
620 /* Don't check for problems if we are suppressing the warnings */
621 bool check_for_problems = ckWARN_d(WARN_LOCALE) || UNLIKELY(DEBUG_L_TEST);
623 PERL_ARGS_ASSERT_NEW_CTYPE;
625 /* We will replace any bad locale warning with 1) nothing if the new one is
626 * ok; or 2) a new warning for the bad new locale */
627 if (PL_warn_locale) {
628 SvREFCNT_dec_NN(PL_warn_locale);
629 PL_warn_locale = NULL;
632 PL_in_utf8_CTYPE_locale = _is_cur_LC_category_utf8(LC_CTYPE);
634 /* A UTF-8 locale gets standard rules. But note that code still has to
635 * handle this specially because of the three problematic code points */
636 if (PL_in_utf8_CTYPE_locale) {
637 Copy(PL_fold_latin1, PL_fold_locale, 256, U8);
640 /* We don't populate the other lists if a UTF-8 locale, but do check that
641 * everything works as expected, unless checking turned off */
642 if (check_for_problems || ! PL_in_utf8_CTYPE_locale) {
643 /* Assume enough space for every character being bad. 4 spaces each
644 * for the 94 printable characters that are output like "'x' "; and 5
645 * spaces each for "'\\' ", "'\t' ", and "'\n' "; plus a terminating
647 char bad_chars_list[ (94 * 4) + (3 * 5) + 1 ] = { '\0' };
648 bool multi_byte_locale = FALSE; /* Assume is a single-byte locale
650 unsigned int bad_count = 0; /* Count of bad characters */
652 for (i = 0; i < 256; i++) {
653 if (! PL_in_utf8_CTYPE_locale) {
655 PL_fold_locale[i] = (U8) tolower(i);
657 PL_fold_locale[i] = (U8) toupper(i);
659 PL_fold_locale[i] = (U8) i;
662 /* If checking for locale problems, see if the native ASCII-range
663 * printables plus \n and \t are in their expected categories in
664 * the new locale. If not, this could mean big trouble, upending
665 * Perl's and most programs' assumptions, like having a
666 * metacharacter with special meaning become a \w. Fortunately,
667 * it's very rare to find locales that aren't supersets of ASCII
668 * nowadays. It isn't a problem for most controls to be changed
669 * into something else; we check only \n and \t, though perhaps \r
670 * could be an issue as well. */
671 if ( check_for_problems
672 && (isGRAPH_A(i) || isBLANK_A(i) || i == '\n'))
675 char name[3] = { '\0' };
677 /* Convert the name into a string */
682 else if (i == '\n') {
683 my_strlcpy(name, "\n", sizeof(name));
686 my_strlcpy(name, "\t", sizeof(name));
689 /* Check each possibe class */
690 if (UNLIKELY(cBOOL(isalnum(i)) != cBOOL(isALPHANUMERIC_A(i)))) {
692 DEBUG_L(PerlIO_printf(Perl_debug_log,
693 "isalnum('%s') unexpectedly is %d\n",
694 name, cBOOL(isalnum(i))));
696 if (UNLIKELY(cBOOL(isalpha(i)) != cBOOL(isALPHA_A(i)))) {
698 DEBUG_L(PerlIO_printf(Perl_debug_log,
699 "isalpha('%s') unexpectedly is %d\n",
700 name, cBOOL(isalpha(i))));
702 if (UNLIKELY(cBOOL(isdigit(i)) != cBOOL(isDIGIT_A(i)))) {
704 DEBUG_L(PerlIO_printf(Perl_debug_log,
705 "isdigit('%s') unexpectedly is %d\n",
706 name, cBOOL(isdigit(i))));
708 if (UNLIKELY(cBOOL(isgraph(i)) != cBOOL(isGRAPH_A(i)))) {
710 DEBUG_L(PerlIO_printf(Perl_debug_log,
711 "isgraph('%s') unexpectedly is %d\n",
712 name, cBOOL(isgraph(i))));
714 if (UNLIKELY(cBOOL(islower(i)) != cBOOL(isLOWER_A(i)))) {
716 DEBUG_L(PerlIO_printf(Perl_debug_log,
717 "islower('%s') unexpectedly is %d\n",
718 name, cBOOL(islower(i))));
720 if (UNLIKELY(cBOOL(isprint(i)) != cBOOL(isPRINT_A(i)))) {
722 DEBUG_L(PerlIO_printf(Perl_debug_log,
723 "isprint('%s') unexpectedly is %d\n",
724 name, cBOOL(isprint(i))));
726 if (UNLIKELY(cBOOL(ispunct(i)) != cBOOL(isPUNCT_A(i)))) {
728 DEBUG_L(PerlIO_printf(Perl_debug_log,
729 "ispunct('%s') unexpectedly is %d\n",
730 name, cBOOL(ispunct(i))));
732 if (UNLIKELY(cBOOL(isspace(i)) != cBOOL(isSPACE_A(i)))) {
734 DEBUG_L(PerlIO_printf(Perl_debug_log,
735 "isspace('%s') unexpectedly is %d\n",
736 name, cBOOL(isspace(i))));
738 if (UNLIKELY(cBOOL(isupper(i)) != cBOOL(isUPPER_A(i)))) {
740 DEBUG_L(PerlIO_printf(Perl_debug_log,
741 "isupper('%s') unexpectedly is %d\n",
742 name, cBOOL(isupper(i))));
744 if (UNLIKELY(cBOOL(isxdigit(i))!= cBOOL(isXDIGIT_A(i)))) {
746 DEBUG_L(PerlIO_printf(Perl_debug_log,
747 "isxdigit('%s') unexpectedly is %d\n",
748 name, cBOOL(isxdigit(i))));
750 if (UNLIKELY(tolower(i) != (int) toLOWER_A(i))) {
752 DEBUG_L(PerlIO_printf(Perl_debug_log,
753 "tolower('%s')=0x%x instead of the expected 0x%x\n",
754 name, tolower(i), (int) toLOWER_A(i)));
756 if (UNLIKELY(toupper(i) != (int) toUPPER_A(i))) {
758 DEBUG_L(PerlIO_printf(Perl_debug_log,
759 "toupper('%s')=0x%x instead of the expected 0x%x\n",
760 name, toupper(i), (int) toUPPER_A(i)));
762 if (UNLIKELY((i == '\n' && ! isCNTRL_LC(i)))) {
764 DEBUG_L(PerlIO_printf(Perl_debug_log,
765 "'\\n' (=%02X) is not a control\n", (int) i));
768 /* Add to the list; Separate multiple entries with a blank */
771 my_strlcat(bad_chars_list, " ", sizeof(bad_chars_list));
773 my_strlcat(bad_chars_list, name, sizeof(bad_chars_list));
781 /* We only handle single-byte locales (outside of UTF-8 ones; so if
782 * this locale requires more than one byte, there are going to be
784 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
785 "%s:%d: check_for_problems=%d, MB_CUR_MAX=%d\n",
786 __FILE__, __LINE__, check_for_problems, (int) MB_CUR_MAX));
788 if ( check_for_problems && MB_CUR_MAX > 1
789 && ! PL_in_utf8_CTYPE_locale
791 /* Some platforms return MB_CUR_MAX > 1 for even the "C"
792 * locale. Just assume that the implementation for them (plus
793 * for POSIX) is correct and the > 1 value is spurious. (Since
794 * these are specially handled to never be considered UTF-8
795 * locales, as long as this is the only problem, everything
796 * should work fine */
797 && strNE(newctype, "C") && strNE(newctype, "POSIX"))
799 multi_byte_locale = TRUE;
804 if (UNLIKELY(bad_count) || UNLIKELY(multi_byte_locale)) {
805 if (UNLIKELY(bad_count) && PL_in_utf8_CTYPE_locale) {
806 PL_warn_locale = Perl_newSVpvf(aTHX_
807 "Locale '%s' contains (at least) the following characters"
808 " which have\nnon-standard meanings: %s\nThe Perl program"
809 " will use the standard meanings",
810 newctype, bad_chars_list);
814 PL_warn_locale = Perl_newSVpvf(aTHX_
815 "Locale '%s' may not work well.%s%s%s\n",
818 ? " Some characters in it are not recognized by"
822 ? "\nThe following characters (and maybe others)"
823 " may not have the same meaning as the Perl"
824 " program expects:\n"
832 # ifdef HAS_NL_LANGINFO
834 Perl_sv_catpvf(aTHX_ PL_warn_locale, "; codeset=%s",
835 /* parameter FALSE is a don't care here */
836 my_nl_langinfo(PERL_CODESET, FALSE));
840 Perl_sv_catpvf(aTHX_ PL_warn_locale, "\n");
842 /* If we are actually in the scope of the locale or are debugging,
843 * output the message now. If not in that scope, we save the
844 * message to be output at the first operation using this locale,
845 * if that actually happens. Most programs don't use locales, so
846 * they are immune to bad ones. */
847 if (IN_LC(LC_CTYPE) || UNLIKELY(DEBUG_L_TEST)) {
849 /* The '0' below suppresses a bogus gcc compiler warning */
850 Perl_warner(aTHX_ packWARN(WARN_LOCALE), SvPVX(PL_warn_locale), 0);
852 if (IN_LC(LC_CTYPE)) {
853 SvREFCNT_dec_NN(PL_warn_locale);
854 PL_warn_locale = NULL;
860 #endif /* USE_LOCALE_CTYPE */
865 Perl__warn_problematic_locale()
868 #ifdef USE_LOCALE_CTYPE
872 /* Internal-to-core function that outputs the message in PL_warn_locale,
873 * and then NULLS it. Should be called only through the macro
874 * _CHECK_AND_WARN_PROBLEMATIC_LOCALE */
876 if (PL_warn_locale) {
877 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
878 SvPVX(PL_warn_locale),
879 0 /* dummy to avoid compiler warning */ );
880 SvREFCNT_dec_NN(PL_warn_locale);
881 PL_warn_locale = NULL;
889 S_new_collate(pTHX_ const char *newcoll)
892 #ifndef USE_LOCALE_COLLATE
894 PERL_UNUSED_ARG(newcoll);
899 /* Called after each libc setlocale() call affecting LC_COLLATE, to tell
900 * core Perl this and that 'newcoll' is the name of the new locale.
902 * The design of locale collation is that every locale change is given an
903 * index 'PL_collation_ix'. The first time a string particpates in an
904 * operation that requires collation while locale collation is active, it
905 * is given PERL_MAGIC_collxfrm magic (via sv_collxfrm_flags()). That
906 * magic includes the collation index, and the transformation of the string
907 * by strxfrm(), q.v. That transformation is used when doing comparisons,
908 * instead of the string itself. If a string changes, the magic is
909 * cleared. The next time the locale changes, the index is incremented,
910 * and so we know during a comparison that the transformation is not
911 * necessarily still valid, and so is recomputed. Note that if the locale
912 * changes enough times, the index could wrap (a U32), and it is possible
913 * that a transformation would improperly be considered valid, leading to
917 if (PL_collation_name) {
919 Safefree(PL_collation_name);
920 PL_collation_name = NULL;
922 PL_collation_standard = TRUE;
923 is_standard_collation:
924 PL_collxfrm_base = 0;
925 PL_collxfrm_mult = 2;
926 PL_in_utf8_COLLATE_locale = FALSE;
927 PL_strxfrm_NUL_replacement = '\0';
928 PL_strxfrm_max_cp = 0;
932 /* If this is not the same locale as currently, set the new one up */
933 if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
935 Safefree(PL_collation_name);
936 PL_collation_name = stdize_locale(savepv(newcoll));
937 PL_collation_standard = isNAME_C_OR_POSIX(newcoll);
938 if (PL_collation_standard) {
939 goto is_standard_collation;
942 PL_in_utf8_COLLATE_locale = _is_cur_LC_category_utf8(LC_COLLATE);
943 PL_strxfrm_NUL_replacement = '\0';
944 PL_strxfrm_max_cp = 0;
946 /* A locale collation definition includes primary, secondary, tertiary,
947 * etc. weights for each character. To sort, the primary weights are
948 * used, and only if they compare equal, then the secondary weights are
949 * used, and only if they compare equal, then the tertiary, etc.
951 * strxfrm() works by taking the input string, say ABC, and creating an
952 * output transformed string consisting of first the primary weights,
953 * A¹B¹C¹ followed by the secondary ones, A²B²C²; and then the
954 * tertiary, etc, yielding A¹B¹C¹ A²B²C² A³B³C³ .... Some characters
955 * may not have weights at every level. In our example, let's say B
956 * doesn't have a tertiary weight, and A doesn't have a secondary
957 * weight. The constructed string is then going to be
958 * A¹B¹C¹ B²C² A³C³ ....
959 * This has the desired effect that strcmp() will look at the secondary
960 * or tertiary weights only if the strings compare equal at all higher
961 * priority weights. The spaces shown here, like in
963 * are not just for readability. In the general case, these must
964 * actually be bytes, which we will call here 'separator weights'; and
965 * they must be smaller than any other weight value, but since these
966 * are C strings, only the terminating one can be a NUL (some
967 * implementations may include a non-NUL separator weight just before
968 * the NUL). Implementations tend to reserve 01 for the separator
969 * weights. They are needed so that a shorter string's secondary
970 * weights won't be misconstrued as primary weights of a longer string,
971 * etc. By making them smaller than any other weight, the shorter
972 * string will sort first. (Actually, if all secondary weights are
973 * smaller than all primary ones, there is no need for a separator
974 * weight between those two levels, etc.)
976 * The length of the transformed string is roughly a linear function of
977 * the input string. It's not exactly linear because some characters
978 * don't have weights at all levels. When we call strxfrm() we have to
979 * allocate some memory to hold the transformed string. The
980 * calculations below try to find coefficients 'm' and 'b' for this
981 * locale so that m*x + b equals how much space we need, given the size
982 * of the input string in 'x'. If we calculate too small, we increase
983 * the size as needed, and call strxfrm() again, but it is better to
984 * get it right the first time to avoid wasted expensive string
985 * transformations. */
988 /* We use the string below to find how long the tranformation of it
989 * is. Almost all locales are supersets of ASCII, or at least the
990 * ASCII letters. We use all of them, half upper half lower,
991 * because if we used fewer, we might hit just the ones that are
992 * outliers in a particular locale. Most of the strings being
993 * collated will contain a preponderance of letters, and even if
994 * they are above-ASCII, they are likely to have the same number of
995 * weight levels as the ASCII ones. It turns out that digits tend
996 * to have fewer levels, and some punctuation has more, but those
997 * are relatively sparse in text, and khw believes this gives a
998 * reasonable result, but it could be changed if experience so
1000 const char longer[] = "ABCDEFGHIJKLMnopqrstuvwxyz";
1001 char * x_longer; /* Transformed 'longer' */
1002 Size_t x_len_longer; /* Length of 'x_longer' */
1004 char * x_shorter; /* We also transform a substring of 'longer' */
1005 Size_t x_len_shorter;
1007 /* _mem_collxfrm() is used get the transformation (though here we
1008 * are interested only in its length). It is used because it has
1009 * the intelligence to handle all cases, but to work, it needs some
1010 * values of 'm' and 'b' to get it started. For the purposes of
1011 * this calculation we use a very conservative estimate of 'm' and
1012 * 'b'. This assumes a weight can be multiple bytes, enough to
1013 * hold any UV on the platform, and there are 5 levels, 4 weight
1014 * bytes, and a trailing NUL. */
1015 PL_collxfrm_base = 5;
1016 PL_collxfrm_mult = 5 * sizeof(UV);
1018 /* Find out how long the transformation really is */
1019 x_longer = _mem_collxfrm(longer,
1023 /* We avoid converting to UTF-8 in the
1024 * called function by telling it the
1025 * string is in UTF-8 if the locale is a
1026 * UTF-8 one. Since the string passed
1027 * here is invariant under UTF-8, we can
1028 * claim it's UTF-8 even though it isn't.
1030 PL_in_utf8_COLLATE_locale);
1033 /* Find out how long the transformation of a substring of 'longer'
1034 * is. Together the lengths of these transformations are
1035 * sufficient to calculate 'm' and 'b'. The substring is all of
1036 * 'longer' except the first character. This minimizes the chances
1037 * of being swayed by outliers */
1038 x_shorter = _mem_collxfrm(longer + 1,
1041 PL_in_utf8_COLLATE_locale);
1042 Safefree(x_shorter);
1044 /* If the results are nonsensical for this simple test, the whole
1045 * locale definition is suspect. Mark it so that locale collation
1046 * is not active at all for it. XXX Should we warn? */
1047 if ( x_len_shorter == 0
1048 || x_len_longer == 0
1049 || x_len_shorter >= x_len_longer)
1051 PL_collxfrm_mult = 0;
1052 PL_collxfrm_base = 0;
1055 SSize_t base; /* Temporary */
1057 /* We have both: m * strlen(longer) + b = x_len_longer
1058 * m * strlen(shorter) + b = x_len_shorter;
1059 * subtracting yields:
1060 * m * (strlen(longer) - strlen(shorter))
1061 * = x_len_longer - x_len_shorter
1062 * But we have set things up so that 'shorter' is 1 byte smaller
1063 * than 'longer'. Hence:
1064 * m = x_len_longer - x_len_shorter
1066 * But if something went wrong, make sure the multiplier is at
1069 if (x_len_longer > x_len_shorter) {
1070 PL_collxfrm_mult = (STRLEN) x_len_longer - x_len_shorter;
1073 PL_collxfrm_mult = 1;
1078 * but in case something has gone wrong, make sure it is
1080 base = x_len_longer - PL_collxfrm_mult * (sizeof(longer) - 1);
1085 /* Add 1 for the trailing NUL */
1086 PL_collxfrm_base = base + 1;
1091 if (DEBUG_L_TEST || debug_initialization) {
1092 PerlIO_printf(Perl_debug_log,
1093 "%s:%d: ?UTF-8 locale=%d; x_len_shorter=%zu, "
1095 " collate multipler=%zu, collate base=%zu\n",
1097 PL_in_utf8_COLLATE_locale,
1098 x_len_shorter, x_len_longer,
1099 PL_collxfrm_mult, PL_collxfrm_base);
1106 #endif /* USE_LOCALE_COLLATE */
1113 S_win32_setlocale(pTHX_ int category, const char* locale)
1115 /* This, for Windows, emulates POSIX setlocale() behavior. There is no
1116 * difference between the two unless the input locale is "", which normally
1117 * means on Windows to get the machine default, which is set via the
1118 * computer's "Regional and Language Options" (or its current equivalent).
1119 * In POSIX, it instead means to find the locale from the user's
1120 * environment. This routine changes the Windows behavior to first look in
1121 * the environment, and, if anything is found, use that instead of going to
1122 * the machine default. If there is no environment override, the machine
1123 * default is used, by calling the real setlocale() with "".
1125 * The POSIX behavior is to use the LC_ALL variable if set; otherwise to
1126 * use the particular category's variable if set; otherwise to use the LANG
1129 bool override_LC_ALL = FALSE;
1133 if (locale && strEQ(locale, "")) {
1137 locale = PerlEnv_getenv("LC_ALL");
1139 if (category == LC_ALL) {
1140 override_LC_ALL = TRUE;
1146 for (i = 0; i < NOMINAL_LC_ALL_INDEX; i++) {
1147 if (category == categories[i]) {
1148 locale = PerlEnv_getenv(category_names[i]);
1153 locale = PerlEnv_getenv("LANG");
1169 result = setlocale(category, locale);
1170 DEBUG_L(STMT_START {
1172 PerlIO_printf(Perl_debug_log, "%s:%d: %s\n", __FILE__, __LINE__,
1173 setlocale_debug_string(category, locale, result));
1177 if (! override_LC_ALL) {
1181 /* Here the input category was LC_ALL, and we have set it to what is in the
1182 * LANG variable or the system default if there is no LANG. But these have
1183 * lower priority than the other LC_foo variables, so override it for each
1184 * one that is set. (If they are set to "", it means to use the same thing
1185 * we just set LC_ALL to, so can skip) */
1187 for (i = 0; i < LC_ALL_INDEX; i++) {
1188 result = PerlEnv_getenv(category_names[i]);
1189 if (result && strNE(result, "")) {
1190 setlocale(categories[i], result);
1191 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
1193 setlocale_debug_string(categories[i], result, "not captured")));
1197 result = setlocale(LC_ALL, NULL);
1198 DEBUG_L(STMT_START {
1200 PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
1202 setlocale_debug_string(LC_ALL, NULL, result));
1212 Perl_setlocale(int category, const char * locale)
1214 /* This wraps POSIX::setlocale() */
1220 #ifdef USE_LOCALE_NUMERIC
1222 /* A NULL locale means only query what the current one is. We have the
1223 * LC_NUMERIC name saved, because we are normally switched into the C
1224 * locale for it. For an LC_ALL query, switch back to get the correct
1225 * results. All other categories don't require special handling */
1226 if (locale == NULL) {
1227 if (category == LC_NUMERIC) {
1228 return savepv(PL_numeric_name);
1233 else if (category == LC_ALL && ! PL_numeric_underlying) {
1235 SET_NUMERIC_UNDERLYING();
1244 /* Save retval since subsequent setlocale() calls may overwrite it. */
1245 retval = savepv(do_setlocale_r(category, locale));
1247 DEBUG_L(PerlIO_printf(Perl_debug_log,
1248 "%s:%d: %s\n", __FILE__, __LINE__,
1249 setlocale_debug_string(category, locale, retval)));
1251 /* Should never happen that a query would return an error, but be
1252 * sure and reset to C locale */
1254 SET_NUMERIC_STANDARD();
1260 /* If locale == NULL, we are just querying the state, but may have switched
1261 * to NUMERIC_UNDERLYING. Switch back before returning. */
1262 if (locale == NULL) {
1263 SET_NUMERIC_STANDARD();
1267 /* Now that have switched locales, we have to update our records to
1272 #ifdef USE_LOCALE_CTYPE
1279 #ifdef USE_LOCALE_COLLATE
1282 new_collate(retval);
1286 #ifdef USE_LOCALE_NUMERIC
1289 new_numeric(retval);
1297 /* LC_ALL updates all the things we care about. The values may not
1298 * be the same as 'retval', as the locale "" may have set things
1301 # ifdef USE_LOCALE_CTYPE
1303 newlocale = do_setlocale_c(LC_CTYPE, NULL);
1304 new_ctype(newlocale);
1306 # endif /* USE_LOCALE_CTYPE */
1307 # ifdef USE_LOCALE_COLLATE
1309 newlocale = do_setlocale_c(LC_COLLATE, NULL);
1310 new_collate(newlocale);
1313 # ifdef USE_LOCALE_NUMERIC
1315 newlocale = do_setlocale_c(LC_NUMERIC, NULL);
1316 new_numeric(newlocale);
1318 # endif /* USE_LOCALE_NUMERIC */
1330 PERL_STATIC_INLINE const char *
1331 S_save_to_buffer(const char * string, char **buf, Size_t *buf_size, const Size_t offset)
1333 /* Copy the NUL-terminated 'string' to 'buf' + 'offset'. 'buf' has size 'buf_size',
1334 * growing it if necessary */
1336 const Size_t string_size = strlen(string) + offset + 1;
1338 PERL_ARGS_ASSERT_SAVE_TO_BUFFER;
1340 if (*buf_size == 0) {
1341 Newx(*buf, string_size, char);
1342 *buf_size = string_size;
1344 else if (string_size > *buf_size) {
1345 Renew(*buf, string_size, char);
1346 *buf_size = string_size;
1349 Copy(string, *buf + offset, string_size - offset, char);
1355 =head1 Locale-related functions and macros
1357 =for apidoc Perl_langinfo
1359 This is an (almost ª) drop-in replacement for the system C<L<nl_langinfo(3)>>,
1360 taking the same C<item> parameter values, and returning the same information.
1361 But it is more thread-safe than regular C<nl_langinfo()>, and hides the quirks
1362 of Perl's locale handling from your code, and can be used on systems that lack
1363 a native C<nl_langinfo>.
1371 It delivers the correct results for the C<RADIXCHAR> and C<THOUSESEP> items,
1372 without you having to write extra code. The reason for the extra code would be
1373 because these are from the C<LC_NUMERIC> locale category, which is normally
1374 kept set to the C locale by Perl, no matter what the underlying locale is
1375 supposed to be, and so to get the expected results, you have to temporarily
1376 toggle into the underlying locale, and later toggle back. (You could use
1377 plain C<nl_langinfo> and C<L</STORE_LC_NUMERIC_FORCE_TO_UNDERLYING>> for this
1378 but then you wouldn't get the other advantages of C<Perl_langinfo()>; not
1379 keeping C<LC_NUMERIC> in the C locale would break a lot of CPAN, which is
1380 expecting the radix (decimal point) character to be a dot.)
1384 Depending on C<item>, it works on systems that don't have C<nl_langinfo>, hence
1385 makes your code more portable. Of the fifty-some possible items specified by
1386 the POSIX 2008 standard,
1387 L<http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/langinfo.h.html>,
1388 only two are completely unimplemented. It uses various techniques to recover
1389 the other items, including calling C<L<localeconv(3)>>, and C<L<strftime(3)>>,
1390 both of which are specified in C89, so should be always be available. Later
1391 C<strftime()> versions have additional capabilities; C<""> is returned for
1392 those not available on your system.
1394 It is important to note that on such systems, this calls C<localeconv>, and so
1395 overwrites the static buffer returned from previous explicit calls to that
1396 function. Thus, if the program doesn't use or save the information from an
1397 explicit C<localeconv> call (which good practice suggests should be done
1398 anyway), use of this function can break it.
1400 The details for those items which may differ from what this emulation returns
1401 and what a native C<nl_langinfo()> would return are:
1409 Unimplemented, so returns C<"">.
1419 Only the values for English are returned. C<YESSTR> and C<NOSTR> have been
1420 removed from POSIX 2008, and are retained for backwards compatibility. Your
1421 platform's C<nl_langinfo> may not support them.
1425 Always evaluates to C<%x>, the locale's appropriate date representation.
1429 Always evaluates to C<%X>, the locale's appropriate time representation.
1433 Always evaluates to C<%c>, the locale's appropriate date and time
1438 The return may be incorrect for those rare locales where the currency symbol
1439 replaces the radix character.
1440 Send email to L<mailto:perlbug@perl.org> if you have examples of it needing
1441 to work differently.
1445 Currently this gives the same results as Linux does.
1446 Send email to L<mailto:perlbug@perl.org> if you have examples of it needing
1447 to work differently.
1453 =item C<ERA_D_T_FMT>
1457 These are derived by using C<strftime()>, and not all versions of that function
1458 know about them. C<""> is returned for these on such systems.
1462 When using C<Perl_langinfo> on systems that don't have a native
1463 C<nl_langinfo()>, you must
1465 #include "perl_langinfo.h"
1467 before the C<perl.h> C<#include>. You can replace your C<langinfo.h>
1468 C<#include> with this one. (Doing it this way keeps out the symbols that plain
1469 C<langinfo.h> imports into the namespace for code that doesn't need it.)
1471 You also should not use the bare C<langinfo.h> item names, but should preface
1472 them with C<PERL_>, so use C<PERL_RADIXCHAR> instead of plain C<RADIXCHAR>.
1473 The C<PERL_I<foo>> versions will also work for this function on systems that do
1474 have a native C<nl_langinfo>.
1478 It is thread-friendly, returning its result in a buffer that won't be
1479 overwritten by another thread, so you don't have to code for that possibility.
1480 The buffer can be overwritten by the next call to C<nl_langinfo> or
1481 C<Perl_langinfo> in the same thread.
1485 ª It returns S<C<const char *>>, whereas plain C<nl_langinfo()> returns S<C<char
1486 *>>, but you are (only by documentation) forbidden to write into the buffer.
1487 By declaring this C<const>, the compiler enforces this restriction. The extra
1488 C<const> is why this isn't an unequivocal drop-in replacement for
1493 The original impetus for C<Perl_langinfo()> was so that code that needs to
1494 find out the current currency symbol, floating point radix character, or digit
1495 grouping separator can use, on all systems, the simpler and more
1496 thread-friendly C<nl_langinfo> API instead of C<L<localeconv(3)>> which is a
1497 pain to make thread-friendly. For other fields returned by C<localeconv>, it
1498 is better to use the methods given in L<perlcall> to call
1499 L<C<POSIX::localeconv()>|POSIX/localeconv>, which is thread-friendly.
1506 #ifdef HAS_NL_LANGINFO
1507 Perl_langinfo(const nl_item item)
1509 Perl_langinfo(const int item)
1512 return my_nl_langinfo(item, TRUE);
1516 #ifdef HAS_NL_LANGINFO
1517 S_my_nl_langinfo(const nl_item item, bool toggle)
1519 S_my_nl_langinfo(const int item, bool toggle)
1524 /* We only need to toggle into the underlying LC_NUMERIC locale for these
1525 * two items, and only if not already there */
1526 if (toggle && (( item != PERL_RADIXCHAR && item != PERL_THOUSEP)
1527 || PL_numeric_underlying))
1532 #if defined(HAS_NL_LANGINFO) /* nl_langinfo() is available. */
1533 #if ! defined(HAS_POSIX_2008_LOCALE)
1535 /* Here, use plain nl_langinfo(), switching to the underlying LC_NUMERIC
1536 * for those items dependent on it. This must be copied to a buffer before
1537 * switching back, as some systems destroy the buffer when setlocale() is
1541 DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
1544 STORE_LC_NUMERIC_FORCE_TO_UNDERLYING();
1547 LOCALE_LOCK; /* Prevent interference from another thread executing
1548 this code section (the only call to nl_langinfo in
1551 save_to_buffer(nl_langinfo(item), &PL_langinfo_buf,
1552 &PL_langinfo_bufsize, 0);
1557 RESTORE_LC_NUMERIC();
1561 # else /* Use nl_langinfo_l(), avoiding both a mutex and changing the locale */
1564 bool do_free = FALSE;
1565 locale_t cur = uselocale((locale_t) 0);
1567 if (cur == LC_GLOBAL_LOCALE) {
1568 cur = duplocale(LC_GLOBAL_LOCALE);
1573 if (PL_underlying_numeric_obj) {
1574 cur = PL_underlying_numeric_obj;
1577 cur = newlocale(LC_NUMERIC_MASK, PL_numeric_name, cur);
1582 save_to_buffer(nl_langinfo_l(item, cur),
1583 &PL_langinfo_buf, &PL_langinfo_bufsize, 0);
1591 if (strEQ(PL_langinfo_buf, "")) {
1592 if (item == PERL_YESSTR) {
1595 if (item == PERL_NOSTR) {
1600 return PL_langinfo_buf;
1602 #else /* Below, emulate nl_langinfo as best we can */
1606 # ifdef HAS_LOCALECONV
1608 const struct lconv* lc;
1609 DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
1612 # ifdef HAS_STRFTIME
1615 bool return_format = FALSE; /* Return the %format, not the value */
1616 const char * format;
1620 /* We copy the results to a per-thread buffer, even if not
1621 * multi-threaded. This is in part to simplify this code, and partly
1622 * because we need a buffer anyway for strftime(), and partly because a
1623 * call of localeconv() could otherwise wipe out the buffer, and the
1624 * programmer would not be expecting this, as this is a nl_langinfo()
1625 * substitute after all, so s/he might be thinking their localeconv()
1626 * is safe until another localeconv() call. */
1630 const char * retval;
1632 /* These 2 are unimplemented */
1634 case PERL_ERA: /* For use with strftime() %E modifier */
1639 /* We use only an English set, since we don't know any more */
1640 case PERL_YESEXPR: return "^[+1yY]";
1641 case PERL_YESSTR: return "yes";
1642 case PERL_NOEXPR: return "^[-0nN]";
1643 case PERL_NOSTR: return "no";
1645 # ifdef HAS_LOCALECONV
1649 /* We don't bother with localeconv_l() because any system that
1650 * has it is likely to also have nl_langinfo() */
1652 LOCALE_LOCK; /* Prevent interference with other threads
1653 using localeconv() */
1657 || ! lc->currency_symbol
1658 || strEQ("", lc->currency_symbol))
1664 /* Leave the first spot empty to be filled in below */
1665 save_to_buffer(lc->currency_symbol, &PL_langinfo_buf,
1666 &PL_langinfo_bufsize, 1);
1667 if (lc->mon_decimal_point && strEQ(lc->mon_decimal_point, ""))
1668 { /* khw couldn't figure out how the localedef specifications
1669 would show that the $ should replace the radix; this is
1670 just a guess as to how it might work.*/
1671 *PL_langinfo_buf = '.';
1673 else if (lc->p_cs_precedes) {
1674 *PL_langinfo_buf = '-';
1677 *PL_langinfo_buf = '+';
1683 case PERL_RADIXCHAR:
1687 STORE_LC_NUMERIC_FORCE_TO_UNDERLYING();
1690 LOCALE_LOCK; /* Prevent interference with other threads
1691 using localeconv() */
1698 retval = (item == PERL_RADIXCHAR)
1700 : lc->thousands_sep;
1706 save_to_buffer(retval, &PL_langinfo_buf,
1707 &PL_langinfo_bufsize, 0);
1712 RESTORE_LC_NUMERIC();
1718 # ifdef HAS_STRFTIME
1720 /* These are defined by C89, so we assume that strftime supports
1721 * them, and so are returned unconditionally; they may not be what
1722 * the locale actually says, but should give good enough results
1723 * for someone using them as formats (as opposed to trying to parse
1724 * them to figure out what the locale says). The other format
1725 * items are actually tested to verify they work on the platform */
1726 case PERL_D_FMT: return "%x";
1727 case PERL_T_FMT: return "%X";
1728 case PERL_D_T_FMT: return "%c";
1730 /* These formats are only available in later strfmtime's */
1731 case PERL_ERA_D_FMT: case PERL_ERA_T_FMT: case PERL_ERA_D_T_FMT:
1732 case PERL_T_FMT_AMPM:
1734 /* The rest can be gotten from most versions of strftime(). */
1735 case PERL_ABDAY_1: case PERL_ABDAY_2: case PERL_ABDAY_3:
1736 case PERL_ABDAY_4: case PERL_ABDAY_5: case PERL_ABDAY_6:
1738 case PERL_ALT_DIGITS:
1739 case PERL_AM_STR: case PERL_PM_STR:
1740 case PERL_ABMON_1: case PERL_ABMON_2: case PERL_ABMON_3:
1741 case PERL_ABMON_4: case PERL_ABMON_5: case PERL_ABMON_6:
1742 case PERL_ABMON_7: case PERL_ABMON_8: case PERL_ABMON_9:
1743 case PERL_ABMON_10: case PERL_ABMON_11: case PERL_ABMON_12:
1744 case PERL_DAY_1: case PERL_DAY_2: case PERL_DAY_3: case PERL_DAY_4:
1745 case PERL_DAY_5: case PERL_DAY_6: case PERL_DAY_7:
1746 case PERL_MON_1: case PERL_MON_2: case PERL_MON_3: case PERL_MON_4:
1747 case PERL_MON_5: case PERL_MON_6: case PERL_MON_7: case PERL_MON_8:
1748 case PERL_MON_9: case PERL_MON_10: case PERL_MON_11:
1753 init_tm(&tm); /* Precaution against core dumps */
1757 tm.tm_year = 2017 - 1900;
1764 "panic: %s: %d: switch case: %d problem",
1765 __FILE__, __LINE__, item);
1766 NOT_REACHED; /* NOTREACHED */
1768 case PERL_PM_STR: tm.tm_hour = 18;
1773 case PERL_ABDAY_7: tm.tm_wday++;
1774 case PERL_ABDAY_6: tm.tm_wday++;
1775 case PERL_ABDAY_5: tm.tm_wday++;
1776 case PERL_ABDAY_4: tm.tm_wday++;
1777 case PERL_ABDAY_3: tm.tm_wday++;
1778 case PERL_ABDAY_2: tm.tm_wday++;
1783 case PERL_DAY_7: tm.tm_wday++;
1784 case PERL_DAY_6: tm.tm_wday++;
1785 case PERL_DAY_5: tm.tm_wday++;
1786 case PERL_DAY_4: tm.tm_wday++;
1787 case PERL_DAY_3: tm.tm_wday++;
1788 case PERL_DAY_2: tm.tm_wday++;
1793 case PERL_ABMON_12: tm.tm_mon++;
1794 case PERL_ABMON_11: tm.tm_mon++;
1795 case PERL_ABMON_10: tm.tm_mon++;
1796 case PERL_ABMON_9: tm.tm_mon++;
1797 case PERL_ABMON_8: tm.tm_mon++;
1798 case PERL_ABMON_7: tm.tm_mon++;
1799 case PERL_ABMON_6: tm.tm_mon++;
1800 case PERL_ABMON_5: tm.tm_mon++;
1801 case PERL_ABMON_4: tm.tm_mon++;
1802 case PERL_ABMON_3: tm.tm_mon++;
1803 case PERL_ABMON_2: tm.tm_mon++;
1808 case PERL_MON_12: tm.tm_mon++;
1809 case PERL_MON_11: tm.tm_mon++;
1810 case PERL_MON_10: tm.tm_mon++;
1811 case PERL_MON_9: tm.tm_mon++;
1812 case PERL_MON_8: tm.tm_mon++;
1813 case PERL_MON_7: tm.tm_mon++;
1814 case PERL_MON_6: tm.tm_mon++;
1815 case PERL_MON_5: tm.tm_mon++;
1816 case PERL_MON_4: tm.tm_mon++;
1817 case PERL_MON_3: tm.tm_mon++;
1818 case PERL_MON_2: tm.tm_mon++;
1823 case PERL_T_FMT_AMPM:
1825 return_format = TRUE;
1828 case PERL_ERA_D_FMT:
1830 return_format = TRUE;
1833 case PERL_ERA_T_FMT:
1835 return_format = TRUE;
1838 case PERL_ERA_D_T_FMT:
1840 return_format = TRUE;
1843 case PERL_ALT_DIGITS:
1845 format = "%Ow"; /* Find the alternate digit for 0 */
1849 /* We can't use my_strftime() because it doesn't look at
1851 while (0 == strftime(PL_langinfo_buf, PL_langinfo_bufsize,
1854 /* A zero return means one of:
1855 * a) there wasn't enough space in PL_langinfo_buf
1856 * b) the format, like a plain %p, returns empty
1857 * c) it was an illegal format, though some
1858 * implementations of strftime will just return the
1859 * illegal format as a plain character sequence.
1861 * To quickly test for case 'b)', try again but precede
1862 * the format with a plain character. If that result is
1863 * still empty, the problem is either 'a)' or 'c)' */
1865 Size_t format_size = strlen(format) + 1;
1866 Size_t mod_size = format_size + 1;
1870 Newx(mod_format, mod_size, char);
1871 Newx(temp_result, PL_langinfo_bufsize, char);
1873 my_strlcpy(mod_format + 1, format, mod_size);
1874 len = strftime(temp_result,
1875 PL_langinfo_bufsize,
1877 Safefree(mod_format);
1878 Safefree(temp_result);
1880 /* If 'len' is non-zero, it means that we had a case like
1881 * %p which means the current locale doesn't use a.m. or
1882 * p.m., and that is valid */
1885 /* Here, still didn't work. If we get well beyond a
1886 * reasonable size, bail out to prevent an infinite
1889 if (PL_langinfo_bufsize > 100 * format_size) {
1890 *PL_langinfo_buf = '\0';
1893 /* Double the buffer size to retry; Add 1 in case
1894 * original was 0, so we aren't stuck at 0. */
1895 PL_langinfo_bufsize *= 2;
1896 PL_langinfo_bufsize++;
1897 Renew(PL_langinfo_buf, PL_langinfo_bufsize, char);
1905 /* Here, we got a result.
1907 * If the item is 'ALT_DIGITS', PL_langinfo_buf contains the
1908 * alternate format for wday 0. If the value is the same as
1909 * the normal 0, there isn't an alternate, so clear the buffer.
1911 if ( item == PERL_ALT_DIGITS
1912 && strEQ(PL_langinfo_buf, "0"))
1914 *PL_langinfo_buf = '\0';
1917 /* ALT_DIGITS is problematic. Experiments on it showed that
1918 * strftime() did not always work properly when going from
1919 * alt-9 to alt-10. Only a few locales have this item defined,
1920 * and in all of them on Linux that khw was able to find,
1921 * nl_langinfo() merely returned the alt-0 character, possibly
1922 * doubled. Most Unicode digits are in blocks of 10
1923 * consecutive code points, so that is sufficient information
1924 * for those scripts, as we can infer alt-1, alt-2, .... But
1925 * for a Japanese locale, a CJK ideographic 0 is returned, and
1926 * the CJK digits are not in code point order, so you can't
1927 * really infer anything. The localedef for this locale did
1928 * specify the succeeding digits, so that strftime() works
1929 * properly on them, without needing to infer anything. But
1930 * the nl_langinfo() return did not give sufficient information
1931 * for the caller to understand what's going on. So until
1932 * there is evidence that it should work differently, this
1933 * returns the alt-0 string for ALT_DIGITS.
1935 * wday was chosen because its range is all a single digit.
1936 * Things like tm_sec have two digits as the minimum: '00' */
1940 /* If to return the format, not the value, overwrite the buffer
1941 * with it. But some strftime()s will keep the original format
1942 * if illegal, so change those to "" */
1943 if (return_format) {
1944 if (strEQ(PL_langinfo_buf, format)) {
1945 *PL_langinfo_buf = '\0';
1948 save_to_buffer(format, &PL_langinfo_buf,
1949 &PL_langinfo_bufsize, 0);
1960 return PL_langinfo_buf;
1967 * Initialize locale awareness.
1970 Perl_init_i18nl10n(pTHX_ int printwarn)
1974 * 0 if not to output warning when setup locale is bad
1975 * 1 if to output warning based on value of PERL_BADLANG
1976 * >1 if to output regardless of PERL_BADLANG
1979 * 1 = set ok or not applicable,
1980 * 0 = fallback to a locale of lower priority
1981 * -1 = fallback to all locales failed, not even to the C locale
1983 * Under -DDEBUGGING, if the environment variable PERL_DEBUG_LOCALE_INIT is
1984 * set, debugging information is output.
1986 * This looks more complicated than it is, mainly due to the #ifdefs.
1988 * We try to set LC_ALL to the value determined by the environment. If
1989 * there is no LC_ALL on this platform, we try the individual categories we
1990 * know about. If this works, we are done.
1992 * But if it doesn't work, we have to do something else. We search the
1993 * environment variables ourselves instead of relying on the system to do
1994 * it. We look at, in order, LC_ALL, LANG, a system default locale (if we
1995 * think there is one), and the ultimate fallback "C". This is all done in
1996 * the same loop as above to avoid duplicating code, but it makes things
1997 * more complex. The 'trial_locales' array is initialized with just one
1998 * element; it causes the behavior described in the paragraph above this to
1999 * happen. If that fails, we add elements to 'trial_locales', and do extra
2000 * loop iterations to cause the behavior described in this paragraph.
2002 * On Ultrix, the locale MUST come from the environment, so there is
2003 * preliminary code to set it. I (khw) am not sure that it is necessary,
2004 * and that this couldn't be folded into the loop, but barring any real
2005 * platforms to test on, it's staying as-is
2007 * A slight complication is that in embedded Perls, the locale may already
2008 * be set-up, and we don't want to get it from the normal environment
2009 * variables. This is handled by having a special environment variable
2010 * indicate we're in this situation. We simply set setlocale's 2nd
2011 * parameter to be a NULL instead of "". That indicates to setlocale that
2012 * it is not to change anything, but to return the current value,
2013 * effectively initializing perl's db to what the locale already is.
2015 * We play the same trick with NULL if a LC_ALL succeeds. We call
2016 * setlocale() on the individual categores with NULL to get their existing
2017 * values for our db, instead of trying to change them.
2024 PERL_UNUSED_ARG(printwarn);
2026 #else /* USE_LOCALE */
2029 const char * const language = savepv(PerlEnv_getenv("LANGUAGE"));
2033 /* NULL uses the existing already set up locale */
2034 const char * const setlocale_init = (PerlEnv_getenv("PERL_SKIP_LOCALE_INIT"))
2037 const char* trial_locales[5]; /* 5 = 1 each for "", LC_ALL, LANG, "", C */
2038 unsigned int trial_locales_count;
2039 const char * const lc_all = savepv(PerlEnv_getenv("LC_ALL"));
2040 const char * const lang = savepv(PerlEnv_getenv("LANG"));
2041 bool setlocale_failure = FALSE;
2044 /* A later getenv() could zap this, so only use here */
2045 const char * const bad_lang_use_once = PerlEnv_getenv("PERL_BADLANG");
2047 const bool locwarn = (printwarn > 1
2049 && ( ! bad_lang_use_once
2051 /* disallow with "" or "0" */
2053 && strNE("0", bad_lang_use_once)))));
2055 /* setlocale() return vals; not copied so must be looked at immediately */
2056 const char * sl_result[NOMINAL_LC_ALL_INDEX + 1];
2058 /* current locale for given category; should have been copied so aren't
2060 const char * curlocales[NOMINAL_LC_ALL_INDEX + 1];
2064 /* In some systems you can find out the system default locale
2065 * and use that as the fallback locale. */
2066 # define SYSTEM_DEFAULT_LOCALE
2068 # ifdef SYSTEM_DEFAULT_LOCALE
2070 const char *system_default_locale = NULL;
2075 # define DEBUG_LOCALE_INIT(a,b,c)
2078 DEBUG_INITIALIZATION_set(cBOOL(PerlEnv_getenv("PERL_DEBUG_LOCALE_INIT")));
2080 # define DEBUG_LOCALE_INIT(category, locale, result) \
2082 if (debug_initialization) { \
2083 PerlIO_printf(Perl_debug_log, \
2085 __FILE__, __LINE__, \
2086 setlocale_debug_string(category, \
2092 /* Make sure the parallel arrays are properly set up */
2093 # ifdef USE_LOCALE_NUMERIC
2094 assert(categories[LC_NUMERIC_INDEX] == LC_NUMERIC);
2095 assert(strEQ(category_names[LC_NUMERIC_INDEX], "LC_NUMERIC"));
2097 # ifdef USE_LOCALE_CTYPE
2098 assert(categories[LC_CTYPE_INDEX] == LC_CTYPE);
2099 assert(strEQ(category_names[LC_CTYPE_INDEX], "LC_CTYPE"));
2101 # ifdef USE_LOCALE_COLLATE
2102 assert(categories[LC_COLLATE_INDEX] == LC_COLLATE);
2103 assert(strEQ(category_names[LC_COLLATE_INDEX], "LC_COLLATE"));
2105 # ifdef USE_LOCALE_TIME
2106 assert(categories[LC_TIME_INDEX] == LC_TIME);
2107 assert(strEQ(category_names[LC_TIME_INDEX], "LC_TIME"));
2109 # ifdef USE_LOCALE_MESSAGES
2110 assert(categories[LC_MESSAGES_INDEX] == LC_MESSAGES);
2111 assert(strEQ(category_names[LC_MESSAGES_INDEX], "LC_MESSAGES"));
2113 # ifdef USE_LOCALE_MONETARY
2114 assert(categories[LC_MONETARY_INDEX] == LC_MONETARY);
2115 assert(strEQ(category_names[LC_MONETARY_INDEX], "LC_MONETARY"));
2117 # ifdef USE_LOCALE_ADDRESS
2118 assert(categories[LC_ADDRESS_INDEX] == LC_ADDRESS);
2119 assert(strEQ(category_names[LC_ADDRESS_INDEX], "LC_ADDRESS"));
2121 # ifdef USE_LOCALE_IDENTIFICATION
2122 assert(categories[LC_IDENTIFICATION_INDEX] == LC_IDENTIFICATION);
2123 assert(strEQ(category_names[LC_IDENTIFICATION_INDEX], "LC_IDENTIFICATION"));
2125 # ifdef USE_LOCALE_MEASUREMENT
2126 assert(categories[LC_MEASUREMENT_INDEX] == LC_MEASUREMENT);
2127 assert(strEQ(category_names[LC_MEASUREMENT_INDEX], "LC_MEASUREMENT"));
2129 # ifdef USE_LOCALE_PAPER
2130 assert(categories[LC_PAPER_INDEX] == LC_PAPER);
2131 assert(strEQ(category_names[LC_PAPER_INDEX], "LC_PAPER"));
2133 # ifdef USE_LOCALE_TELEPHONE
2134 assert(categories[LC_TELEPHONE_INDEX] == LC_TELEPHONE);
2135 assert(strEQ(category_names[LC_TELEPHONE_INDEX], "LC_TELEPHONE"));
2138 assert(categories[LC_ALL_INDEX] == LC_ALL);
2139 assert(strEQ(category_names[LC_ALL_INDEX], "LC_ALL"));
2140 assert(NOMINAL_LC_ALL_INDEX == LC_ALL_INDEX);
2142 # endif /* DEBUGGING */
2144 /* Initialize the cache of the program's UTF-8ness for the always known
2145 * locales C and POSIX */
2146 my_strlcpy(PL_locale_utf8ness, C_and_POSIX_utf8ness,
2147 sizeof(PL_locale_utf8ness));
2149 PL_numeric_radix_sv = newSVpvs(".");
2151 # ifdef LOCALE_ENVIRON_REQUIRED
2154 * Ultrix setlocale(..., "") fails if there are no environment
2155 * variables from which to get a locale name.
2159 # error Ultrix without LC_ALL not implemented
2165 sl_result[LC_ALL_INDEX] = do_setlocale_c(LC_ALL, setlocale_init);
2166 DEBUG_LOCALE_INIT(LC_ALL, setlocale_init, sl_result[LC_ALL_INDEX]);
2167 if (sl_result[LC_ALL_INDEX])
2170 setlocale_failure = TRUE;
2172 if (! setlocale_failure) {
2173 const char * locale_param;
2174 for (i = 0; i < LC_ALL_INDEX; i++) {
2175 locale_param = (! done && (lang || PerlEnv_getenv(category_names[i])))
2178 sl_result[i] = do_setlocale_r(categories[i], locale_param);
2179 if (! sl_result[i]) {
2180 setlocale_failure = TRUE;
2182 DEBUG_LOCALE_INIT(categories[i], locale_param, sl_result[i]);
2187 # endif /* LC_ALL */
2188 # endif /* LOCALE_ENVIRON_REQUIRED */
2190 /* We try each locale in the list until we get one that works, or exhaust
2191 * the list. Normally the loop is executed just once. But if setting the
2192 * locale fails, inside the loop we add fallback trials to the array and so
2193 * will execute the loop multiple times */
2194 trial_locales[0] = setlocale_init;
2195 trial_locales_count = 1;
2197 for (i= 0; i < trial_locales_count; i++) {
2198 const char * trial_locale = trial_locales[i];
2202 /* XXX This is to preserve old behavior for LOCALE_ENVIRON_REQUIRED
2203 * when i==0, but I (khw) don't think that behavior makes much
2205 setlocale_failure = FALSE;
2207 # ifdef SYSTEM_DEFAULT_LOCALE
2208 # ifdef WIN32 /* Note that assumes Win32 has LC_ALL */
2210 /* On Windows machines, an entry of "" after the 0th means to use
2211 * the system default locale, which we now proceed to get. */
2212 if (strEQ(trial_locale, "")) {
2215 /* Note that this may change the locale, but we are going to do
2216 * that anyway just below */
2217 system_default_locale = do_setlocale_c(LC_ALL, "");
2218 DEBUG_LOCALE_INIT(LC_ALL, "", system_default_locale);
2220 /* Skip if invalid or if it's already on the list of locales to
2222 if (! system_default_locale) {
2223 goto next_iteration;
2225 for (j = 0; j < trial_locales_count; j++) {
2226 if (strEQ(system_default_locale, trial_locales[j])) {
2227 goto next_iteration;
2231 trial_locale = system_default_locale;
2234 # error SYSTEM_DEFAULT_LOCALE only implemented for Win32
2236 # endif /* SYSTEM_DEFAULT_LOCALE */
2242 sl_result[LC_ALL_INDEX] = do_setlocale_c(LC_ALL, trial_locale);
2243 DEBUG_LOCALE_INIT(LC_ALL, trial_locale, sl_result[LC_ALL_INDEX]);
2244 if (! sl_result[LC_ALL_INDEX]) {
2245 setlocale_failure = TRUE;
2248 /* Since LC_ALL succeeded, it should have changed all the other
2249 * categories it can to its value; so we massage things so that the
2250 * setlocales below just return their category's current values.
2251 * This adequately handles the case in NetBSD where LC_COLLATE may
2252 * not be defined for a locale, and setting it individually will
2253 * fail, whereas setting LC_ALL succeeds, leaving LC_COLLATE set to
2254 * the POSIX locale. */
2255 trial_locale = NULL;
2258 # endif /* LC_ALL */
2260 if (! setlocale_failure) {
2262 for (j = 0; j < NOMINAL_LC_ALL_INDEX; j++) {
2264 = savepv(do_setlocale_r(categories[j], trial_locale));
2265 if (! curlocales[j]) {
2266 setlocale_failure = TRUE;
2268 DEBUG_LOCALE_INIT(categories[j], trial_locale, curlocales[j]);
2271 if (! setlocale_failure) { /* All succeeded */
2272 break; /* Exit trial_locales loop */
2276 /* Here, something failed; will need to try a fallback. */
2282 if (locwarn) { /* Output failure info only on the first one */
2286 PerlIO_printf(Perl_error_log,
2287 "perl: warning: Setting locale failed.\n");
2289 # else /* !LC_ALL */
2291 PerlIO_printf(Perl_error_log,
2292 "perl: warning: Setting locale failed for the categories:\n\t");
2294 for (j = 0; j < NOMINAL_LC_ALL_INDEX; j++) {
2295 if (! curlocales[j]) {
2296 PerlIO_printf(Perl_error_log, category_names[j]);
2299 Safefree(curlocales[j]);
2303 # endif /* LC_ALL */
2305 PerlIO_printf(Perl_error_log,
2306 "perl: warning: Please check that your locale settings:\n");
2310 PerlIO_printf(Perl_error_log,
2311 "\tLANGUAGE = %c%s%c,\n",
2312 language ? '"' : '(',
2313 language ? language : "unset",
2314 language ? '"' : ')');
2317 PerlIO_printf(Perl_error_log,
2318 "\tLC_ALL = %c%s%c,\n",
2320 lc_all ? lc_all : "unset",
2321 lc_all ? '"' : ')');
2323 # if defined(USE_ENVIRON_ARRAY)
2328 /* Look through the environment for any variables of the
2329 * form qr/ ^ LC_ [A-Z]+ = /x, except LC_ALL which was
2330 * already handled above. These are assumed to be locale
2331 * settings. Output them and their values. */
2332 for (e = environ; *e; e++) {
2333 const STRLEN prefix_len = sizeof("LC_") - 1;
2336 if ( strBEGINs(*e, "LC_")
2337 && ! strBEGINs(*e, "LC_ALL=")
2338 && (uppers_len = strspn(*e + prefix_len,
2339 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
2340 && ((*e)[prefix_len + uppers_len] == '='))
2342 PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
2343 (int) (prefix_len + uppers_len), *e,
2344 *e + prefix_len + uppers_len + 1);
2351 PerlIO_printf(Perl_error_log,
2352 "\t(possibly more locale environment variables)\n");
2356 PerlIO_printf(Perl_error_log,
2357 "\tLANG = %c%s%c\n",
2359 lang ? lang : "unset",
2362 PerlIO_printf(Perl_error_log,
2363 " are supported and installed on your system.\n");
2366 /* Calculate what fallback locales to try. We have avoided this
2367 * until we have to, because failure is quite unlikely. This will
2368 * usually change the upper bound of the loop we are in.
2370 * Since the system's default way of setting the locale has not
2371 * found one that works, We use Perl's defined ordering: LC_ALL,
2372 * LANG, and the C locale. We don't try the same locale twice, so
2373 * don't add to the list if already there. (On POSIX systems, the
2374 * LC_ALL element will likely be a repeat of the 0th element "",
2375 * but there's no harm done by doing it explicitly.
2377 * Note that this tries the LC_ALL environment variable even on
2378 * systems which have no LC_ALL locale setting. This may or may
2379 * not have been originally intentional, but there's no real need
2380 * to change the behavior. */
2382 for (j = 0; j < trial_locales_count; j++) {
2383 if (strEQ(lc_all, trial_locales[j])) {
2387 trial_locales[trial_locales_count++] = lc_all;
2392 for (j = 0; j < trial_locales_count; j++) {
2393 if (strEQ(lang, trial_locales[j])) {
2397 trial_locales[trial_locales_count++] = lang;
2401 # if defined(WIN32) && defined(LC_ALL)
2403 /* For Windows, we also try the system default locale before "C".
2404 * (If there exists a Windows without LC_ALL we skip this because
2405 * it gets too complicated. For those, the "C" is the next
2406 * fallback possibility). The "" is the same as the 0th element of
2407 * the array, but the code at the loop above knows to treat it
2408 * differently when not the 0th */
2409 trial_locales[trial_locales_count++] = "";
2413 for (j = 0; j < trial_locales_count; j++) {
2414 if (strEQ("C", trial_locales[j])) {
2418 trial_locales[trial_locales_count++] = "C";
2421 } /* end of first time through the loop */
2429 } /* end of looping through the trial locales */
2431 if (ok < 1) { /* If we tried to fallback */
2433 if (! setlocale_failure) { /* fallback succeeded */
2434 msg = "Falling back to";
2436 else { /* fallback failed */
2439 /* We dropped off the end of the loop, so have to decrement i to
2440 * get back to the value the last time through */
2444 msg = "Failed to fall back to";
2446 /* To continue, we should use whatever values we've got */
2448 for (j = 0; j < NOMINAL_LC_ALL_INDEX; j++) {
2449 Safefree(curlocales[j]);
2450 curlocales[j] = savepv(do_setlocale_r(categories[j], NULL));
2451 DEBUG_LOCALE_INIT(categories[j], NULL, curlocales[j]);
2456 const char * description;
2457 const char * name = "";
2458 if (strEQ(trial_locales[i], "C")) {
2459 description = "the standard locale";
2463 # ifdef SYSTEM_DEFAULT_LOCALE
2465 else if (strEQ(trial_locales[i], "")) {
2466 description = "the system default locale";
2467 if (system_default_locale) {
2468 name = system_default_locale;
2472 # endif /* SYSTEM_DEFAULT_LOCALE */
2475 description = "a fallback locale";
2476 name = trial_locales[i];
2478 if (name && strNE(name, "")) {
2479 PerlIO_printf(Perl_error_log,
2480 "perl: warning: %s %s (\"%s\").\n", msg, description, name);
2483 PerlIO_printf(Perl_error_log,
2484 "perl: warning: %s %s.\n", msg, description);
2487 } /* End of tried to fallback */
2489 /* Done with finding the locales; update our records */
2491 # ifdef USE_LOCALE_CTYPE
2493 new_ctype(curlocales[LC_CTYPE_INDEX]);
2496 # ifdef USE_LOCALE_COLLATE
2498 new_collate(curlocales[LC_COLLATE_INDEX]);
2501 # ifdef USE_LOCALE_NUMERIC
2503 new_numeric(curlocales[LC_NUMERIC_INDEX]);
2507 for (i = 0; i < NOMINAL_LC_ALL_INDEX; i++) {
2509 # if defined(USE_ITHREADS)
2511 /* This caches whether each category's locale is UTF-8 or not. This
2512 * may involve changing the locale. It is ok to do this at
2513 * initialization time before any threads have started, but not later.
2514 * Caching means that if the program heeds our dictate not to change
2515 * locales in threaded applications, this data will remain valid, and
2516 * it may get queried without having to change locales. If the
2517 * environment is such that all categories have the same locale, this
2518 * isn't needed, as the code will not change the locale; but this
2519 * handles the uncommon case where the environment has disparate
2520 * locales for the categories */
2521 (void) _is_cur_LC_category_utf8(categories[i]);
2525 Safefree(curlocales[i]);
2528 # if defined(USE_PERLIO) && defined(USE_LOCALE_CTYPE)
2530 /* Set PL_utf8locale to TRUE if using PerlIO _and_ the current LC_CTYPE
2531 * locale is UTF-8. The call to new_ctype() just above has already
2532 * calculated the latter value and saved it in PL_in_utf8_CTYPE_locale. If
2533 * both PL_utf8locale and PL_unicode (set by -C or by $ENV{PERL_UNICODE})
2534 * are true, perl.c:S_parse_body() will turn on the PerlIO :utf8 layer on
2535 * STDIN, STDOUT, STDERR, _and_ the default open discipline. */
2536 PL_utf8locale = PL_in_utf8_CTYPE_locale;
2538 /* Set PL_unicode to $ENV{PERL_UNICODE} if using PerlIO.
2539 This is an alternative to using the -C command line switch
2540 (the -C if present will override this). */
2542 const char *p = PerlEnv_getenv("PERL_UNICODE");
2543 PL_unicode = p ? parse_unicode_opts(&p) : 0;
2544 if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
2558 #endif /* USE_LOCALE */
2561 /* So won't continue to output stuff */
2562 DEBUG_INITIALIZATION_set(FALSE);
2569 #ifdef USE_LOCALE_COLLATE
2572 Perl__mem_collxfrm(pTHX_ const char *input_string,
2573 STRLEN len, /* Length of 'input_string' */
2574 STRLEN *xlen, /* Set to length of returned string
2575 (not including the collation index
2577 bool utf8 /* Is the input in UTF-8? */
2581 /* _mem_collxfrm() is a bit like strxfrm() but with two important
2582 * differences. First, it handles embedded NULs. Second, it allocates a bit
2583 * more memory than needed for the transformed data itself. The real
2584 * transformed data begins at offset COLLXFRM_HDR_LEN. *xlen is set to
2585 * the length of that, and doesn't include the collation index size.
2586 * Please see sv_collxfrm() to see how this is used. */
2588 #define COLLXFRM_HDR_LEN sizeof(PL_collation_ix)
2590 char * s = (char *) input_string;
2591 STRLEN s_strlen = strlen(input_string);
2593 STRLEN xAlloc; /* xalloc is a reserved word in VC */
2594 STRLEN length_in_chars;
2595 bool first_time = TRUE; /* Cleared after first loop iteration */
2597 PERL_ARGS_ASSERT__MEM_COLLXFRM;
2599 /* Must be NUL-terminated */
2600 assert(*(input_string + len) == '\0');
2602 /* If this locale has defective collation, skip */
2603 if (PL_collxfrm_base == 0 && PL_collxfrm_mult == 0) {
2604 DEBUG_L(PerlIO_printf(Perl_debug_log,
2605 "_mem_collxfrm: locale's collation is defective\n"));
2609 /* Replace any embedded NULs with the control that sorts before any others.
2610 * This will give as good as possible results on strings that don't
2611 * otherwise contain that character, but otherwise there may be
2612 * less-than-perfect results with that character and NUL. This is
2613 * unavoidable unless we replace strxfrm with our own implementation. */
2614 if (UNLIKELY(s_strlen < len)) { /* Only execute if there is an embedded
2618 STRLEN sans_nuls_len;
2619 int try_non_controls;
2620 char this_replacement_char[] = "?\0"; /* Room for a two-byte string,
2621 making sure 2nd byte is NUL.
2623 STRLEN this_replacement_len;
2625 /* If we don't know what non-NUL control character sorts lowest for
2626 * this locale, find it */
2627 if (PL_strxfrm_NUL_replacement == '\0') {
2629 char * cur_min_x = NULL; /* The min_char's xfrm, (except it also
2630 includes the collation index
2633 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "Looking to replace NUL\n"));
2635 /* Unlikely, but it may be that no control will work to replace
2636 * NUL, in which case we instead look for any character. Controls
2637 * are preferred because collation order is, in general, context
2638 * sensitive, with adjoining characters affecting the order, and
2639 * controls are less likely to have such interactions, allowing the
2640 * NUL-replacement to stand on its own. (Another way to look at it
2641 * is to imagine what would happen if the NUL were replaced by a
2642 * combining character; it wouldn't work out all that well.) */
2643 for (try_non_controls = 0;
2644 try_non_controls < 2;
2647 /* Look through all legal code points (NUL isn't) */
2648 for (j = 1; j < 256; j++) {
2649 char * x; /* j's xfrm plus collation index */
2650 STRLEN x_len; /* length of 'x' */
2651 STRLEN trial_len = 1;
2652 char cur_source[] = { '\0', '\0' };
2654 /* Skip non-controls the first time through the loop. The
2655 * controls in a UTF-8 locale are the L1 ones */
2656 if (! try_non_controls && (PL_in_utf8_COLLATE_locale)
2663 /* Create a 1-char string of the current code point */
2664 cur_source[0] = (char) j;
2666 /* Then transform it */
2667 x = _mem_collxfrm(cur_source, trial_len, &x_len,
2668 0 /* The string is not in UTF-8 */);
2670 /* Ignore any character that didn't successfully transform.
2676 /* If this character's transformation is lower than
2677 * the current lowest, this one becomes the lowest */
2678 if ( cur_min_x == NULL
2679 || strLT(x + COLLXFRM_HDR_LEN,
2680 cur_min_x + COLLXFRM_HDR_LEN))
2682 PL_strxfrm_NUL_replacement = j;
2688 } /* end of loop through all 255 characters */
2690 /* Stop looking if found */
2695 /* Unlikely, but possible, if there aren't any controls that
2696 * work in the locale, repeat the loop, looking for any
2697 * character that works */
2698 DEBUG_L(PerlIO_printf(Perl_debug_log,
2699 "_mem_collxfrm: No control worked. Trying non-controls\n"));
2700 } /* End of loop to try first the controls, then any char */
2703 DEBUG_L(PerlIO_printf(Perl_debug_log,
2704 "_mem_collxfrm: Couldn't find any character to replace"
2705 " embedded NULs in locale %s with", PL_collation_name));
2709 DEBUG_L(PerlIO_printf(Perl_debug_log,
2710 "_mem_collxfrm: Replacing embedded NULs in locale %s with "
2711 "0x%02X\n", PL_collation_name, PL_strxfrm_NUL_replacement));
2713 Safefree(cur_min_x);
2714 } /* End of determining the character that is to replace NULs */
2716 /* If the replacement is variant under UTF-8, it must match the
2717 * UTF8-ness of the original */
2718 if ( ! UVCHR_IS_INVARIANT(PL_strxfrm_NUL_replacement) && utf8) {
2719 this_replacement_char[0] =
2720 UTF8_EIGHT_BIT_HI(PL_strxfrm_NUL_replacement);
2721 this_replacement_char[1] =
2722 UTF8_EIGHT_BIT_LO(PL_strxfrm_NUL_replacement);
2723 this_replacement_len = 2;
2726 this_replacement_char[0] = PL_strxfrm_NUL_replacement;
2727 /* this_replacement_char[1] = '\0' was done at initialization */
2728 this_replacement_len = 1;
2731 /* The worst case length for the replaced string would be if every
2732 * character in it is NUL. Multiply that by the length of each
2733 * replacement, and allow for a trailing NUL */
2734 sans_nuls_len = (len * this_replacement_len) + 1;
2735 Newx(sans_nuls, sans_nuls_len, char);
2738 /* Replace each NUL with the lowest collating control. Loop until have
2739 * exhausted all the NULs */
2740 while (s + s_strlen < e) {
2741 my_strlcat(sans_nuls, s, sans_nuls_len);
2743 /* Do the actual replacement */
2744 my_strlcat(sans_nuls, this_replacement_char, sans_nuls_len);
2746 /* Move past the input NUL */
2748 s_strlen = strlen(s);
2751 /* And add anything that trails the final NUL */
2752 my_strlcat(sans_nuls, s, sans_nuls_len);
2754 /* Switch so below we transform this modified string */
2757 } /* End of replacing NULs */
2759 /* Make sure the UTF8ness of the string and locale match */
2760 if (utf8 != PL_in_utf8_COLLATE_locale) {
2761 /* XXX convert above Unicode to 10FFFF? */
2762 const char * const t = s; /* Temporary so we can later find where the
2765 /* Here they don't match. Change the string's to be what the locale is
2768 if (! utf8) { /* locale is UTF-8, but input isn't; upgrade the input */
2769 s = (char *) bytes_to_utf8((const U8 *) s, &len);
2772 else { /* locale is not UTF-8; but input is; downgrade the input */
2774 s = (char *) bytes_from_utf8((const U8 *) s, &len, &utf8);
2776 /* If the downgrade was successful we are done, but if the input
2777 * contains things that require UTF-8 to represent, have to do
2778 * damage control ... */
2779 if (UNLIKELY(utf8)) {
2781 /* What we do is construct a non-UTF-8 string with
2782 * 1) the characters representable by a single byte converted
2783 * to be so (if necessary);
2784 * 2) and the rest converted to collate the same as the
2785 * highest collating representable character. That makes
2786 * them collate at the end. This is similar to how we
2787 * handle embedded NULs, but we use the highest collating
2788 * code point instead of the smallest. Like the NUL case,
2789 * this isn't perfect, but is the best we can reasonably
2790 * do. Every above-255 code point will sort the same as
2791 * the highest-sorting 0-255 code point. If that code
2792 * point can combine in a sequence with some other code
2793 * points for weight calculations, us changing something to
2794 * be it can adversely affect the results. But in most
2795 * cases, it should work reasonably. And note that this is
2796 * really an illegal situation: using code points above 255
2797 * on a locale where only 0-255 are valid. If two strings
2798 * sort entirely equal, then the sort order for the
2799 * above-255 code points will be in code point order. */
2803 /* If we haven't calculated the code point with the maximum
2804 * collating order for this locale, do so now */
2805 if (! PL_strxfrm_max_cp) {
2808 /* The current transformed string that collates the
2809 * highest (except it also includes the prefixed collation
2811 char * cur_max_x = NULL;
2813 /* Look through all legal code points (NUL isn't) */
2814 for (j = 1; j < 256; j++) {
2817 char cur_source[] = { '\0', '\0' };
2819 /* Create a 1-char string of the current code point */
2820 cur_source[0] = (char) j;
2822 /* Then transform it */
2823 x = _mem_collxfrm(cur_source, 1, &x_len, FALSE);
2825 /* If something went wrong (which it shouldn't), just
2826 * ignore this code point */
2831 /* If this character's transformation is higher than
2832 * the current highest, this one becomes the highest */
2833 if ( cur_max_x == NULL
2834 || strGT(x + COLLXFRM_HDR_LEN,
2835 cur_max_x + COLLXFRM_HDR_LEN))
2837 PL_strxfrm_max_cp = j;
2846 DEBUG_L(PerlIO_printf(Perl_debug_log,
2847 "_mem_collxfrm: Couldn't find any character to"
2848 " replace above-Latin1 chars in locale %s with",
2849 PL_collation_name));
2853 DEBUG_L(PerlIO_printf(Perl_debug_log,
2854 "_mem_collxfrm: highest 1-byte collating character"
2855 " in locale %s is 0x%02X\n",
2857 PL_strxfrm_max_cp));
2859 Safefree(cur_max_x);
2862 /* Here we know which legal code point collates the highest.
2863 * We are ready to construct the non-UTF-8 string. The length
2864 * will be at least 1 byte smaller than the input string
2865 * (because we changed at least one 2-byte character into a
2866 * single byte), but that is eaten up by the trailing NUL */
2872 char * e = (char *) t + len;
2874 for (i = 0; i < len; i+= UTF8SKIP(t + i)) {
2876 if (UTF8_IS_INVARIANT(cur_char)) {
2879 else if (UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(t + i, e)) {
2880 s[d++] = EIGHT_BIT_UTF8_TO_NATIVE(cur_char, t[i+1]);
2882 else { /* Replace illegal cp with highest collating
2884 s[d++] = PL_strxfrm_max_cp;
2888 Renew(s, d, char); /* Free up unused space */
2893 /* Here, we have constructed a modified version of the input. It could
2894 * be that we already had a modified copy before we did this version.
2895 * If so, that copy is no longer needed */
2896 if (t != input_string) {
2901 length_in_chars = (utf8)
2902 ? utf8_length((U8 *) s, (U8 *) s + len)
2905 /* The first element in the output is the collation id, used by
2906 * sv_collxfrm(); then comes the space for the transformed string. The
2907 * equation should give us a good estimate as to how much is needed */
2908 xAlloc = COLLXFRM_HDR_LEN
2910 + (PL_collxfrm_mult * length_in_chars);
2911 Newx(xbuf, xAlloc, char);
2912 if (UNLIKELY(! xbuf)) {
2913 DEBUG_L(PerlIO_printf(Perl_debug_log,
2914 "_mem_collxfrm: Couldn't malloc %zu bytes\n", xAlloc));
2918 /* Store the collation id */
2919 *(U32*)xbuf = PL_collation_ix;
2921 /* Then the transformation of the input. We loop until successful, or we
2925 *xlen = strxfrm(xbuf + COLLXFRM_HDR_LEN, s, xAlloc - COLLXFRM_HDR_LEN);
2927 /* If the transformed string occupies less space than we told strxfrm()
2928 * was available, it means it successfully transformed the whole
2930 if (*xlen < xAlloc - COLLXFRM_HDR_LEN) {
2932 /* Some systems include a trailing NUL in the returned length.
2933 * Ignore it, using a loop in case multiple trailing NULs are
2936 && *(xbuf + COLLXFRM_HDR_LEN + (*xlen) - 1) == '\0')
2941 /* If the first try didn't get it, it means our prediction was low.
2942 * Modify the coefficients so that we predict a larger value in any
2943 * future transformations */
2945 STRLEN needed = *xlen + 1; /* +1 For trailing NUL */
2946 STRLEN computed_guess = PL_collxfrm_base
2947 + (PL_collxfrm_mult * length_in_chars);
2949 /* On zero-length input, just keep current slope instead of
2951 const STRLEN new_m = (length_in_chars != 0)
2952 ? needed / length_in_chars
2955 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2956 "%s: %d: initial size of %zu bytes for a length "
2957 "%zu string was insufficient, %zu needed\n",
2959 computed_guess, length_in_chars, needed));
2961 /* If slope increased, use it, but discard this result for
2962 * length 1 strings, as we can't be sure that it's a real slope
2964 if (length_in_chars > 1 && new_m > PL_collxfrm_mult) {
2968 STRLEN old_m = PL_collxfrm_mult;
2969 STRLEN old_b = PL_collxfrm_base;
2973 PL_collxfrm_mult = new_m;
2974 PL_collxfrm_base = 1; /* +1 For trailing NUL */
2975 computed_guess = PL_collxfrm_base
2976 + (PL_collxfrm_mult * length_in_chars);
2977 if (computed_guess < needed) {
2978 PL_collxfrm_base += needed - computed_guess;
2981 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2982 "%s: %d: slope is now %zu; was %zu, base "
2983 "is now %zu; was %zu\n",
2985 PL_collxfrm_mult, old_m,
2986 PL_collxfrm_base, old_b));
2988 else { /* Slope didn't change, but 'b' did */
2989 const STRLEN new_b = needed
2992 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2993 "%s: %d: base is now %zu; was %zu\n",
2995 new_b, PL_collxfrm_base));
2996 PL_collxfrm_base = new_b;
3003 if (UNLIKELY(*xlen >= PERL_INT_MAX)) {
3004 DEBUG_L(PerlIO_printf(Perl_debug_log,
3005 "_mem_collxfrm: Needed %zu bytes, max permissible is %u\n",
3006 *xlen, PERL_INT_MAX));
3010 /* A well-behaved strxfrm() returns exactly how much space it needs
3011 * (usually not including the trailing NUL) when it fails due to not
3012 * enough space being provided. Assume that this is the case unless
3013 * it's been proven otherwise */
3014 if (LIKELY(PL_strxfrm_is_behaved) && first_time) {
3015 xAlloc = *xlen + COLLXFRM_HDR_LEN + 1;
3017 else { /* Here, either:
3018 * 1) The strxfrm() has previously shown bad behavior; or
3019 * 2) It isn't the first time through the loop, which means
3020 * that the strxfrm() is now showing bad behavior, because
3021 * we gave it what it said was needed in the previous
3022 * iteration, and it came back saying it needed still more.
3023 * (Many versions of cygwin fit this. When the buffer size
3024 * isn't sufficient, they return the input size instead of
3025 * how much is needed.)
3026 * Increase the buffer size by a fixed percentage and try again.
3028 xAlloc += (xAlloc / 4) + 1;
3029 PL_strxfrm_is_behaved = FALSE;
3033 if (DEBUG_Lv_TEST || debug_initialization) {
3034 PerlIO_printf(Perl_debug_log,
3035 "_mem_collxfrm required more space than previously calculated"
3036 " for locale %s, trying again with new guess=%d+%zu\n",
3037 PL_collation_name, (int) COLLXFRM_HDR_LEN,
3038 xAlloc - COLLXFRM_HDR_LEN);
3045 Renew(xbuf, xAlloc, char);
3046 if (UNLIKELY(! xbuf)) {
3047 DEBUG_L(PerlIO_printf(Perl_debug_log,
3048 "_mem_collxfrm: Couldn't realloc %zu bytes\n", xAlloc));
3058 if (DEBUG_Lv_TEST || debug_initialization) {
3060 print_collxfrm_input_and_return(s, s + len, xlen, utf8);
3061 PerlIO_printf(Perl_debug_log, "Its xfrm is:");
3062 PerlIO_printf(Perl_debug_log, "%s\n",
3063 _byte_dump_string((U8 *) xbuf + COLLXFRM_HDR_LEN,
3069 /* Free up unneeded space; retain ehough for trailing NUL */
3070 Renew(xbuf, COLLXFRM_HDR_LEN + *xlen + 1, char);
3072 if (s != input_string) {
3080 if (s != input_string) {
3087 if (DEBUG_Lv_TEST || debug_initialization) {
3088 print_collxfrm_input_and_return(s, s + len, NULL, utf8);
3099 S_print_collxfrm_input_and_return(pTHX_
3100 const char * const s,
3101 const char * const e,
3102 const STRLEN * const xlen,
3106 PERL_ARGS_ASSERT_PRINT_COLLXFRM_INPUT_AND_RETURN;
3108 PerlIO_printf(Perl_debug_log, "_mem_collxfrm[%" UVuf "]: returning ",
3109 (UV)PL_collation_ix);
3111 PerlIO_printf(Perl_debug_log, "%zu", *xlen);
3114 PerlIO_printf(Perl_debug_log, "NULL");
3116 PerlIO_printf(Perl_debug_log, " for locale '%s', string='",
3118 print_bytes_for_locale(s, e, is_utf8);
3120 PerlIO_printf(Perl_debug_log, "'\n");
3124 S_print_bytes_for_locale(pTHX_
3125 const char * const s,
3126 const char * const e,
3130 bool prev_was_printable = TRUE;
3131 bool first_time = TRUE;
3133 PERL_ARGS_ASSERT_PRINT_BYTES_FOR_LOCALE;
3137 ? utf8_to_uvchr_buf((U8 *) t, e, NULL)
3140 if (! prev_was_printable) {
3141 PerlIO_printf(Perl_debug_log, " ");
3143 PerlIO_printf(Perl_debug_log, "%c", (U8) cp);
3144 prev_was_printable = TRUE;
3148 PerlIO_printf(Perl_debug_log, " ");
3150 PerlIO_printf(Perl_debug_log, "%02" UVXf, cp);
3151 prev_was_printable = FALSE;
3153 t += (is_utf8) ? UTF8SKIP(t) : 1;
3158 # endif /* #ifdef DEBUGGING */
3159 #endif /* USE_LOCALE_COLLATE */
3164 S_switch_category_locale_to_template(pTHX_ const int switch_category, const int template_category, const char * template_locale)
3166 /* Changes the locale for LC_'switch_category" to that of
3167 * LC_'template_category', if they aren't already the same. If not NULL,
3168 * 'template_locale' is the locale that 'template_category' is in.
3170 * Returns a copy of the name of the original locale for 'switch_category'
3171 * so can be switched back to with the companion function
3172 * restore_switched_locale(), (NULL if no restoral is necessary.) */
3174 char * restore_to_locale = NULL;
3176 if (switch_category == template_category) { /* No changes needed */
3180 /* Find the original locale of the category we may need to change, so that
3181 * it can be restored to later */
3182 restore_to_locale = stdize_locale(savepv(do_setlocale_r(switch_category,
3184 if (! restore_to_locale) {
3186 "panic: %s: %d: Could not find current %s locale, errno=%d\n",
3187 __FILE__, __LINE__, category_name(switch_category), errno);
3190 /* If the locale of the template category wasn't passed in, find it now */
3191 if (template_locale == NULL) {
3192 template_locale = do_setlocale_r(template_category, NULL);
3193 if (! template_locale) {
3195 "panic: %s: %d: Could not find current %s locale, errno=%d\n",
3196 __FILE__, __LINE__, category_name(template_category), errno);
3200 /* It the locales are the same, there's nothing to do */
3201 if (strEQ(restore_to_locale, template_locale)) {
3202 Safefree(restore_to_locale);
3204 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s locale unchanged as %s\n",
3205 category_name(switch_category), restore_to_locale));
3210 /* Finally, change the locale to the template one */
3211 if (! do_setlocale_r(switch_category, template_locale)) {
3213 "panic: %s: %d: Could not change %s locale to %s, errno=%d\n",
3214 __FILE__, __LINE__, category_name(switch_category),
3215 template_locale, errno);
3218 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s locale switched to %s\n",
3219 category_name(switch_category), template_locale));
3221 return restore_to_locale;
3225 S_restore_switched_locale(pTHX_ const int category, const char * const original_locale)
3227 /* Restores the locale for LC_'category' to 'original_locale' (which is a
3228 * copy that will be freed by this function), or do nothing if the latter
3229 * parameter is NULL */
3231 if (original_locale == NULL) {
3235 if (! do_setlocale_r(category, original_locale)) {
3237 "panic: %s: %d: setlocale %s restore to %s failed, errno=%d\n",
3239 category_name(category), original_locale, errno);
3242 Safefree(original_locale);
3246 Perl__is_cur_LC_category_utf8(pTHX_ int category)
3248 /* Returns TRUE if the current locale for 'category' is UTF-8; FALSE
3249 * otherwise. 'category' may not be LC_ALL. If the platform doesn't have
3250 * nl_langinfo(), nor MB_CUR_MAX, this employs a heuristic, which hence
3251 * could give the wrong result. The result will very likely be correct for
3252 * languages that have commonly used non-ASCII characters, but for notably
3253 * English, it comes down to if the locale's name ends in something like
3254 * "UTF-8". It errs on the side of not being a UTF-8 locale.
3256 * If the platform is early C89, not containing mbtowc(), or we are
3257 * compiled to not pay attention to LC_CTYPE, this employs heuristics.
3258 * These work very well for non-Latin locales or those whose currency
3259 * symbol isn't a '$' nor plain ASCII text. But without LC_CTYPE and at
3260 * least MB_CUR_MAX, English locales with an ASCII currency symbol depend
3261 * on the name containing UTF-8 or not. */
3263 /* Name of current locale corresponding to the input category */
3264 const char *save_input_locale = NULL;
3266 bool is_utf8 = FALSE; /* The return value */
3268 /* The variables below are for the cache of previous lookups using this
3269 * function. The cache is a C string, described at the definition for
3270 * 'C_and_POSIX_utf8ness'.
3272 * The first part of the cache is fixed, for the C and POSIX locales. The
3273 * varying part starts just after them. */
3274 char * utf8ness_cache = PL_locale_utf8ness + STRLENs(C_and_POSIX_utf8ness);
3276 Size_t utf8ness_cache_size; /* Size of the varying portion */
3277 Size_t input_name_len; /* Length in bytes of save_input_locale */
3278 Size_t input_name_len_with_overhead; /* plus extra chars used to store
3279 the name in the cache */
3280 char * delimited; /* The name plus the delimiters used to store
3282 char * name_pos; /* position of 'delimited' in the cache, or 0
3288 assert(category != LC_ALL);
3292 /* Get the desired category's locale */
3293 save_input_locale = stdize_locale(savepv(do_setlocale_r(category, NULL)));
3294 if (! save_input_locale) {
3296 "panic: %s: %d: Could not find current %s locale, errno=%d\n",
3297 __FILE__, __LINE__, category_name(category), errno);
3300 DEBUG_L(PerlIO_printf(Perl_debug_log,
3301 "Current locale for %s is %s\n",
3302 category_name(category), save_input_locale));
3304 input_name_len = strlen(save_input_locale);
3306 /* In our cache, each name is accompanied by two delimiters and a single
3308 input_name_len_with_overhead = input_name_len + 3;
3310 /* Allocate and populate space for a copy of the name surrounded by the
3312 Newx(delimited, input_name_len_with_overhead, char);
3313 delimited[0] = UTF8NESS_SEP[0];
3314 Copy(save_input_locale, delimited + 1, input_name_len, char);
3315 delimited[input_name_len+1] = UTF8NESS_PREFIX[0];
3316 delimited[input_name_len+2] = '\0';
3318 /* And see if that is in the cache */
3319 name_pos = instr(PL_locale_utf8ness, delimited);
3321 is_utf8 = *(name_pos + input_name_len_with_overhead - 1) - '0';
3325 if (DEBUG_Lv_TEST || debug_initialization) {
3326 PerlIO_printf(Perl_debug_log, "UTF8ness for locale %s=%d, \n",
3327 save_input_locale, is_utf8);
3332 /* And, if not already in that position, move it to the beginning of
3333 * the non-constant portion of the list, since it is the most recently
3334 * used. (We don't have to worry about overflow, since just moving
3335 * existing names around) */
3336 if (name_pos > utf8ness_cache) {
3337 Move(utf8ness_cache,
3338 utf8ness_cache + input_name_len_with_overhead,
3339 name_pos - utf8ness_cache, char);
3342 input_name_len_with_overhead - 1, char);
3343 utf8ness_cache[input_name_len_with_overhead - 1] = is_utf8 + '0';
3346 Safefree(delimited);
3347 Safefree(save_input_locale);
3351 /* Here we don't have stored the utf8ness for the input locale. We have to
3354 # if defined(USE_LOCALE_CTYPE) \
3355 && ( (defined(HAS_NL_LANGINFO) && defined(CODESET)) \
3356 || (defined(HAS_MBTOWC) || defined(HAS_MBRTOWC)))
3359 const char *original_ctype_locale
3360 = switch_category_locale_to_template(LC_CTYPE,
3364 /* Here the current LC_CTYPE is set to the locale of the category whose
3365 * information is desired. This means that nl_langinfo() and mbtowc()
3366 * should give the correct results */
3368 # ifdef MB_CUR_MAX /* But we can potentially rule out UTF-8ness, avoiding
3369 calling the functions if we have this */
3371 /* Standard UTF-8 needs at least 4 bytes to represent the maximum
3372 * Unicode code point. */
3374 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s: %d: MB_CUR_MAX=%d\n",
3375 __FILE__, __LINE__, (int) MB_CUR_MAX));
3376 if ((unsigned) MB_CUR_MAX < STRLENs(MAX_UNICODE_UTF8)) {
3378 restore_switched_locale(LC_CTYPE, original_ctype_locale);
3379 goto finish_and_return;
3383 # if defined(HAS_NL_LANGINFO) && defined(CODESET)
3385 { /* The task is easiest if the platform has this POSIX 2001 function.
3386 Except on some platforms it can wrongly return "", so have to have
3387 a fallback. And it can return that it's UTF-8, even if there are
3388 variances from that. For example, Turkish locales may use the
3389 alternate dotted I rules, and sometimes it appears to be a
3390 defective locale definition. XXX We should probably check for
3391 these in the Latin1 range and warn (but on glibc, requires
3392 iswalnum() etc. due to their not handling 80-FF correctly */
3393 const char *codeset = my_nl_langinfo(PERL_CODESET, FALSE);
3394 /* FALSE => already in dest locale */
3396 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3397 "\tnllanginfo returned CODESET '%s'\n", codeset));
3399 if (codeset && strNE(codeset, "")) {
3401 /* If the implementation of foldEQ() somehow were
3402 * to change to not go byte-by-byte, this could
3403 * read past end of string, as only one length is
3404 * checked. But currently, a premature NUL will
3405 * compare false, and it will stop there */
3406 is_utf8 = cBOOL( foldEQ(codeset, STR_WITH_LEN("UTF-8"))
3407 || foldEQ(codeset, STR_WITH_LEN("UTF8")));
3409 DEBUG_L(PerlIO_printf(Perl_debug_log,
3410 "\tnllanginfo returned CODESET '%s'; ?UTF8 locale=%d\n",
3412 restore_switched_locale(LC_CTYPE, original_ctype_locale);
3413 goto finish_and_return;
3418 # if defined(HAS_MBTOWC) || defined(HAS_MBRTOWC)
3419 /* We can see if this is a UTF-8-like locale if have mbtowc(). It was a
3420 * late adder to C89, so very likely to have it. However, testing has
3421 * shown that, like nl_langinfo() above, there are locales that are not
3422 * strictly UTF-8 that this will return that they are */
3429 # if defined(HAS_MBRTOWC) && defined(USE_ITHREADS)
3435 /* mbrtowc() and mbtowc() convert a byte string to a wide
3436 * character. Feed a byte string to one of them and check that the
3437 * result is the expected Unicode code point */
3439 # if defined(HAS_MBRTOWC) && defined(USE_ITHREADS)
3440 /* Prefer this function if available, as it's reentrant */
3442 memset(&ps, 0, sizeof(ps));;
3443 PERL_UNUSED_RESULT(mbrtowc(&wc, NULL, 0, &ps)); /* Reset any shift
3446 len = mbrtowc(&wc, STR_WITH_LEN(REPLACEMENT_CHARACTER_UTF8), &ps);
3452 PERL_UNUSED_RESULT(mbtowc(&wc, NULL, 0));/* Reset any shift state */
3454 len = mbtowc(&wc, STR_WITH_LEN(REPLACEMENT_CHARACTER_UTF8));
3461 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3462 "\treturn from mbtowc; len=%d; code_point=%x; errno=%d\n",
3463 len, (unsigned int) wc, GET_ERRNO));
3465 is_utf8 = cBOOL( len == STRLENs(REPLACEMENT_CHARACTER_UTF8)
3466 && wc == (wchar_t) UNICODE_REPLACEMENT);
3469 restore_switched_locale(LC_CTYPE, original_ctype_locale);
3470 goto finish_and_return;
3476 /* Here, we must have a C89 compiler that doesn't have mbtowc(). Next
3477 * try looking at the currency symbol to see if it disambiguates
3478 * things. Often that will be in the native script, and if the symbol
3479 * isn't in UTF-8, we know that the locale isn't. If it is non-ASCII
3480 * UTF-8, we infer that the locale is too, as the odds of a non-UTF8
3481 * string being valid UTF-8 are quite small */
3483 # ifdef USE_LOCALE_MONETARY
3485 /* If have LC_MONETARY, we can look at the currency symbol. Often that
3486 * will be in the native script. We do this one first because there is
3487 * just one string to examine, so potentially avoids work */
3490 const char *original_monetary_locale
3491 = switch_category_locale_to_template(LC_MONETARY,
3494 bool only_ascii = FALSE;
3495 const U8 * currency_string
3496 = (const U8 *) my_nl_langinfo(PERL_CRNCYSTR, FALSE);
3497 /* 2nd param not relevant for this item */
3498 const U8 * first_variant;
3500 assert( *currency_string == '-'
3501 || *currency_string == '+'
3502 || *currency_string == '.');
3506 if (is_utf8_invariant_string_loc(currency_string, 0, &first_variant))
3508 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));
3512 is_utf8 = is_strict_utf8_string(first_variant, 0);
3515 restore_switched_locale(LC_MONETARY, original_monetary_locale);
3519 /* It isn't a UTF-8 locale if the symbol is not legal UTF-8;
3520 * otherwise assume the locale is UTF-8 if and only if the symbol
3521 * is non-ascii UTF-8. */
3522 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "\t?Currency symbol for %s is UTF-8=%d\n",
3523 save_input_locale, is_utf8));
3524 goto finish_and_return;
3528 # endif /* USE_LOCALE_MONETARY */
3529 # if defined(HAS_STRFTIME) && defined(USE_LOCALE_TIME)
3531 /* Still haven't found a non-ASCII string to disambiguate UTF-8 or not. Try
3532 * the names of the months and weekdays, timezone, and am/pm indicator */
3534 const char *original_time_locale
3535 = switch_category_locale_to_template(LC_TIME,
3539 bool is_dst = FALSE;
3543 char * formatted_time;
3545 /* Here the current LC_TIME is set to the locale of the category
3546 * whose information is desired. Look at all the days of the week and
3547 * month names, and the timezone and am/pm indicator for UTF-8 variant
3548 * characters. The first such a one found will tell us if the locale
3549 * is UTF-8 or not */
3551 for (i = 0; i < 7 + 12; i++) { /* 7 days; 12 months */
3552 formatted_time = my_strftime("%A %B %Z %p",
3553 0, 0, hour, dom, month, 2012 - 1900, 0, 0, is_dst);
3554 if ( ! formatted_time
3555 || is_utf8_invariant_string((U8 *) formatted_time, 0))
3558 /* Here, we didn't find a non-ASCII. Try the next time through
3559 * with the complemented dst and am/pm, and try with the next
3560 * weekday. After we have gotten all weekdays, try the next
3563 hour = (hour + 12) % 24;
3571 /* Here, we have a non-ASCII. Return TRUE is it is valid UTF8;
3572 * false otherwise. But first, restore LC_TIME to its original
3573 * locale if we changed it */
3574 restore_switched_locale(LC_TIME, original_time_locale);
3576 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "\t?time-related strings for %s are UTF-8=%d\n",
3578 is_utf8_string((U8 *) formatted_time, 0)));
3579 is_utf8 = is_utf8_string((U8 *) formatted_time, 0);
3580 goto finish_and_return;
3583 /* Falling off the end of the loop indicates all the names were just
3584 * ASCII. Go on to the next test. If we changed it, restore LC_TIME
3585 * to its original locale */
3586 restore_switched_locale(LC_TIME, original_time_locale);
3587 DEBUG_Lv(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));
3592 # if 0 && defined(USE_LOCALE_MESSAGES) && defined(HAS_SYS_ERRLIST)
3594 /* This code is ifdefd out because it was found to not be necessary in testing
3595 * on our dromedary test machine, which has over 700 locales. There, this
3596 * added no value to looking at the currency symbol and the time strings. I
3597 * left it in so as to avoid rewriting it if real-world experience indicates
3598 * that dromedary is an outlier. Essentially, instead of returning abpve if we
3599 * haven't found illegal utf8, we continue on and examine all the strerror()
3600 * messages on the platform for utf8ness. If all are ASCII, we still don't
3601 * know the answer; but otherwise we have a pretty good indication of the
3602 * utf8ness. The reason this doesn't help much is that the messages may not
3603 * have been translated into the locale. The currency symbol and time strings
3604 * are much more likely to have been translated. */
3607 bool non_ascii = FALSE;
3608 const char *original_messages_locale
3609 = switch_category_locale_to_template(LC_MESSAGES,
3612 const char * errmsg = NULL;
3614 /* Here the current LC_MESSAGES is set to the locale of the category
3615 * whose information is desired. Look through all the messages. We
3616 * can't use Strerror() here because it may expand to code that
3617 * segfaults in miniperl */
3619 for (e = 0; e <= sys_nerr; e++) {
3621 errmsg = sys_errlist[e];
3622 if (errno || !errmsg) {
3625 errmsg = savepv(errmsg);
3626 if (! is_utf8_invariant_string((U8 *) errmsg, 0)) {
3628 is_utf8 = is_utf8_string((U8 *) errmsg, 0);
3634 restore_switched_locale(LC_MESSAGES, original_messages_locale);
3638 /* Any non-UTF-8 message means not a UTF-8 locale; if all are valid,
3639 * any non-ascii means it is one; otherwise we assume it isn't */
3640 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "\t?error messages for %s are UTF-8=%d\n",
3643 goto finish_and_return;
3646 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));
3650 # ifndef EBCDIC /* On os390, even if the name ends with "UTF-8', it isn't a
3653 /* As a last resort, look at the locale name to see if it matches
3654 * qr/UTF -? * 8 /ix, or some other common locale names. This "name", the
3655 * return of setlocale(), is actually defined to be opaque, so we can't
3656 * really rely on the absence of various substrings in the name to indicate
3657 * its UTF-8ness, but if it has UTF8 in the name, it is extremely likely to
3658 * be a UTF-8 locale. Similarly for the other common names */
3661 const Size_t final_pos = strlen(save_input_locale) - 1;
3663 if (final_pos >= 3) {
3664 const char *name = save_input_locale;
3666 /* Find next 'U' or 'u' and look from there */
3667 while ((name += strcspn(name, "Uu") + 1)
3668 <= save_input_locale + final_pos - 2)
3670 if ( isALPHA_FOLD_NE(*name, 't')
3671 || isALPHA_FOLD_NE(*(name + 1), 'f'))
3676 if (*(name) == '-') {
3677 if ((name > save_input_locale + final_pos - 1)) {
3682 if (*(name) == '8') {
3683 DEBUG_L(PerlIO_printf(Perl_debug_log,
3684 "Locale %s ends with UTF-8 in name\n",
3685 save_input_locale));
3687 goto finish_and_return;
3690 DEBUG_L(PerlIO_printf(Perl_debug_log,
3691 "Locale %s doesn't end with UTF-8 in name\n",
3692 save_input_locale));
3697 /* http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756.aspx */
3698 if (memENDs(save_input_locale, final_pos, "65001")) {
3699 DEBUG_L(PerlIO_printf(Perl_debug_log,
3700 "Locale %s ends with 65001 in name, is UTF-8 locale\n",
3701 save_input_locale));
3703 goto finish_and_return;
3710 /* Other common encodings are the ISO 8859 series, which aren't UTF-8. But
3711 * since we are about to return FALSE anyway, there is no point in doing
3712 * this extra work */
3715 if (instr(save_input_locale, "8859")) {
3716 DEBUG_L(PerlIO_printf(Perl_debug_log,
3717 "Locale %s has 8859 in name, not UTF-8 locale\n",
3718 save_input_locale));
3720 goto finish_and_return;
3724 DEBUG_L(PerlIO_printf(Perl_debug_log,
3725 "Assuming locale %s is not a UTF-8 locale\n",
3726 save_input_locale));
3729 # endif /* the code that is compiled when no modern LC_CTYPE */
3733 /* Cache this result so we don't have to go through all this next time. */
3734 utf8ness_cache_size = sizeof(PL_locale_utf8ness)
3735 - (utf8ness_cache - PL_locale_utf8ness);
3737 /* But we can't save it if it is too large for the total space available */
3738 if (LIKELY(input_name_len_with_overhead < utf8ness_cache_size)) {
3739 Size_t utf8ness_cache_len = strlen(utf8ness_cache);
3741 /* Here it can fit, but we may need to clear out the oldest cached
3742 * result(s) to do so. Check */
3743 if (utf8ness_cache_len + input_name_len_with_overhead
3744 >= utf8ness_cache_size)
3746 /* Here we have to clear something out to make room for this.
3747 * Start looking at the rightmost place where it could fit and find
3748 * the beginning of the entry that extends past that. */
3749 char * cutoff = (char *) my_memrchr(utf8ness_cache,
3752 - input_name_len_with_overhead);
3755 assert(cutoff >= utf8ness_cache);
3757 /* This and all subsequent entries must be removed */
3759 utf8ness_cache_len = strlen(utf8ness_cache);
3762 /* Make space for the new entry */
3763 Move(utf8ness_cache,
3764 utf8ness_cache + input_name_len_with_overhead,
3765 utf8ness_cache_len + 1 /* Incl. trailing NUL */, char);
3768 Copy(delimited, utf8ness_cache, input_name_len_with_overhead - 1, char);
3769 utf8ness_cache[input_name_len_with_overhead - 1] = is_utf8 + '0';
3771 if ((PL_locale_utf8ness[strlen(PL_locale_utf8ness)-1]
3772 & (PERL_UINTMAX_T) ~1) != '0')
3775 "panic: %s: %d: Corrupt utf8ness_cache=%s\nlen=%zu,"
3776 " inserted_name=%s, its_len=%zu\n",
3778 PL_locale_utf8ness, strlen(PL_locale_utf8ness),
3779 delimited, input_name_len_with_overhead);
3785 if (DEBUG_Lv_TEST) {
3786 const char * s = PL_locale_utf8ness;
3788 /* Audit the structure */
3789 while (s < PL_locale_utf8ness + strlen(PL_locale_utf8ness)) {
3792 if (*s != UTF8NESS_SEP[0]) {
3794 "panic: %s: %d: Corrupt utf8ness_cache: missing"
3795 " separator %.*s<-- HERE %s\n",
3797 (int) (s - PL_locale_utf8ness), PL_locale_utf8ness,
3801 e = strchr(s, UTF8NESS_PREFIX[0]);
3804 "panic: %s: %d: Corrupt utf8ness_cache: missing"
3805 " separator %.*s<-- HERE %s\n",
3807 (int) (e - PL_locale_utf8ness), PL_locale_utf8ness,
3811 if (*e != '0' && *e != '1') {
3813 "panic: %s: %d: Corrupt utf8ness_cache: utf8ness"
3814 " must be [01] %.*s<-- HERE %s\n",
3816 (int) (e + 1 - PL_locale_utf8ness),
3817 PL_locale_utf8ness, e + 1);
3819 if (ninstr(PL_locale_utf8ness, s, s-1, e)) {
3821 "panic: %s: %d: Corrupt utf8ness_cache: entry"
3822 " has duplicate %.*s<-- HERE %s\n",
3824 (int) (e - PL_locale_utf8ness), PL_locale_utf8ness,
3831 if (DEBUG_Lv_TEST || debug_initialization) {
3833 PerlIO_printf(Perl_debug_log,
3834 "PL_locale_utf8ness is now %s; returning %d\n",
3835 PL_locale_utf8ness, is_utf8);
3840 Safefree(delimited);
3841 Safefree(save_input_locale);
3848 Perl__is_in_locale_category(pTHX_ const bool compiling, const int category)
3851 /* Internal function which returns if we are in the scope of a pragma that
3852 * enables the locale category 'category'. 'compiling' should indicate if
3853 * this is during the compilation phase (TRUE) or not (FALSE). */
3855 const COP * const cop = (compiling) ? &PL_compiling : PL_curcop;
3857 SV *categories = cop_hints_fetch_pvs(cop, "locale", 0);
3858 if (! categories || categories == &PL_sv_placeholder) {
3862 /* The pseudo-category 'not_characters' is -1, so just add 1 to each to get
3863 * a valid unsigned */
3864 assert(category >= -1);
3865 return cBOOL(SvUV(categories) & (1U << (category + 1)));
3869 Perl_my_strerror(pTHX_ const int errnum)
3871 /* Returns a mortalized copy of the text of the error message associated
3872 * with 'errnum'. It uses the current locale's text unless the platform
3873 * doesn't have the LC_MESSAGES category or we are not being called from
3874 * within the scope of 'use locale'. In the former case, it uses whatever
3875 * strerror returns; in the latter case it uses the text from the C locale.
3877 * The function just calls strerror(), but temporarily switches, if needed,
3878 * to the C locale */
3883 #ifndef USE_LOCALE_MESSAGES
3885 /* If platform doesn't have messages category, we don't do any switching to
3886 * the C locale; we just use whatever strerror() returns */
3888 errstr = savepv(Strerror(errnum));
3890 #else /* Has locale messages */
3892 const bool within_locale_scope = IN_LC(LC_MESSAGES);
3894 # if defined(HAS_POSIX_2008_LOCALE) && defined(HAS_STRERROR_L)
3896 /* This function is trivial if we don't have to worry about thread safety
3897 * and have strerror_l(), as it handles the switch of locales so we don't
3898 * have to deal with that. We don't have to worry about thread safety if
3899 * this is an unthreaded build, or if strerror_r() is also available. Both
3900 * it and strerror_l() are thread-safe. Plain strerror() isn't thread
3901 * safe. But on threaded builds when strerror_r() is available, the
3902 * apparent call to strerror() below is actually a macro that
3903 * behind-the-scenes calls strerror_r().
3906 # if ! defined(USE_ITHREADS) || defined(HAS_STRERROR_R)
3908 if (within_locale_scope) {
3909 errstr = savepv(strerror(errnum));
3912 errstr = savepv(strerror_l(errnum, PL_C_locale_obj));
3917 /* Here we have strerror_l(), but not strerror_r() and we are on a
3918 * threaded-build. We use strerror_l() for everything, constructing a
3919 * locale to pass to it if necessary */
3921 bool do_free = FALSE;
3922 locale_t locale_to_use;
3924 if (within_locale_scope) {
3925 locale_to_use = uselocale((locale_t) 0);
3926 if (locale_to_use == LC_GLOBAL_LOCALE) {
3927 locale_to_use = duplocale(LC_GLOBAL_LOCALE);
3931 else { /* Use C locale if not within 'use locale' scope */
3932 locale_to_use = PL_C_locale_obj;
3935 errstr = savepv(strerror_l(errnum, locale_to_use));
3938 freelocale(locale_to_use);
3942 # else /* Doesn't have strerror_l() */
3944 # ifdef USE_POSIX_2008_LOCALE
3946 locale_t save_locale = NULL;
3950 const char * save_locale = NULL;
3951 bool locale_is_C = FALSE;
3953 /* We have a critical section to prevent another thread from executing this
3954 * same code at the same time. (On unthreaded perls, the LOCK is a
3955 * no-op.) Since this is the only place in core that changes LC_MESSAGES
3956 * (unless the user has called setlocale(), this works to prevent races. */
3961 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3962 "my_strerror called with errnum %d\n", errnum));
3963 if (! within_locale_scope) {
3966 # ifdef USE_POSIX_2008_LOCALE /* Use the thread-safe locale functions */
3968 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3969 "Not within locale scope, about to call"
3970 " uselocale(0x%p)\n", PL_C_locale_obj));
3971 save_locale = uselocale(PL_C_locale_obj);
3972 if (! save_locale) {
3973 DEBUG_L(PerlIO_printf(Perl_debug_log,
3974 "uselocale failed, errno=%d\n", errno));
3977 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3978 "uselocale returned 0x%p\n", save_locale));
3981 # else /* Not thread-safe build */
3983 save_locale = do_setlocale_c(LC_MESSAGES, NULL);
3984 if (! save_locale) {
3986 "panic: %s: %d: Could not find current LC_MESSAGES locale,"
3987 " errno=%d\n", __FILE__, __LINE__, errno);
3990 locale_is_C = isNAME_C_OR_POSIX(save_locale);
3992 /* Switch to the C locale if not already in it */
3993 if (! locale_is_C) {
3995 /* The setlocale() just below likely will zap 'save_locale', so
3997 save_locale = savepv(save_locale);
3998 do_setlocale_c(LC_MESSAGES, "C");
4004 } /* end of ! within_locale_scope */
4006 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s: %d: WITHIN locale scope\n",
4007 __FILE__, __LINE__));
4010 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
4011 "Any locale change has been done; about to call Strerror\n"));
4012 errstr = savepv(Strerror(errnum));
4014 if (! within_locale_scope) {
4017 # ifdef USE_POSIX_2008_LOCALE
4019 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
4020 "%s: %d: not within locale scope, restoring the locale\n",
4021 __FILE__, __LINE__));
4022 if (save_locale && ! uselocale(save_locale)) {
4023 DEBUG_L(PerlIO_printf(Perl_debug_log,
4024 "uselocale restore failed, errno=%d\n", errno));
4030 if (save_locale && ! locale_is_C) {
4031 if (! do_setlocale_c(LC_MESSAGES, save_locale)) {
4033 "panic: %s: %d: setlocale restore failed, errno=%d\n",
4034 __FILE__, __LINE__, errno);
4036 Safefree(save_locale);
4043 # endif /* End of doesn't have strerror_l */
4044 #endif /* End of does have locale messages */
4048 if (DEBUG_Lv_TEST) {
4049 PerlIO_printf(Perl_debug_log, "Strerror returned; saving a copy: '");
4050 print_bytes_for_locale(errstr, errstr + strlen(errstr), 0);
4051 PerlIO_printf(Perl_debug_log, "'\n");
4062 =for apidoc sync_locale
4064 Changing the program's locale should be avoided by XS code. Nevertheless,
4065 certain non-Perl libraries called from XS, such as C<Gtk> do so. When this
4066 happens, Perl needs to be told that the locale has changed. Use this function
4067 to do so, before returning to Perl.
4073 Perl_sync_locale(pTHX)
4077 #ifdef USE_LOCALE_CTYPE
4079 newlocale = do_setlocale_c(LC_CTYPE, NULL);
4080 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
4081 "%s:%d: %s\n", __FILE__, __LINE__,
4082 setlocale_debug_string(LC_CTYPE, NULL, newlocale)));
4083 new_ctype(newlocale);
4085 #endif /* USE_LOCALE_CTYPE */
4086 #ifdef USE_LOCALE_COLLATE
4088 newlocale = do_setlocale_c(LC_COLLATE, NULL);
4089 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
4090 "%s:%d: %s\n", __FILE__, __LINE__,
4091 setlocale_debug_string(LC_COLLATE, NULL, newlocale)));
4092 new_collate(newlocale);
4095 #ifdef USE_LOCALE_NUMERIC
4097 newlocale = do_setlocale_c(LC_NUMERIC, NULL);
4098 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
4099 "%s:%d: %s\n", __FILE__, __LINE__,
4100 setlocale_debug_string(LC_NUMERIC, NULL, newlocale)));
4101 new_numeric(newlocale);
4103 #endif /* USE_LOCALE_NUMERIC */
4107 #if defined(DEBUGGING) && defined(USE_LOCALE)
4110 S_setlocale_debug_string(const int category, /* category number,
4112 const char* const locale, /* locale name */
4114 /* return value from setlocale() when attempting to
4115 * set 'category' to 'locale' */
4116 const char* const retval)
4118 /* Returns a pointer to a NUL-terminated string in static storage with
4119 * added text about the info passed in. This is not thread safe and will
4120 * be overwritten by the next call, so this should be used just to
4121 * formulate a string to immediately print or savepv() on. */
4123 /* initialise to a non-null value to keep it out of BSS and so keep
4124 * -DPERL_GLOBAL_STRUCT_PRIVATE happy */
4125 static char ret[128] = "If you can read this, thank your buggy C"
4126 " library strlcpy(), and change your hints file"
4129 my_strlcpy(ret, "setlocale(", sizeof(ret));
4130 my_strlcat(ret, category_name(category), sizeof(ret));
4131 my_strlcat(ret, ", ", sizeof(ret));
4134 my_strlcat(ret, "\"", sizeof(ret));
4135 my_strlcat(ret, locale, sizeof(ret));
4136 my_strlcat(ret, "\"", sizeof(ret));
4139 my_strlcat(ret, "NULL", sizeof(ret));
4142 my_strlcat(ret, ") returned ", sizeof(ret));
4145 my_strlcat(ret, "\"", sizeof(ret));
4146 my_strlcat(ret, retval, sizeof(ret));
4147 my_strlcat(ret, "\"", sizeof(ret));
4150 my_strlcat(ret, "NULL", sizeof(ret));
4153 assert(strlen(ret) < sizeof(ret));
4162 * ex: set ts=8 sts=4 sw=4 et: