3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
4 * 2002, 2003, 2005, 2006, 2007, 2008 by Larry Wall and others
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
12 * A Elbereth Gilthoniel,
13 * silivren penna míriel
14 * o menel aglar elenath!
15 * Na-chaered palan-díriel
16 * o galadhremmin ennorath,
17 * Fanuilos, le linnathon
18 * nef aear, si nef aearon!
20 * [p.238 of _The Lord of the Rings_, II/i: "Many Meetings"]
23 /* utility functions for handling locale-specific stuff like what
24 * character represents the decimal point.
26 * All C programs have an underlying locale. Perl generally doesn't pay any
27 * attention to it except within the scope of a 'use locale'. For most
28 * categories, it accomplishes this by just using different operations if it is
29 * in such scope than if not. However, various libc functions called by Perl
30 * are affected by the LC_NUMERIC category, so there are macros in perl.h that
31 * are used to toggle between the current locale and the C locale depending on
32 * the desired behavior of those functions at the moment. And, LC_MESSAGES is
33 * switched to the C locale for outputting the message unless within the scope
38 #define PERL_IN_LOCALE_C
42 # include <langinfo.h>
47 /* If the environment says to, we can output debugging information during
48 * initialization. This is done before option parsing, and before any thread
49 * creation, so can be a file-level static */
51 # ifdef PERL_GLOBAL_STRUCT
52 /* no global syms allowed */
53 # define debug_initialization 0
54 # define DEBUG_INITIALIZATION_set(v)
56 static bool debug_initialization = FALSE;
57 # define DEBUG_INITIALIZATION_set(v) (debug_initialization = v)
64 * Standardize the locale name from a string returned by 'setlocale', possibly
65 * modifying that string.
67 * The typical return value of setlocale() is either
68 * (1) "xx_YY" if the first argument of setlocale() is not LC_ALL
69 * (2) "xa_YY xb_YY ..." if the first argument of setlocale() is LC_ALL
70 * (the space-separated values represent the various sublocales,
71 * in some unspecified order). This is not handled by this function.
73 * In some platforms it has a form like "LC_SOMETHING=Lang_Country.866\n",
74 * which is harmful for further use of the string in setlocale(). This
75 * function removes the trailing new line and everything up through the '='
79 S_stdize_locale(pTHX_ char *locs)
81 const char * const s = strchr(locs, '=');
84 PERL_ARGS_ASSERT_STDIZE_LOCALE;
87 const char * const t = strchr(s, '.');
90 const char * const u = strchr(t, '\n');
91 if (u && (u[1] == 0)) {
92 const STRLEN len = u - s;
93 Move(s + 1, locs, len, char);
101 Perl_croak(aTHX_ "Can't fix broken locale name \"%s\"", locs);
109 Perl_set_numeric_radix(pTHX)
111 #ifdef USE_LOCALE_NUMERIC
112 # ifdef HAS_LOCALECONV
113 const struct lconv* const lc = localeconv();
115 if (lc && lc->decimal_point) {
116 if (lc->decimal_point[0] == '.' && lc->decimal_point[1] == 0) {
117 SvREFCNT_dec(PL_numeric_radix_sv);
118 PL_numeric_radix_sv = NULL;
121 if (PL_numeric_radix_sv)
122 sv_setpv(PL_numeric_radix_sv, lc->decimal_point);
124 PL_numeric_radix_sv = newSVpv(lc->decimal_point, 0);
125 if (! is_utf8_invariant_string((U8 *) lc->decimal_point, 0)
126 && is_utf8_string((U8 *) lc->decimal_point, 0)
127 && _is_cur_LC_category_utf8(LC_NUMERIC))
129 SvUTF8_on(PL_numeric_radix_sv);
134 PL_numeric_radix_sv = NULL;
137 if (DEBUG_L_TEST || debug_initialization) {
138 PerlIO_printf(Perl_debug_log, "Locale radix is '%s', ?UTF-8=%d\n",
139 (PL_numeric_radix_sv)
140 ? SvPVX(PL_numeric_radix_sv)
142 (PL_numeric_radix_sv)
143 ? cBOOL(SvUTF8(PL_numeric_radix_sv))
148 # endif /* HAS_LOCALECONV */
149 #endif /* USE_LOCALE_NUMERIC */
152 /* Is the C string input 'name' "C" or "POSIX"? If so, and 'name' is the
153 * return of setlocale(), then this is extremely likely to be the C or POSIX
154 * locale. However, the output of setlocale() is documented to be opaque, but
155 * the odds are extremely small that it would return these two strings for some
156 * other locale. Note that VMS in these two locales includes many non-ASCII
157 * characters as controls and punctuation (below are hex bytes):
158 * cntrl: 00-1F 7F 84-97 9B-9F
159 * punct: 21-2F 3A-40 5B-60 7B-7E A1-A3 A5 A7-AB B0-B3 B5-B7 B9-BD BF-CF D1-DD DF-EF F1-FD
160 * Oddly, none there are listed as alphas, though some represent alphabetics
161 * http://www.nntp.perl.org/group/perl.perl5.porters/2013/02/msg198753.html */
162 #define isNAME_C_OR_POSIX(name) ((name) != NULL \
163 && ((*(name) == 'C' && (*(name + 1)) == '\0') \
164 || strEQ((name), "POSIX")))
167 Perl_new_numeric(pTHX_ const char *newnum)
169 #ifdef USE_LOCALE_NUMERIC
171 /* Called after all libc setlocale() calls affecting LC_NUMERIC, to tell
172 * core Perl this and that 'newnum' is the name of the new locale.
173 * It installs this locale as the current underlying default.
175 * The default locale and the C locale can be toggled between by use of the
176 * set_numeric_local() and set_numeric_standard() functions, which should
177 * probably not be called directly, but only via macros like
178 * SET_NUMERIC_STANDARD() in perl.h.
180 * The toggling is necessary mainly so that a non-dot radix decimal point
181 * character can be output, while allowing internal calculations to use a
184 * This sets several interpreter-level variables:
185 * PL_numeric_name The underlying locale's name: a copy of 'newnum'
186 * PL_numeric_local A boolean indicating if the toggled state is such
187 * that the current locale is the program's underlying
189 * PL_numeric_standard An int indicating if the toggled state is such
190 * that the current locale is the C locale. If non-zero,
191 * it is in C; if > 1, it means it may not be toggled away
193 * Note that both of the last two variables can be true at the same time,
194 * if the underlying locale is C. (Toggling is a no-op under these
197 * Any code changing the locale (outside this file) should use
198 * POSIX::setlocale, which calls this function. Therefore this function
199 * should be called directly only from this file and from
200 * POSIX::setlocale() */
205 Safefree(PL_numeric_name);
206 PL_numeric_name = NULL;
207 PL_numeric_standard = TRUE;
208 PL_numeric_local = TRUE;
212 save_newnum = stdize_locale(savepv(newnum));
214 PL_numeric_standard = isNAME_C_OR_POSIX(save_newnum);
215 PL_numeric_local = TRUE;
217 if (! PL_numeric_name || strNE(PL_numeric_name, save_newnum)) {
218 Safefree(PL_numeric_name);
219 PL_numeric_name = save_newnum;
222 Safefree(save_newnum);
225 /* Keep LC_NUMERIC in the C locale. This is for XS modules, so they don't
226 * have to worry about the radix being a non-dot. (Core operations that
227 * need the underlying locale change to it temporarily). */
228 set_numeric_standard();
233 PERL_UNUSED_ARG(newnum);
234 #endif /* USE_LOCALE_NUMERIC */
238 Perl_set_numeric_standard(pTHX)
240 #ifdef USE_LOCALE_NUMERIC
241 /* Toggle the LC_NUMERIC locale to C. Most code should use the macros like
242 * SET_NUMERIC_STANDARD() in perl.h instead of calling this directly. The
243 * macro avoids calling this routine if toggling isn't necessary according
244 * to our records (which could be wrong if some XS code has changed the
245 * locale behind our back) */
247 setlocale(LC_NUMERIC, "C");
248 PL_numeric_standard = TRUE;
249 PL_numeric_local = isNAME_C_OR_POSIX(PL_numeric_name);
252 if (DEBUG_L_TEST || debug_initialization) {
253 PerlIO_printf(Perl_debug_log,
254 "Underlying LC_NUMERIC locale now is C\n");
258 #endif /* USE_LOCALE_NUMERIC */
262 Perl_set_numeric_local(pTHX)
264 #ifdef USE_LOCALE_NUMERIC
265 /* Toggle the LC_NUMERIC locale to the current underlying default. Most
266 * code should use the macros like SET_NUMERIC_LOCAL() in perl.h instead of
267 * calling this directly. The macro avoids calling this routine if
268 * toggling isn't necessary according to our records (which could be wrong
269 * if some XS code has changed the locale behind our back) */
271 setlocale(LC_NUMERIC, PL_numeric_name);
272 PL_numeric_standard = isNAME_C_OR_POSIX(PL_numeric_name);
273 PL_numeric_local = TRUE;
276 if (DEBUG_L_TEST || debug_initialization) {
277 PerlIO_printf(Perl_debug_log,
278 "Underlying LC_NUMERIC locale now is %s\n",
283 #endif /* USE_LOCALE_NUMERIC */
287 * Set up for a new ctype locale.
290 Perl_new_ctype(pTHX_ const char *newctype)
292 #ifdef USE_LOCALE_CTYPE
294 /* Called after all libc setlocale() calls affecting LC_CTYPE, to tell
295 * core Perl this and that 'newctype' is the name of the new locale.
297 * This function sets up the folding arrays for all 256 bytes, assuming
298 * that tofold() is tolc() since fold case is not a concept in POSIX,
300 * Any code changing the locale (outside this file) should use
301 * POSIX::setlocale, which calls this function. Therefore this function
302 * should be called directly only from this file and from
303 * POSIX::setlocale() */
308 PERL_ARGS_ASSERT_NEW_CTYPE;
310 /* We will replace any bad locale warning with 1) nothing if the new one is
311 * ok; or 2) a new warning for the bad new locale */
312 if (PL_warn_locale) {
313 SvREFCNT_dec_NN(PL_warn_locale);
314 PL_warn_locale = NULL;
317 PL_in_utf8_CTYPE_locale = _is_cur_LC_category_utf8(LC_CTYPE);
319 /* A UTF-8 locale gets standard rules. But note that code still has to
320 * handle this specially because of the three problematic code points */
321 if (PL_in_utf8_CTYPE_locale) {
322 Copy(PL_fold_latin1, PL_fold_locale, 256, U8);
325 /* Assume enough space for every character being bad. 4 spaces each
326 * for the 94 printable characters that are output like "'x' "; and 5
327 * spaces each for "'\\' ", "'\t' ", and "'\n' "; plus a terminating
329 char bad_chars_list[ (94 * 4) + (3 * 5) + 1 ];
331 /* Don't check for problems if we are suppressing the warnings */
332 bool check_for_problems = ckWARN_d(WARN_LOCALE)
333 || UNLIKELY(DEBUG_L_TEST);
334 bool multi_byte_locale = FALSE; /* Assume is a single-byte locale
336 unsigned int bad_count = 0; /* Count of bad characters */
338 for (i = 0; i < 256; i++) {
339 if (isUPPER_LC((U8) i))
340 PL_fold_locale[i] = (U8) toLOWER_LC((U8) i);
341 else if (isLOWER_LC((U8) i))
342 PL_fold_locale[i] = (U8) toUPPER_LC((U8) i);
344 PL_fold_locale[i] = (U8) i;
346 /* If checking for locale problems, see if the native ASCII-range
347 * printables plus \n and \t are in their expected categories in
348 * the new locale. If not, this could mean big trouble, upending
349 * Perl's and most programs' assumptions, like having a
350 * metacharacter with special meaning become a \w. Fortunately,
351 * it's very rare to find locales that aren't supersets of ASCII
352 * nowadays. It isn't a problem for most controls to be changed
353 * into something else; we check only \n and \t, though perhaps \r
354 * could be an issue as well. */
355 if (check_for_problems
356 && (isGRAPH_A(i) || isBLANK_A(i) || i == '\n'))
358 if ((isALPHANUMERIC_A(i) && ! isALPHANUMERIC_LC(i))
359 || (isPUNCT_A(i) && ! isPUNCT_LC(i))
360 || (isBLANK_A(i) && ! isBLANK_LC(i))
361 || (i == '\n' && ! isCNTRL_LC(i)))
363 if (bad_count) { /* Separate multiple entries with a
365 bad_chars_list[bad_count++] = ' ';
367 bad_chars_list[bad_count++] = '\'';
369 bad_chars_list[bad_count++] = (char) i;
372 bad_chars_list[bad_count++] = '\\';
374 bad_chars_list[bad_count++] = 'n';
378 bad_chars_list[bad_count++] = 't';
381 bad_chars_list[bad_count++] = '\'';
382 bad_chars_list[bad_count] = '\0';
388 /* We only handle single-byte locales (outside of UTF-8 ones; so if
389 * this locale requires more than one byte, there are going to be
391 if (check_for_problems && MB_CUR_MAX > 1
393 /* Some platforms return MB_CUR_MAX > 1 for even the "C"
394 * locale. Just assume that the implementation for them (plus
395 * for POSIX) is correct and the > 1 value is spurious. (Since
396 * these are specially handled to never be considered UTF-8
397 * locales, as long as this is the only problem, everything
398 * should work fine */
399 && strNE(newctype, "C") && strNE(newctype, "POSIX"))
401 multi_byte_locale = TRUE;
405 if (bad_count || multi_byte_locale) {
406 PL_warn_locale = Perl_newSVpvf(aTHX_
407 "Locale '%s' may not work well.%s%s%s\n",
410 ? " Some characters in it are not recognized by"
414 ? "\nThe following characters (and maybe others)"
415 " may not have the same meaning as the Perl"
416 " program expects:\n"
422 /* If we are actually in the scope of the locale or are debugging,
423 * output the message now. If not in that scope, we save the
424 * message to be output at the first operation using this locale,
425 * if that actually happens. Most programs don't use locales, so
426 * they are immune to bad ones. */
427 if (IN_LC(LC_CTYPE) || UNLIKELY(DEBUG_L_TEST)) {
429 /* We have to save 'newctype' because the setlocale() just
430 * below may destroy it. The next setlocale() further down
431 * should restore it properly so that the intermediate change
432 * here is transparent to this function's caller */
433 const char * const badlocale = savepv(newctype);
435 setlocale(LC_CTYPE, "C");
437 /* The '0' below suppresses a bogus gcc compiler warning */
438 Perl_warner(aTHX_ packWARN(WARN_LOCALE), SvPVX(PL_warn_locale), 0);
440 setlocale(LC_CTYPE, badlocale);
443 if (IN_LC(LC_CTYPE)) {
444 SvREFCNT_dec_NN(PL_warn_locale);
445 PL_warn_locale = NULL;
451 #endif /* USE_LOCALE_CTYPE */
452 PERL_ARGS_ASSERT_NEW_CTYPE;
453 PERL_UNUSED_ARG(newctype);
458 Perl__warn_problematic_locale()
461 #ifdef USE_LOCALE_CTYPE
465 /* Internal-to-core function that outputs the message in PL_warn_locale,
466 * and then NULLS it. Should be called only through the macro
467 * _CHECK_AND_WARN_PROBLEMATIC_LOCALE */
469 if (PL_warn_locale) {
470 /*GCC_DIAG_IGNORE(-Wformat-security); Didn't work */
471 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
472 SvPVX(PL_warn_locale),
473 0 /* dummy to avoid compiler warning */ );
474 /* GCC_DIAG_RESTORE; */
475 SvREFCNT_dec_NN(PL_warn_locale);
476 PL_warn_locale = NULL;
484 Perl_new_collate(pTHX_ const char *newcoll)
486 #ifdef USE_LOCALE_COLLATE
488 /* Called after all libc setlocale() calls affecting LC_COLLATE, to tell
489 * core Perl this and that 'newcoll' is the name of the new locale.
491 * Any code changing the locale (outside this file) should use
492 * POSIX::setlocale, which calls this function. Therefore this function
493 * should be called directly only from this file and from
494 * POSIX::setlocale().
496 * The design of locale collation is that every locale change is given an
497 * index 'PL_collation_ix'. The first time a string particpates in an
498 * operation that requires collation while locale collation is active, it
499 * is given PERL_MAGIC_collxfrm magic (via sv_collxfrm_flags()). That
500 * magic includes the collation index, and the transformation of the string
501 * by strxfrm(), q.v. That transformation is used when doing comparisons,
502 * instead of the string itself. If a string changes, the magic is
503 * cleared. The next time the locale changes, the index is incremented,
504 * and so we know during a comparison that the transformation is not
505 * necessarily still valid, and so is recomputed. Note that if the locale
506 * changes enough times, the index could wrap (a U32), and it is possible
507 * that a transformation would improperly be considered valid, leading to
511 if (PL_collation_name) {
513 Safefree(PL_collation_name);
514 PL_collation_name = NULL;
516 PL_collation_standard = TRUE;
517 is_standard_collation:
518 PL_collxfrm_base = 0;
519 PL_collxfrm_mult = 2;
520 PL_in_utf8_COLLATE_locale = FALSE;
521 PL_strxfrm_NUL_replacement = '\0';
522 PL_strxfrm_max_cp = 0;
526 /* If this is not the same locale as currently, set the new one up */
527 if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
529 Safefree(PL_collation_name);
530 PL_collation_name = stdize_locale(savepv(newcoll));
531 PL_collation_standard = isNAME_C_OR_POSIX(newcoll);
532 if (PL_collation_standard) {
533 goto is_standard_collation;
536 PL_in_utf8_COLLATE_locale = _is_cur_LC_category_utf8(LC_COLLATE);
537 PL_strxfrm_NUL_replacement = '\0';
538 PL_strxfrm_max_cp = 0;
540 /* A locale collation definition includes primary, secondary, tertiary,
541 * etc. weights for each character. To sort, the primary weights are
542 * used, and only if they compare equal, then the secondary weights are
543 * used, and only if they compare equal, then the tertiary, etc.
545 * strxfrm() works by taking the input string, say ABC, and creating an
546 * output transformed string consisting of first the primary weights,
547 * A¹B¹C¹ followed by the secondary ones, A²B²C²; and then the
548 * tertiary, etc, yielding A¹B¹C¹ A²B²C² A³B³C³ .... Some characters
549 * may not have weights at every level. In our example, let's say B
550 * doesn't have a tertiary weight, and A doesn't have a secondary
551 * weight. The constructed string is then going to be
552 * A¹B¹C¹ B²C² A³C³ ....
553 * This has the desired effect that strcmp() will look at the secondary
554 * or tertiary weights only if the strings compare equal at all higher
555 * priority weights. The spaces shown here, like in
557 * are not just for readability. In the general case, these must
558 * actually be bytes, which we will call here 'separator weights'; and
559 * they must be smaller than any other weight value, but since these
560 * are C strings, only the terminating one can be a NUL (some
561 * implementations may include a non-NUL separator weight just before
562 * the NUL). Implementations tend to reserve 01 for the separator
563 * weights. They are needed so that a shorter string's secondary
564 * weights won't be misconstrued as primary weights of a longer string,
565 * etc. By making them smaller than any other weight, the shorter
566 * string will sort first. (Actually, if all secondary weights are
567 * smaller than all primary ones, there is no need for a separator
568 * weight between those two levels, etc.)
570 * The length of the transformed string is roughly a linear function of
571 * the input string. It's not exactly linear because some characters
572 * don't have weights at all levels. When we call strxfrm() we have to
573 * allocate some memory to hold the transformed string. The
574 * calculations below try to find coefficients 'm' and 'b' for this
575 * locale so that m*x + b equals how much space we need, given the size
576 * of the input string in 'x'. If we calculate too small, we increase
577 * the size as needed, and call strxfrm() again, but it is better to
578 * get it right the first time to avoid wasted expensive string
579 * transformations. */
582 /* We use the string below to find how long the tranformation of it
583 * is. Almost all locales are supersets of ASCII, or at least the
584 * ASCII letters. We use all of them, half upper half lower,
585 * because if we used fewer, we might hit just the ones that are
586 * outliers in a particular locale. Most of the strings being
587 * collated will contain a preponderance of letters, and even if
588 * they are above-ASCII, they are likely to have the same number of
589 * weight levels as the ASCII ones. It turns out that digits tend
590 * to have fewer levels, and some punctuation has more, but those
591 * are relatively sparse in text, and khw believes this gives a
592 * reasonable result, but it could be changed if experience so
594 const char longer[] = "ABCDEFGHIJKLMnopqrstuvwxyz";
595 char * x_longer; /* Transformed 'longer' */
596 Size_t x_len_longer; /* Length of 'x_longer' */
598 char * x_shorter; /* We also transform a substring of 'longer' */
599 Size_t x_len_shorter;
601 /* _mem_collxfrm() is used get the transformation (though here we
602 * are interested only in its length). It is used because it has
603 * the intelligence to handle all cases, but to work, it needs some
604 * values of 'm' and 'b' to get it started. For the purposes of
605 * this calculation we use a very conservative estimate of 'm' and
606 * 'b'. This assumes a weight can be multiple bytes, enough to
607 * hold any UV on the platform, and there are 5 levels, 4 weight
608 * bytes, and a trailing NUL. */
609 PL_collxfrm_base = 5;
610 PL_collxfrm_mult = 5 * sizeof(UV);
612 /* Find out how long the transformation really is */
613 x_longer = _mem_collxfrm(longer,
617 /* We avoid converting to UTF-8 in the
618 * called function by telling it the
619 * string is in UTF-8 if the locale is a
620 * UTF-8 one. Since the string passed
621 * here is invariant under UTF-8, we can
622 * claim it's UTF-8 even though it isn't.
624 PL_in_utf8_COLLATE_locale);
627 /* Find out how long the transformation of a substring of 'longer'
628 * is. Together the lengths of these transformations are
629 * sufficient to calculate 'm' and 'b'. The substring is all of
630 * 'longer' except the first character. This minimizes the chances
631 * of being swayed by outliers */
632 x_shorter = _mem_collxfrm(longer + 1,
635 PL_in_utf8_COLLATE_locale);
638 /* If the results are nonsensical for this simple test, the whole
639 * locale definition is suspect. Mark it so that locale collation
640 * is not active at all for it. XXX Should we warn? */
641 if ( x_len_shorter == 0
643 || x_len_shorter >= x_len_longer)
645 PL_collxfrm_mult = 0;
646 PL_collxfrm_base = 0;
649 SSize_t base; /* Temporary */
651 /* We have both: m * strlen(longer) + b = x_len_longer
652 * m * strlen(shorter) + b = x_len_shorter;
653 * subtracting yields:
654 * m * (strlen(longer) - strlen(shorter))
655 * = x_len_longer - x_len_shorter
656 * But we have set things up so that 'shorter' is 1 byte smaller
657 * than 'longer'. Hence:
658 * m = x_len_longer - x_len_shorter
660 * But if something went wrong, make sure the multiplier is at
663 if (x_len_longer > x_len_shorter) {
664 PL_collxfrm_mult = (STRLEN) x_len_longer - x_len_shorter;
667 PL_collxfrm_mult = 1;
672 * but in case something has gone wrong, make sure it is
674 base = x_len_longer - PL_collxfrm_mult * (sizeof(longer) - 1);
679 /* Add 1 for the trailing NUL */
680 PL_collxfrm_base = base + 1;
684 if (DEBUG_L_TEST || debug_initialization) {
685 PerlIO_printf(Perl_debug_log,
686 "%s:%d: ?UTF-8 locale=%d; x_len_shorter=%zu, "
688 " collate multipler=%zu, collate base=%zu\n",
690 PL_in_utf8_COLLATE_locale,
691 x_len_shorter, x_len_longer,
692 PL_collxfrm_mult, PL_collxfrm_base);
699 PERL_UNUSED_ARG(newcoll);
700 #endif /* USE_LOCALE_COLLATE */
706 Perl_my_setlocale(pTHX_ int category, const char* locale)
708 /* This, for Windows, emulates POSIX setlocale() behavior. There is no
709 * difference unless the input locale is "", which means on Windows to get
710 * the machine default, which is set via the computer's "Regional and
711 * Language Options" (or its current equivalent). In POSIX, it instead
712 * means to find the locale from the user's environment. This routine
713 * looks in the environment, and, if anything is found, uses that instead
714 * of going to the machine default. If there is no environment override,
715 * the machine default is used, as normal, by calling the real setlocale()
716 * with "". The POSIX behavior is to use the LC_ALL variable if set;
717 * otherwise to use the particular category's variable if set; otherwise to
718 * use the LANG variable. */
720 bool override_LC_ALL = FALSE;
723 if (locale && strEQ(locale, "")) {
725 locale = PerlEnv_getenv("LC_ALL");
731 override_LC_ALL = TRUE;
732 break; /* We already know its variable isn't set */
734 # ifdef USE_LOCALE_TIME
736 locale = PerlEnv_getenv("LC_TIME");
739 # ifdef USE_LOCALE_CTYPE
741 locale = PerlEnv_getenv("LC_CTYPE");
744 # ifdef USE_LOCALE_COLLATE
746 locale = PerlEnv_getenv("LC_COLLATE");
749 # ifdef USE_LOCALE_MONETARY
751 locale = PerlEnv_getenv("LC_MONETARY");
754 # ifdef USE_LOCALE_NUMERIC
756 locale = PerlEnv_getenv("LC_NUMERIC");
759 # ifdef USE_LOCALE_MESSAGES
761 locale = PerlEnv_getenv("LC_MESSAGES");
765 /* This is a category, like PAPER_SIZE that we don't
766 * know about; and so can't provide a wrapper. */
770 locale = PerlEnv_getenv("LANG");
780 result = setlocale(category, locale);
781 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n", __FILE__, __LINE__,
782 _setlocale_debug_string(category, locale, result)));
784 if (! override_LC_ALL) {
788 /* Here the input category was LC_ALL, and we have set it to what is in the
789 * LANG variable or the system default if there is no LANG. But these have
790 * lower priority than the other LC_foo variables, so override it for each
791 * one that is set. (If they are set to "", it means to use the same thing
792 * we just set LC_ALL to, so can skip) */
793 # ifdef USE_LOCALE_TIME
794 result = PerlEnv_getenv("LC_TIME");
795 if (result && strNE(result, "")) {
796 setlocale(LC_TIME, result);
797 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
799 _setlocale_debug_string(LC_TIME, result, "not captured")));
802 # ifdef USE_LOCALE_CTYPE
803 result = PerlEnv_getenv("LC_CTYPE");
804 if (result && strNE(result, "")) {
805 setlocale(LC_CTYPE, result);
806 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
808 _setlocale_debug_string(LC_CTYPE, result, "not captured")));
811 # ifdef USE_LOCALE_COLLATE
812 result = PerlEnv_getenv("LC_COLLATE");
813 if (result && strNE(result, "")) {
814 setlocale(LC_COLLATE, result);
815 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
817 _setlocale_debug_string(LC_COLLATE, result, "not captured")));
820 # ifdef USE_LOCALE_MONETARY
821 result = PerlEnv_getenv("LC_MONETARY");
822 if (result && strNE(result, "")) {
823 setlocale(LC_MONETARY, result);
824 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
826 _setlocale_debug_string(LC_MONETARY, result, "not captured")));
829 # ifdef USE_LOCALE_NUMERIC
830 result = PerlEnv_getenv("LC_NUMERIC");
831 if (result && strNE(result, "")) {
832 setlocale(LC_NUMERIC, result);
833 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
835 _setlocale_debug_string(LC_NUMERIC, result, "not captured")));
838 # ifdef USE_LOCALE_MESSAGES
839 result = PerlEnv_getenv("LC_MESSAGES");
840 if (result && strNE(result, "")) {
841 setlocale(LC_MESSAGES, result);
842 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
844 _setlocale_debug_string(LC_MESSAGES, result, "not captured")));
848 result = setlocale(LC_ALL, NULL);
849 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
851 _setlocale_debug_string(LC_ALL, NULL, result)));
860 * Initialize locale awareness.
863 Perl_init_i18nl10n(pTHX_ int printwarn)
867 * 0 if not to output warning when setup locale is bad
868 * 1 if to output warning based on value of PERL_BADLANG
869 * >1 if to output regardless of PERL_BADLANG
872 * 1 = set ok or not applicable,
873 * 0 = fallback to a locale of lower priority
874 * -1 = fallback to all locales failed, not even to the C locale
876 * Under -DDEBUGGING, if the environment variable PERL_DEBUG_LOCALE_INIT is
877 * set, debugging information is output.
879 * This looks more complicated than it is, mainly due to the #ifdefs.
881 * We try to set LC_ALL to the value determined by the environment. If
882 * there is no LC_ALL on this platform, we try the individual categories we
883 * know about. If this works, we are done.
885 * But if it doesn't work, we have to do something else. We search the
886 * environment variables ourselves instead of relying on the system to do
887 * it. We look at, in order, LC_ALL, LANG, a system default locale (if we
888 * think there is one), and the ultimate fallback "C". This is all done in
889 * the same loop as above to avoid duplicating code, but it makes things
890 * more complex. After the original failure, we add the fallback
891 * possibilities to the list of locales to try, and iterate the loop
892 * through them all until one succeeds.
894 * On Ultrix, the locale MUST come from the environment, so there is
895 * preliminary code to set it. I (khw) am not sure that it is necessary,
896 * and that this couldn't be folded into the loop, but barring any real
897 * platforms to test on, it's staying as-is
899 * A slight complication is that in embedded Perls, the locale may already
900 * be set-up, and we don't want to get it from the normal environment
901 * variables. This is handled by having a special environment variable
902 * indicate we're in this situation. We simply set setlocale's 2nd
903 * parameter to be a NULL instead of "". That indicates to setlocale that
904 * it is not to change anything, but to return the current value,
905 * effectively initializing perl's db to what the locale already is.
907 * We play the same trick with NULL if a LC_ALL succeeds. We call
908 * setlocale() on the individual categores with NULL to get their existing
909 * values for our db, instead of trying to change them.
914 #if defined(USE_LOCALE)
915 #ifdef USE_LOCALE_CTYPE
916 char *curctype = NULL;
917 #endif /* USE_LOCALE_CTYPE */
918 #ifdef USE_LOCALE_COLLATE
919 char *curcoll = NULL;
920 #endif /* USE_LOCALE_COLLATE */
921 #ifdef USE_LOCALE_NUMERIC
923 #endif /* USE_LOCALE_NUMERIC */
925 const char * const language = savepv(PerlEnv_getenv("LANGUAGE"));
928 /* NULL uses the existing already set up locale */
929 const char * const setlocale_init = (PerlEnv_getenv("PERL_SKIP_LOCALE_INIT"))
932 const char* trial_locales[5]; /* 5 = 1 each for "", LC_ALL, LANG, "", C */
933 unsigned int trial_locales_count;
934 const char * const lc_all = savepv(PerlEnv_getenv("LC_ALL"));
935 const char * const lang = savepv(PerlEnv_getenv("LANG"));
936 bool setlocale_failure = FALSE;
940 /* A later getenv() could zap this, so only use here */
941 const char * const bad_lang_use_once = PerlEnv_getenv("PERL_BADLANG");
943 const bool locwarn = (printwarn > 1
945 && (! bad_lang_use_once
947 /* disallow with "" or "0" */
949 && strNE("0", bad_lang_use_once)))));
951 char * sl_result; /* return from setlocale() */
954 /* In some systems you can find out the system default locale
955 * and use that as the fallback locale. */
956 # define SYSTEM_DEFAULT_LOCALE
958 #ifdef SYSTEM_DEFAULT_LOCALE
959 const char *system_default_locale = NULL;
963 DEBUG_INITIALIZATION_set(cBOOL(PerlEnv_getenv("PERL_DEBUG_LOCALE_INIT")));
964 # define DEBUG_LOCALE_INIT(category, locale, result) \
966 if (debug_initialization) { \
967 PerlIO_printf(Perl_debug_log, \
969 __FILE__, __LINE__, \
970 _setlocale_debug_string(category, \
976 # define DEBUG_LOCALE_INIT(a,b,c)
979 #ifndef LOCALE_ENVIRON_REQUIRED
980 PERL_UNUSED_VAR(done);
981 PERL_UNUSED_VAR(locale_param);
985 * Ultrix setlocale(..., "") fails if there are no environment
986 * variables from which to get a locale name.
991 sl_result = my_setlocale(LC_ALL, setlocale_init);
992 DEBUG_LOCALE_INIT(LC_ALL, setlocale_init, sl_result);
996 setlocale_failure = TRUE;
998 if (! setlocale_failure) {
999 # ifdef USE_LOCALE_CTYPE
1000 locale_param = (! done && (lang || PerlEnv_getenv("LC_CTYPE")))
1003 curctype = my_setlocale(LC_CTYPE, locale_param);
1004 DEBUG_LOCALE_INIT(LC_CTYPE, locale_param, sl_result);
1006 setlocale_failure = TRUE;
1008 curctype = savepv(curctype);
1009 # endif /* USE_LOCALE_CTYPE */
1010 # ifdef USE_LOCALE_COLLATE
1011 locale_param = (! done && (lang || PerlEnv_getenv("LC_COLLATE")))
1014 curcoll = my_setlocale(LC_COLLATE, locale_param);
1015 DEBUG_LOCALE_INIT(LC_COLLATE, locale_param, sl_result);
1017 setlocale_failure = TRUE;
1019 curcoll = savepv(curcoll);
1020 # endif /* USE_LOCALE_COLLATE */
1021 # ifdef USE_LOCALE_NUMERIC
1022 locale_param = (! done && (lang || PerlEnv_getenv("LC_NUMERIC")))
1025 curnum = my_setlocale(LC_NUMERIC, locale_param);
1026 DEBUG_LOCALE_INIT(LC_NUMERIC, locale_param, sl_result);
1028 setlocale_failure = TRUE;
1030 curnum = savepv(curnum);
1031 # endif /* USE_LOCALE_NUMERIC */
1032 # ifdef USE_LOCALE_MESSAGES
1033 locale_param = (! done && (lang || PerlEnv_getenv("LC_MESSAGES")))
1036 sl_result = my_setlocale(LC_MESSAGES, locale_param);
1037 DEBUG_LOCALE_INIT(LC_MESSAGES, locale_param, sl_result);
1039 setlocale_failure = TRUE;
1041 # endif /* USE_LOCALE_MESSAGES */
1042 # ifdef USE_LOCALE_MONETARY
1043 locale_param = (! done && (lang || PerlEnv_getenv("LC_MONETARY")))
1046 sl_result = my_setlocale(LC_MONETARY, locale_param);
1047 DEBUG_LOCALE_INIT(LC_MONETARY, locale_param, sl_result);
1049 setlocale_failure = TRUE;
1051 # endif /* USE_LOCALE_MONETARY */
1054 # endif /* LC_ALL */
1056 #endif /* !LOCALE_ENVIRON_REQUIRED */
1058 /* We try each locale in the list until we get one that works, or exhaust
1059 * the list. Normally the loop is executed just once. But if setting the
1060 * locale fails, inside the loop we add fallback trials to the array and so
1061 * will execute the loop multiple times */
1062 trial_locales[0] = setlocale_init;
1063 trial_locales_count = 1;
1064 for (i= 0; i < trial_locales_count; i++) {
1065 const char * trial_locale = trial_locales[i];
1069 /* XXX This is to preserve old behavior for LOCALE_ENVIRON_REQUIRED
1070 * when i==0, but I (khw) don't think that behavior makes much
1072 setlocale_failure = FALSE;
1074 #ifdef SYSTEM_DEFAULT_LOCALE
1076 /* On Windows machines, an entry of "" after the 0th means to use
1077 * the system default locale, which we now proceed to get. */
1078 if (strEQ(trial_locale, "")) {
1081 /* Note that this may change the locale, but we are going to do
1082 * that anyway just below */
1083 system_default_locale = setlocale(LC_ALL, "");
1084 DEBUG_LOCALE_INIT(LC_ALL, "", system_default_locale);
1086 /* Skip if invalid or it's already on the list of locales to
1088 if (! system_default_locale) {
1089 goto next_iteration;
1091 for (j = 0; j < trial_locales_count; j++) {
1092 if (strEQ(system_default_locale, trial_locales[j])) {
1093 goto next_iteration;
1097 trial_locale = system_default_locale;
1100 #endif /* SYSTEM_DEFAULT_LOCALE */
1104 sl_result = my_setlocale(LC_ALL, trial_locale);
1105 DEBUG_LOCALE_INIT(LC_ALL, trial_locale, sl_result);
1107 setlocale_failure = TRUE;
1110 /* Since LC_ALL succeeded, it should have changed all the other
1111 * categories it can to its value; so we massage things so that the
1112 * setlocales below just return their category's current values.
1113 * This adequately handles the case in NetBSD where LC_COLLATE may
1114 * not be defined for a locale, and setting it individually will
1115 * fail, whereas setting LC_ALL suceeds, leaving LC_COLLATE set to
1116 * the POSIX locale. */
1117 trial_locale = NULL;
1121 if (!setlocale_failure) {
1122 #ifdef USE_LOCALE_CTYPE
1124 curctype = my_setlocale(LC_CTYPE, trial_locale);
1125 DEBUG_LOCALE_INIT(LC_CTYPE, trial_locale, curctype);
1127 setlocale_failure = TRUE;
1129 curctype = savepv(curctype);
1130 #endif /* USE_LOCALE_CTYPE */
1131 #ifdef USE_LOCALE_COLLATE
1133 curcoll = my_setlocale(LC_COLLATE, trial_locale);
1134 DEBUG_LOCALE_INIT(LC_COLLATE, trial_locale, curcoll);
1136 setlocale_failure = TRUE;
1138 curcoll = savepv(curcoll);
1139 #endif /* USE_LOCALE_COLLATE */
1140 #ifdef USE_LOCALE_NUMERIC
1142 curnum = my_setlocale(LC_NUMERIC, trial_locale);
1143 DEBUG_LOCALE_INIT(LC_NUMERIC, trial_locale, curnum);
1145 setlocale_failure = TRUE;
1147 curnum = savepv(curnum);
1148 #endif /* USE_LOCALE_NUMERIC */
1149 #ifdef USE_LOCALE_MESSAGES
1150 sl_result = my_setlocale(LC_MESSAGES, trial_locale);
1151 DEBUG_LOCALE_INIT(LC_MESSAGES, trial_locale, sl_result);
1153 setlocale_failure = TRUE;
1154 #endif /* USE_LOCALE_MESSAGES */
1155 #ifdef USE_LOCALE_MONETARY
1156 sl_result = my_setlocale(LC_MONETARY, trial_locale);
1157 DEBUG_LOCALE_INIT(LC_MONETARY, trial_locale, sl_result);
1159 setlocale_failure = TRUE;
1160 #endif /* USE_LOCALE_MONETARY */
1162 if (! setlocale_failure) { /* Success */
1167 /* Here, something failed; will need to try a fallback. */
1173 if (locwarn) { /* Output failure info only on the first one */
1176 PerlIO_printf(Perl_error_log,
1177 "perl: warning: Setting locale failed.\n");
1181 PerlIO_printf(Perl_error_log,
1182 "perl: warning: Setting locale failed for the categories:\n\t");
1183 # ifdef USE_LOCALE_CTYPE
1185 PerlIO_printf(Perl_error_log, "LC_CTYPE ");
1186 # endif /* USE_LOCALE_CTYPE */
1187 # ifdef USE_LOCALE_COLLATE
1189 PerlIO_printf(Perl_error_log, "LC_COLLATE ");
1190 # endif /* USE_LOCALE_COLLATE */
1191 # ifdef USE_LOCALE_NUMERIC
1193 PerlIO_printf(Perl_error_log, "LC_NUMERIC ");
1194 # endif /* USE_LOCALE_NUMERIC */
1195 PerlIO_printf(Perl_error_log, "and possibly others\n");
1199 PerlIO_printf(Perl_error_log,
1200 "perl: warning: Please check that your locale settings:\n");
1203 PerlIO_printf(Perl_error_log,
1204 "\tLANGUAGE = %c%s%c,\n",
1205 language ? '"' : '(',
1206 language ? language : "unset",
1207 language ? '"' : ')');
1210 PerlIO_printf(Perl_error_log,
1211 "\tLC_ALL = %c%s%c,\n",
1213 lc_all ? lc_all : "unset",
1214 lc_all ? '"' : ')');
1216 #if defined(USE_ENVIRON_ARRAY)
1219 for (e = environ; *e; e++) {
1220 if (strEQs(*e, "LC_")
1221 && strNEs(*e, "LC_ALL=")
1222 && (p = strchr(*e, '=')))
1223 PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
1224 (int)(p - *e), *e, p + 1);
1228 PerlIO_printf(Perl_error_log,
1229 "\t(possibly more locale environment variables)\n");
1232 PerlIO_printf(Perl_error_log,
1233 "\tLANG = %c%s%c\n",
1235 lang ? lang : "unset",
1238 PerlIO_printf(Perl_error_log,
1239 " are supported and installed on your system.\n");
1242 /* Calculate what fallback locales to try. We have avoided this
1243 * until we have to, because failure is quite unlikely. This will
1244 * usually change the upper bound of the loop we are in.
1246 * Since the system's default way of setting the locale has not
1247 * found one that works, We use Perl's defined ordering: LC_ALL,
1248 * LANG, and the C locale. We don't try the same locale twice, so
1249 * don't add to the list if already there. (On POSIX systems, the
1250 * LC_ALL element will likely be a repeat of the 0th element "",
1251 * but there's no harm done by doing it explicitly.
1253 * Note that this tries the LC_ALL environment variable even on
1254 * systems which have no LC_ALL locale setting. This may or may
1255 * not have been originally intentional, but there's no real need
1256 * to change the behavior. */
1258 for (j = 0; j < trial_locales_count; j++) {
1259 if (strEQ(lc_all, trial_locales[j])) {
1263 trial_locales[trial_locales_count++] = lc_all;
1268 for (j = 0; j < trial_locales_count; j++) {
1269 if (strEQ(lang, trial_locales[j])) {
1273 trial_locales[trial_locales_count++] = lang;
1277 #if defined(WIN32) && defined(LC_ALL)
1278 /* For Windows, we also try the system default locale before "C".
1279 * (If there exists a Windows without LC_ALL we skip this because
1280 * it gets too complicated. For those, the "C" is the next
1281 * fallback possibility). The "" is the same as the 0th element of
1282 * the array, but the code at the loop above knows to treat it
1283 * differently when not the 0th */
1284 trial_locales[trial_locales_count++] = "";
1287 for (j = 0; j < trial_locales_count; j++) {
1288 if (strEQ("C", trial_locales[j])) {
1292 trial_locales[trial_locales_count++] = "C";
1295 } /* end of first time through the loop */
1301 } /* end of looping through the trial locales */
1303 if (ok < 1) { /* If we tried to fallback */
1305 if (! setlocale_failure) { /* fallback succeeded */
1306 msg = "Falling back to";
1308 else { /* fallback failed */
1310 /* We dropped off the end of the loop, so have to decrement i to
1311 * get back to the value the last time through */
1315 msg = "Failed to fall back to";
1317 /* To continue, we should use whatever values we've got */
1318 #ifdef USE_LOCALE_CTYPE
1320 curctype = savepv(setlocale(LC_CTYPE, NULL));
1321 DEBUG_LOCALE_INIT(LC_CTYPE, NULL, curctype);
1322 #endif /* USE_LOCALE_CTYPE */
1323 #ifdef USE_LOCALE_COLLATE
1325 curcoll = savepv(setlocale(LC_COLLATE, NULL));
1326 DEBUG_LOCALE_INIT(LC_COLLATE, NULL, curcoll);
1327 #endif /* USE_LOCALE_COLLATE */
1328 #ifdef USE_LOCALE_NUMERIC
1330 curnum = savepv(setlocale(LC_NUMERIC, NULL));
1331 DEBUG_LOCALE_INIT(LC_NUMERIC, NULL, curnum);
1332 #endif /* USE_LOCALE_NUMERIC */
1336 const char * description;
1337 const char * name = "";
1338 if (strEQ(trial_locales[i], "C")) {
1339 description = "the standard locale";
1342 #ifdef SYSTEM_DEFAULT_LOCALE
1343 else if (strEQ(trial_locales[i], "")) {
1344 description = "the system default locale";
1345 if (system_default_locale) {
1346 name = system_default_locale;
1349 #endif /* SYSTEM_DEFAULT_LOCALE */
1351 description = "a fallback locale";
1352 name = trial_locales[i];
1354 if (name && strNE(name, "")) {
1355 PerlIO_printf(Perl_error_log,
1356 "perl: warning: %s %s (\"%s\").\n", msg, description, name);
1359 PerlIO_printf(Perl_error_log,
1360 "perl: warning: %s %s.\n", msg, description);
1363 } /* End of tried to fallback */
1365 #ifdef USE_LOCALE_CTYPE
1366 new_ctype(curctype);
1367 #endif /* USE_LOCALE_CTYPE */
1369 #ifdef USE_LOCALE_COLLATE
1370 new_collate(curcoll);
1371 #endif /* USE_LOCALE_COLLATE */
1373 #ifdef USE_LOCALE_NUMERIC
1374 new_numeric(curnum);
1375 #endif /* USE_LOCALE_NUMERIC */
1377 #if defined(USE_PERLIO) && defined(USE_LOCALE_CTYPE)
1378 /* Set PL_utf8locale to TRUE if using PerlIO _and_ the current LC_CTYPE
1379 * locale is UTF-8. If PL_utf8locale and PL_unicode (set by -C or by
1380 * $ENV{PERL_UNICODE}) are true, perl.c:S_parse_body() will turn on the
1381 * PerlIO :utf8 layer on STDIN, STDOUT, STDERR, _and_ the default open
1383 PL_utf8locale = _is_cur_LC_category_utf8(LC_CTYPE);
1385 /* Set PL_unicode to $ENV{PERL_UNICODE} if using PerlIO.
1386 This is an alternative to using the -C command line switch
1387 (the -C if present will override this). */
1389 const char *p = PerlEnv_getenv("PERL_UNICODE");
1390 PL_unicode = p ? parse_unicode_opts(&p) : 0;
1391 if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
1396 #ifdef USE_LOCALE_CTYPE
1398 #endif /* USE_LOCALE_CTYPE */
1399 #ifdef USE_LOCALE_COLLATE
1401 #endif /* USE_LOCALE_COLLATE */
1402 #ifdef USE_LOCALE_NUMERIC
1404 #endif /* USE_LOCALE_NUMERIC */
1413 #else /* !USE_LOCALE */
1414 PERL_UNUSED_ARG(printwarn);
1415 #endif /* USE_LOCALE */
1418 /* So won't continue to output stuff */
1419 DEBUG_INITIALIZATION_set(FALSE);
1425 #ifdef USE_LOCALE_COLLATE
1428 Perl__mem_collxfrm(pTHX_ const char *input_string,
1429 STRLEN len, /* Length of 'input_string' */
1430 STRLEN *xlen, /* Set to length of returned string
1431 (not including the collation index
1433 bool utf8 /* Is the input in UTF-8? */
1437 /* _mem_collxfrm() is a bit like strxfrm() but with two important
1438 * differences. First, it handles embedded NULs. Second, it allocates a bit
1439 * more memory than needed for the transformed data itself. The real
1440 * transformed data begins at offset COLLXFRM_HDR_LEN. *xlen is set to
1441 * the length of that, and doesn't include the collation index size.
1442 * Please see sv_collxfrm() to see how this is used. */
1444 #define COLLXFRM_HDR_LEN sizeof(PL_collation_ix)
1446 char * s = (char *) input_string;
1447 STRLEN s_strlen = strlen(input_string);
1449 STRLEN xAlloc; /* xalloc is a reserved word in VC */
1450 STRLEN length_in_chars;
1451 bool first_time = TRUE; /* Cleared after first loop iteration */
1453 PERL_ARGS_ASSERT__MEM_COLLXFRM;
1455 /* Must be NUL-terminated */
1456 assert(*(input_string + len) == '\0');
1458 /* If this locale has defective collation, skip */
1459 if (PL_collxfrm_base == 0 && PL_collxfrm_mult == 0) {
1460 DEBUG_L(PerlIO_printf(Perl_debug_log,
1461 "_mem_collxfrm: locale's collation is defective\n"));
1465 /* Replace any embedded NULs with the control that sorts before any others.
1466 * This will give as good as possible results on strings that don't
1467 * otherwise contain that character, but otherwise there may be
1468 * less-than-perfect results with that character and NUL. This is
1469 * unavoidable unless we replace strxfrm with our own implementation. */
1470 if (s_strlen < len) { /* Only execute if there is an embedded NUL */
1473 STRLEN sans_nuls_len;
1474 STRLEN sans_nuls_pos;
1475 int try_non_controls;
1476 char this_replacement_char[] = "?\0"; /* Room for a two-byte string,
1477 making sure 2nd byte is NUL.
1479 STRLEN this_replacement_len;
1481 /* If we don't know what non-NUL control character sorts lowest for
1482 * this locale, find it */
1483 if (PL_strxfrm_NUL_replacement == '\0') {
1485 char * cur_min_x = NULL; /* The min_char's xfrm, (except it also
1486 includes the collation index
1489 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "Looking to replace NUL\n"));
1491 /* Unlikely, but it may be that no control will work to replace
1492 * NUL, in which case we instead look for any character. Controls
1493 * are preferred because collation order is, in general, context
1494 * sensitive, with adjoining characters affecting the order, and
1495 * controls are less likely to have such interactions, allowing the
1496 * NUL-replacement to stand on its own. (Another way to look at it
1497 * is to imagine what would happen if the NUL were replaced by a
1498 * combining character; it wouldn't work out all that well.) */
1499 for (try_non_controls = 0;
1500 try_non_controls < 2;
1503 /* Look through all legal code points (NUL isn't) */
1504 for (j = 1; j < 256; j++) {
1505 char * x; /* j's xfrm plus collation index */
1506 STRLEN x_len; /* length of 'x' */
1507 STRLEN trial_len = 1;
1508 char cur_source[] = { '\0', '\0' };
1510 /* Skip non-controls the first time through the loop. The
1511 * controls in a UTF-8 locale are the L1 ones */
1512 if (! try_non_controls && (PL_in_utf8_COLLATE_locale)
1519 /* Create a 1-char string of the current code point */
1520 cur_source[0] = (char) j;
1522 /* Then transform it */
1523 x = _mem_collxfrm(cur_source, trial_len, &x_len,
1524 0 /* The string is not in UTF-8 */);
1526 /* Ignore any character that didn't successfully transform.
1532 /* If this character's transformation is lower than
1533 * the current lowest, this one becomes the lowest */
1534 if ( cur_min_x == NULL
1535 || strLT(x + COLLXFRM_HDR_LEN,
1536 cur_min_x + COLLXFRM_HDR_LEN))
1538 PL_strxfrm_NUL_replacement = j;
1544 } /* end of loop through all 255 characters */
1546 /* Stop looking if found */
1551 /* Unlikely, but possible, if there aren't any controls that
1552 * work in the locale, repeat the loop, looking for any
1553 * character that works */
1554 DEBUG_L(PerlIO_printf(Perl_debug_log,
1555 "_mem_collxfrm: No control worked. Trying non-controls\n"));
1556 } /* End of loop to try first the controls, then any char */
1559 DEBUG_L(PerlIO_printf(Perl_debug_log,
1560 "_mem_collxfrm: Couldn't find any character to replace"
1561 " embedded NULs in locale %s with", PL_collation_name));
1565 DEBUG_L(PerlIO_printf(Perl_debug_log,
1566 "_mem_collxfrm: Replacing embedded NULs in locale %s with "
1567 "0x%02X\n", PL_collation_name, PL_strxfrm_NUL_replacement));
1569 Safefree(cur_min_x);
1570 } /* End of determining the character that is to replace NULs */
1572 /* If the replacement is variant under UTF-8, it must match the
1573 * UTF8-ness as the original */
1574 if ( ! UVCHR_IS_INVARIANT(PL_strxfrm_NUL_replacement) && utf8) {
1575 this_replacement_char[0] =
1576 UTF8_EIGHT_BIT_HI(PL_strxfrm_NUL_replacement);
1577 this_replacement_char[1] =
1578 UTF8_EIGHT_BIT_LO(PL_strxfrm_NUL_replacement);
1579 this_replacement_len = 2;
1582 this_replacement_char[0] = PL_strxfrm_NUL_replacement;
1583 /* this_replacement_char[1] = '\0' was done at initialization */
1584 this_replacement_len = 1;
1587 /* The worst case length for the replaced string would be if every
1588 * character in it is NUL. Multiply that by the length of each
1589 * replacement, and allow for a trailing NUL */
1590 sans_nuls_len = (len * this_replacement_len) + 1;
1591 Newx(sans_nuls, sans_nuls_len, char);
1595 /* Replace each NUL with the lowest collating control. Loop until have
1596 * exhausted all the NULs */
1597 while (s + s_strlen < e) {
1598 sans_nuls_pos = my_strlcat(sans_nuls + sans_nuls_pos,
1602 /* Do the actual replacement */
1603 sans_nuls_pos = my_strlcat(sans_nuls + sans_nuls_pos,
1604 this_replacement_char,
1607 /* Move past the input NUL */
1609 s_strlen = strlen(s);
1612 /* And add anything that trails the final NUL */
1613 my_strlcat(sans_nuls + sans_nuls_pos, s, sans_nuls_len);
1615 /* Switch so below we transform this modified string */
1618 } /* End of replacing NULs */
1620 /* Make sure the UTF8ness of the string and locale match */
1621 if (utf8 != PL_in_utf8_COLLATE_locale) {
1622 const char * const t = s; /* Temporary so we can later find where the
1625 /* Here they don't match. Change the string's to be what the locale is
1628 if (! utf8) { /* locale is UTF-8, but input isn't; upgrade the input */
1629 s = (char *) bytes_to_utf8((const U8 *) s, &len);
1632 else { /* locale is not UTF-8; but input is; downgrade the input */
1634 s = (char *) bytes_from_utf8((const U8 *) s, &len, &utf8);
1636 /* If the downgrade was successful we are done, but if the input
1637 * contains things that require UTF-8 to represent, have to do
1638 * damage control ... */
1639 if (UNLIKELY(utf8)) {
1641 /* What we do is construct a non-UTF-8 string with
1642 * 1) the characters representable by a single byte converted
1643 * to be so (if necessary);
1644 * 2) and the rest converted to collate the same as the
1645 * highest collating representable character. That makes
1646 * them collate at the end. This is similar to how we
1647 * handle embedded NULs, but we use the highest collating
1648 * code point instead of the smallest. Like the NUL case,
1649 * this isn't perfect, but is the best we can reasonably
1650 * do. Every above-255 code point will sort the same as
1651 * the highest-sorting 0-255 code point. If that code
1652 * point can combine in a sequence with some other code
1653 * points for weight calculations, us changing something to
1654 * be it can adversely affect the results. But in most
1655 * cases, it should work reasonably. And note that this is
1656 * really an illegal situation: using code points above 255
1657 * on a locale where only 0-255 are valid. If two strings
1658 * sort entirely equal, then the sort order for the
1659 * above-255 code points will be in code point order. */
1663 /* If we haven't calculated the code point with the maximum
1664 * collating order for this locale, do so now */
1665 if (! PL_strxfrm_max_cp) {
1668 /* The current transformed string that collates the
1669 * highest (except it also includes the prefixed collation
1671 char * cur_max_x = NULL;
1673 /* Look through all legal code points (NUL isn't) */
1674 for (j = 1; j < 256; j++) {
1677 char cur_source[] = { '\0', '\0' };
1679 /* Create a 1-char string of the current code point */
1680 cur_source[0] = (char) j;
1682 /* Then transform it */
1683 x = _mem_collxfrm(cur_source, 1, &x_len, FALSE);
1685 /* If something went wrong (which it shouldn't), just
1686 * ignore this code point */
1691 /* If this character's transformation is higher than
1692 * the current highest, this one becomes the highest */
1693 if ( cur_max_x == NULL
1694 || strGT(x + COLLXFRM_HDR_LEN,
1695 cur_max_x + COLLXFRM_HDR_LEN))
1697 PL_strxfrm_max_cp = j;
1706 DEBUG_L(PerlIO_printf(Perl_debug_log,
1707 "_mem_collxfrm: Couldn't find any character to"
1708 " replace above-Latin1 chars in locale %s with",
1709 PL_collation_name));
1713 DEBUG_L(PerlIO_printf(Perl_debug_log,
1714 "_mem_collxfrm: highest 1-byte collating character"
1715 " in locale %s is 0x%02X\n",
1717 PL_strxfrm_max_cp));
1719 Safefree(cur_max_x);
1722 /* Here we know which legal code point collates the highest.
1723 * We are ready to construct the non-UTF-8 string. The length
1724 * will be at least 1 byte smaller than the input string
1725 * (because we changed at least one 2-byte character into a
1726 * single byte), but that is eaten up by the trailing NUL */
1732 char * e = (char *) t + len;
1734 for (i = 0; i < len; i+= UTF8SKIP(t + i)) {
1736 if (UTF8_IS_INVARIANT(cur_char)) {
1739 else if (UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(t + i, e)) {
1740 s[d++] = EIGHT_BIT_UTF8_TO_NATIVE(cur_char, t[i+1]);
1742 else { /* Replace illegal cp with highest collating
1744 s[d++] = PL_strxfrm_max_cp;
1748 Renew(s, d, char); /* Free up unused space */
1753 /* Here, we have constructed a modified version of the input. It could
1754 * be that we already had a modified copy before we did this version.
1755 * If so, that copy is no longer needed */
1756 if (t != input_string) {
1761 length_in_chars = (utf8)
1762 ? utf8_length((U8 *) s, (U8 *) s + len)
1765 /* The first element in the output is the collation id, used by
1766 * sv_collxfrm(); then comes the space for the transformed string. The
1767 * equation should give us a good estimate as to how much is needed */
1768 xAlloc = COLLXFRM_HDR_LEN
1770 + (PL_collxfrm_mult * length_in_chars);
1771 Newx(xbuf, xAlloc, char);
1772 if (UNLIKELY(! xbuf)) {
1773 DEBUG_L(PerlIO_printf(Perl_debug_log,
1774 "_mem_collxfrm: Couldn't malloc %zu bytes\n", xAlloc));
1778 /* Store the collation id */
1779 *(U32*)xbuf = PL_collation_ix;
1781 /* Then the transformation of the input. We loop until successful, or we
1785 *xlen = strxfrm(xbuf + COLLXFRM_HDR_LEN, s, xAlloc - COLLXFRM_HDR_LEN);
1787 /* If the transformed string occupies less space than we told strxfrm()
1788 * was available, it means it successfully transformed the whole
1790 if (*xlen < xAlloc - COLLXFRM_HDR_LEN) {
1792 /* Some systems include a trailing NUL in the returned length.
1793 * Ignore it, using a loop in case multiple trailing NULs are
1796 && *(xbuf + COLLXFRM_HDR_LEN + (*xlen) - 1) == '\0')
1801 /* If the first try didn't get it, it means our prediction was low.
1802 * Modify the coefficients so that we predict a larger value in any
1803 * future transformations */
1805 STRLEN needed = *xlen + 1; /* +1 For trailing NUL */
1806 STRLEN computed_guess = PL_collxfrm_base
1807 + (PL_collxfrm_mult * length_in_chars);
1809 /* On zero-length input, just keep current slope instead of
1811 const STRLEN new_m = (length_in_chars != 0)
1812 ? needed / length_in_chars
1815 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
1816 "%s: %d: initial size of %zu bytes for a length "
1817 "%zu string was insufficient, %zu needed\n",
1819 computed_guess, length_in_chars, needed));
1821 /* If slope increased, use it, but discard this result for
1822 * length 1 strings, as we can't be sure that it's a real slope
1824 if (length_in_chars > 1 && new_m > PL_collxfrm_mult) {
1826 STRLEN old_m = PL_collxfrm_mult;
1827 STRLEN old_b = PL_collxfrm_base;
1829 PL_collxfrm_mult = new_m;
1830 PL_collxfrm_base = 1; /* +1 For trailing NUL */
1831 computed_guess = PL_collxfrm_base
1832 + (PL_collxfrm_mult * length_in_chars);
1833 if (computed_guess < needed) {
1834 PL_collxfrm_base += needed - computed_guess;
1837 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
1838 "%s: %d: slope is now %zu; was %zu, base "
1839 "is now %zu; was %zu\n",
1841 PL_collxfrm_mult, old_m,
1842 PL_collxfrm_base, old_b));
1844 else { /* Slope didn't change, but 'b' did */
1845 const STRLEN new_b = needed
1848 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
1849 "%s: %d: base is now %zu; was %zu\n",
1851 new_b, PL_collxfrm_base));
1852 PL_collxfrm_base = new_b;
1859 if (UNLIKELY(*xlen >= PERL_INT_MAX)) {
1860 DEBUG_L(PerlIO_printf(Perl_debug_log,
1861 "_mem_collxfrm: Needed %zu bytes, max permissible is %u\n",
1862 *xlen, PERL_INT_MAX));
1866 /* A well-behaved strxfrm() returns exactly how much space it needs
1867 * (usually not including the trailing NUL) when it fails due to not
1868 * enough space being provided. Assume that this is the case unless
1869 * it's been proven otherwise */
1870 if (LIKELY(PL_strxfrm_is_behaved) && first_time) {
1871 xAlloc = *xlen + COLLXFRM_HDR_LEN + 1;
1873 else { /* Here, either:
1874 * 1) The strxfrm() has previously shown bad behavior; or
1875 * 2) It isn't the first time through the loop, which means
1876 * that the strxfrm() is now showing bad behavior, because
1877 * we gave it what it said was needed in the previous
1878 * iteration, and it came back saying it needed still more.
1879 * (Many versions of cygwin fit this. When the buffer size
1880 * isn't sufficient, they return the input size instead of
1881 * how much is needed.)
1882 * Increase the buffer size by a fixed percentage and try again.
1884 xAlloc += (xAlloc / 4) + 1;
1885 PL_strxfrm_is_behaved = FALSE;
1888 if (DEBUG_Lv_TEST || debug_initialization) {
1889 PerlIO_printf(Perl_debug_log,
1890 "_mem_collxfrm required more space than previously calculated"
1891 " for locale %s, trying again with new guess=%d+%zu\n",
1892 PL_collation_name, (int) COLLXFRM_HDR_LEN,
1893 xAlloc - COLLXFRM_HDR_LEN);
1898 Renew(xbuf, xAlloc, char);
1899 if (UNLIKELY(! xbuf)) {
1900 DEBUG_L(PerlIO_printf(Perl_debug_log,
1901 "_mem_collxfrm: Couldn't realloc %zu bytes\n", xAlloc));
1910 if (DEBUG_Lv_TEST || debug_initialization) {
1913 print_collxfrm_input_and_return(s, s + len, xlen, utf8);
1914 PerlIO_printf(Perl_debug_log, "Its xfrm is:");
1915 for (i = COLLXFRM_HDR_LEN; i < *xlen + COLLXFRM_HDR_LEN; i++) {
1916 PerlIO_printf(Perl_debug_log, " %02x", (U8) xbuf[i]);
1918 PerlIO_printf(Perl_debug_log, "\n");
1922 /* Free up unneeded space; retain ehough for trailing NUL */
1923 Renew(xbuf, COLLXFRM_HDR_LEN + *xlen + 1, char);
1925 if (s != input_string) {
1933 if (s != input_string) {
1938 if (DEBUG_Lv_TEST || debug_initialization) {
1939 print_collxfrm_input_and_return(s, s + len, NULL, utf8);
1948 S_print_collxfrm_input_and_return(pTHX_
1949 const char * const s,
1950 const char * const e,
1951 const STRLEN * const xlen,
1955 bool prev_was_printable = TRUE;
1956 bool first_time = TRUE;
1958 PERL_ARGS_ASSERT_PRINT_COLLXFRM_INPUT_AND_RETURN;
1960 PerlIO_printf(Perl_debug_log, "_mem_collxfrm[%u]: returning ",
1963 PerlIO_printf(Perl_debug_log, "%" UVuf, (UV) *xlen);
1966 PerlIO_printf(Perl_debug_log, "NULL");
1968 PerlIO_printf(Perl_debug_log, " for locale '%s', string='",
1973 ? utf8_to_uvchr_buf((U8 *) t, e, NULL)
1976 if (! prev_was_printable) {
1977 PerlIO_printf(Perl_debug_log, " ");
1979 PerlIO_printf(Perl_debug_log, "%c", (U8) cp);
1980 prev_was_printable = TRUE;
1984 PerlIO_printf(Perl_debug_log, " ");
1986 PerlIO_printf(Perl_debug_log, "%02" UVXf, cp);
1987 prev_was_printable = FALSE;
1989 t += (is_utf8) ? UTF8SKIP(t) : 1;
1993 PerlIO_printf(Perl_debug_log, "'\n");
1996 #endif /* #ifdef DEBUGGING */
1998 #endif /* USE_LOCALE_COLLATE */
2003 Perl__is_cur_LC_category_utf8(pTHX_ int category)
2005 /* Returns TRUE if the current locale for 'category' is UTF-8; FALSE
2006 * otherwise. 'category' may not be LC_ALL. If the platform doesn't have
2007 * nl_langinfo(), nor MB_CUR_MAX, this employs a heuristic, which hence
2008 * could give the wrong result. The result will very likely be correct for
2009 * languages that have commonly used non-ASCII characters, but for notably
2010 * English, it comes down to if the locale's name ends in something like
2011 * "UTF-8". It errs on the side of not being a UTF-8 locale. */
2013 char *save_input_locale = NULL;
2017 assert(category != LC_ALL);
2020 /* First dispose of the trivial cases */
2021 save_input_locale = setlocale(category, NULL);
2022 if (! save_input_locale) {
2023 DEBUG_L(PerlIO_printf(Perl_debug_log,
2024 "Could not find current locale for category %d\n",
2026 return FALSE; /* XXX maybe should croak */
2028 save_input_locale = stdize_locale(savepv(save_input_locale));
2029 if (isNAME_C_OR_POSIX(save_input_locale)) {
2030 DEBUG_L(PerlIO_printf(Perl_debug_log,
2031 "Current locale for category %d is %s\n",
2032 category, save_input_locale));
2033 Safefree(save_input_locale);
2037 #if defined(USE_LOCALE_CTYPE) \
2038 && (defined(MB_CUR_MAX) || (defined(HAS_NL_LANGINFO) && defined(CODESET)))
2040 { /* Next try nl_langinfo or MB_CUR_MAX if available */
2042 char *save_ctype_locale = NULL;
2045 if (category != LC_CTYPE) { /* These work only on LC_CTYPE */
2047 /* Get the current LC_CTYPE locale */
2048 save_ctype_locale = setlocale(LC_CTYPE, NULL);
2049 if (! save_ctype_locale) {
2050 DEBUG_L(PerlIO_printf(Perl_debug_log,
2051 "Could not find current locale for LC_CTYPE\n"));
2052 goto cant_use_nllanginfo;
2054 save_ctype_locale = stdize_locale(savepv(save_ctype_locale));
2056 /* If LC_CTYPE and the desired category use the same locale, this
2057 * means that finding the value for LC_CTYPE is the same as finding
2058 * the value for the desired category. Otherwise, switch LC_CTYPE
2059 * to the desired category's locale */
2060 if (strEQ(save_ctype_locale, save_input_locale)) {
2061 Safefree(save_ctype_locale);
2062 save_ctype_locale = NULL;
2064 else if (! setlocale(LC_CTYPE, save_input_locale)) {
2065 DEBUG_L(PerlIO_printf(Perl_debug_log,
2066 "Could not change LC_CTYPE locale to %s\n",
2067 save_input_locale));
2068 Safefree(save_ctype_locale);
2069 goto cant_use_nllanginfo;
2073 DEBUG_L(PerlIO_printf(Perl_debug_log, "Current LC_CTYPE locale=%s\n",
2074 save_input_locale));
2076 /* Here the current LC_CTYPE is set to the locale of the category whose
2077 * information is desired. This means that nl_langinfo() and MB_CUR_MAX
2078 * should give the correct results */
2080 # if defined(HAS_NL_LANGINFO) && defined(CODESET)
2082 char *codeset = nl_langinfo(CODESET);
2083 if (codeset && strNE(codeset, "")) {
2084 codeset = savepv(codeset);
2086 /* If we switched LC_CTYPE, switch back */
2087 if (save_ctype_locale) {
2088 setlocale(LC_CTYPE, save_ctype_locale);
2089 Safefree(save_ctype_locale);
2092 is_utf8 = foldEQ(codeset, STR_WITH_LEN("UTF-8"))
2093 || foldEQ(codeset, STR_WITH_LEN("UTF8"));
2095 DEBUG_L(PerlIO_printf(Perl_debug_log,
2096 "\tnllanginfo returned CODESET '%s'; ?UTF8 locale=%d\n",
2099 Safefree(save_input_locale);
2107 /* Here, either we don't have nl_langinfo, or it didn't return a
2108 * codeset. Try MB_CUR_MAX */
2110 /* Standard UTF-8 needs at least 4 bytes to represent the maximum
2111 * Unicode code point. Since UTF-8 is the only non-single byte
2112 * encoding we handle, we just say any such encoding is UTF-8, and if
2113 * turns out to be wrong, other things will fail */
2114 is_utf8 = MB_CUR_MAX >= 4;
2116 DEBUG_L(PerlIO_printf(Perl_debug_log,
2117 "\tMB_CUR_MAX=%d; ?UTF8 locale=%d\n",
2118 (int) MB_CUR_MAX, is_utf8));
2120 Safefree(save_input_locale);
2124 /* ... But, most system that have MB_CUR_MAX will also have mbtowc(),
2125 * since they are both in the C99 standard. We can feed a known byte
2126 * string to the latter function, and check that it gives the expected
2130 PERL_UNUSED_RESULT(mbtowc(&wc, NULL, 0));/* Reset any shift state */
2132 if ((size_t)mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8))
2133 != strlen(HYPHEN_UTF8)
2134 || wc != (wchar_t) 0x2010)
2137 DEBUG_L(PerlIO_printf(Perl_debug_log, "\thyphen=U+%x\n", (unsigned int)wc));
2138 DEBUG_L(PerlIO_printf(Perl_debug_log,
2139 "\treturn from mbtowc=%d; errno=%d; ?UTF8 locale=0\n",
2140 mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8)), errno));
2145 /* If we switched LC_CTYPE, switch back */
2146 if (save_ctype_locale) {
2147 setlocale(LC_CTYPE, save_ctype_locale);
2148 Safefree(save_ctype_locale);
2155 cant_use_nllanginfo:
2157 #else /* nl_langinfo should work if available, so don't bother compiling this
2158 fallback code. The final fallback of looking at the name is
2159 compiled, and will be executed if nl_langinfo fails */
2161 /* nl_langinfo not available or failed somehow. Next try looking at the
2162 * currency symbol to see if it disambiguates things. Often that will be
2163 * in the native script, and if the symbol isn't in UTF-8, we know that the
2164 * locale isn't. If it is non-ASCII UTF-8, we infer that the locale is
2165 * too, as the odds of a non-UTF8 string being valid UTF-8 are quite small
2168 #ifdef HAS_LOCALECONV
2169 # ifdef USE_LOCALE_MONETARY
2171 char *save_monetary_locale = NULL;
2172 bool only_ascii = FALSE;
2173 bool is_utf8 = FALSE;
2176 /* Like above for LC_CTYPE, we first set LC_MONETARY to the locale of
2177 * the desired category, if it isn't that locale already */
2179 if (category != LC_MONETARY) {
2181 save_monetary_locale = setlocale(LC_MONETARY, NULL);
2182 if (! save_monetary_locale) {
2183 DEBUG_L(PerlIO_printf(Perl_debug_log,
2184 "Could not find current locale for LC_MONETARY\n"));
2185 goto cant_use_monetary;
2187 save_monetary_locale = stdize_locale(savepv(save_monetary_locale));
2189 if (strEQ(save_monetary_locale, save_input_locale)) {
2190 Safefree(save_monetary_locale);
2191 save_monetary_locale = NULL;
2193 else if (! setlocale(LC_MONETARY, save_input_locale)) {
2194 DEBUG_L(PerlIO_printf(Perl_debug_log,
2195 "Could not change LC_MONETARY locale to %s\n",
2196 save_input_locale));
2197 Safefree(save_monetary_locale);
2198 goto cant_use_monetary;
2202 /* Here the current LC_MONETARY is set to the locale of the category
2203 * whose information is desired. */
2207 || ! lc->currency_symbol
2208 || is_utf8_invariant_string((U8 *) lc->currency_symbol, 0))
2210 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));
2214 is_utf8 = is_utf8_string((U8 *) lc->currency_symbol, 0);
2217 /* If we changed it, restore LC_MONETARY to its original locale */
2218 if (save_monetary_locale) {
2219 setlocale(LC_MONETARY, save_monetary_locale);
2220 Safefree(save_monetary_locale);
2225 /* It isn't a UTF-8 locale if the symbol is not legal UTF-8;
2226 * otherwise assume the locale is UTF-8 if and only if the symbol
2227 * is non-ascii UTF-8. */
2228 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?Currency symbol for %s is UTF-8=%d\n",
2229 save_input_locale, is_utf8));
2230 Safefree(save_input_locale);
2236 # endif /* USE_LOCALE_MONETARY */
2237 #endif /* HAS_LOCALECONV */
2239 #if defined(HAS_STRFTIME) && defined(USE_LOCALE_TIME)
2241 /* Still haven't found a non-ASCII string to disambiguate UTF-8 or not. Try
2242 * the names of the months and weekdays, timezone, and am/pm indicator */
2244 char *save_time_locale = NULL;
2246 bool is_dst = FALSE;
2250 char * formatted_time;
2253 /* Like above for LC_MONETARY, we set LC_TIME to the locale of the
2254 * desired category, if it isn't that locale already */
2256 if (category != LC_TIME) {
2258 save_time_locale = setlocale(LC_TIME, NULL);
2259 if (! save_time_locale) {
2260 DEBUG_L(PerlIO_printf(Perl_debug_log,
2261 "Could not find current locale for LC_TIME\n"));
2264 save_time_locale = stdize_locale(savepv(save_time_locale));
2266 if (strEQ(save_time_locale, save_input_locale)) {
2267 Safefree(save_time_locale);
2268 save_time_locale = NULL;
2270 else if (! setlocale(LC_TIME, save_input_locale)) {
2271 DEBUG_L(PerlIO_printf(Perl_debug_log,
2272 "Could not change LC_TIME locale to %s\n",
2273 save_input_locale));
2274 Safefree(save_time_locale);
2279 /* Here the current LC_TIME is set to the locale of the category
2280 * whose information is desired. Look at all the days of the week and
2281 * month names, and the timezone and am/pm indicator for UTF-8 variant
2282 * characters. The first such a one found will tell us if the locale
2283 * is UTF-8 or not */
2285 for (i = 0; i < 7 + 12; i++) { /* 7 days; 12 months */
2286 formatted_time = my_strftime("%A %B %Z %p",
2287 0, 0, hour, dom, month, 112, 0, 0, is_dst);
2288 if ( ! formatted_time
2289 || is_utf8_invariant_string((U8 *) formatted_time, 0))
2292 /* Here, we didn't find a non-ASCII. Try the next time through
2293 * with the complemented dst and am/pm, and try with the next
2294 * weekday. After we have gotten all weekdays, try the next
2297 hour = (hour + 12) % 24;
2305 /* Here, we have a non-ASCII. Return TRUE is it is valid UTF8;
2306 * false otherwise. But first, restore LC_TIME to its original
2307 * locale if we changed it */
2308 if (save_time_locale) {
2309 setlocale(LC_TIME, save_time_locale);
2310 Safefree(save_time_locale);
2313 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?time-related strings for %s are UTF-8=%d\n",
2315 is_utf8_string((U8 *) formatted_time, 0)));
2316 Safefree(save_input_locale);
2317 return is_utf8_string((U8 *) formatted_time, 0);
2320 /* Falling off the end of the loop indicates all the names were just
2321 * ASCII. Go on to the next test. If we changed it, restore LC_TIME
2322 * to its original locale */
2323 if (save_time_locale) {
2324 setlocale(LC_TIME, save_time_locale);
2325 Safefree(save_time_locale);
2327 DEBUG_L(PerlIO_printf(Perl_debug_log, "All time-related words for %s contain only ASCII; can't use for determining if UTF-8 locale\n", save_input_locale));
2333 #if 0 && defined(USE_LOCALE_MESSAGES) && defined(HAS_SYS_ERRLIST)
2335 /* This code is ifdefd out because it was found to not be necessary in testing
2336 * on our dromedary test machine, which has over 700 locales. There, this
2337 * added no value to looking at the currency symbol and the time strings. I
2338 * left it in so as to avoid rewriting it if real-world experience indicates
2339 * that dromedary is an outlier. Essentially, instead of returning abpve if we
2340 * haven't found illegal utf8, we continue on and examine all the strerror()
2341 * messages on the platform for utf8ness. If all are ASCII, we still don't
2342 * know the answer; but otherwise we have a pretty good indication of the
2343 * utf8ness. The reason this doesn't help much is that the messages may not
2344 * have been translated into the locale. The currency symbol and time strings
2345 * are much more likely to have been translated. */
2348 bool is_utf8 = FALSE;
2349 bool non_ascii = FALSE;
2350 char *save_messages_locale = NULL;
2351 const char * errmsg = NULL;
2353 /* Like above, we set LC_MESSAGES to the locale of the desired
2354 * category, if it isn't that locale already */
2356 if (category != LC_MESSAGES) {
2358 save_messages_locale = setlocale(LC_MESSAGES, NULL);
2359 if (! save_messages_locale) {
2360 DEBUG_L(PerlIO_printf(Perl_debug_log,
2361 "Could not find current locale for LC_MESSAGES\n"));
2362 goto cant_use_messages;
2364 save_messages_locale = stdize_locale(savepv(save_messages_locale));
2366 if (strEQ(save_messages_locale, save_input_locale)) {
2367 Safefree(save_messages_locale);
2368 save_messages_locale = NULL;
2370 else if (! setlocale(LC_MESSAGES, save_input_locale)) {
2371 DEBUG_L(PerlIO_printf(Perl_debug_log,
2372 "Could not change LC_MESSAGES locale to %s\n",
2373 save_input_locale));
2374 Safefree(save_messages_locale);
2375 goto cant_use_messages;
2379 /* Here the current LC_MESSAGES is set to the locale of the category
2380 * whose information is desired. Look through all the messages. We
2381 * can't use Strerror() here because it may expand to code that
2382 * segfaults in miniperl */
2384 for (e = 0; e <= sys_nerr; e++) {
2386 errmsg = sys_errlist[e];
2387 if (errno || !errmsg) {
2390 errmsg = savepv(errmsg);
2391 if (! is_utf8_invariant_string((U8 *) errmsg, 0)) {
2393 is_utf8 = is_utf8_string((U8 *) errmsg, 0);
2399 /* And, if we changed it, restore LC_MESSAGES to its original locale */
2400 if (save_messages_locale) {
2401 setlocale(LC_MESSAGES, save_messages_locale);
2402 Safefree(save_messages_locale);
2407 /* Any non-UTF-8 message means not a UTF-8 locale; if all are valid,
2408 * any non-ascii means it is one; otherwise we assume it isn't */
2409 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?error messages for %s are UTF-8=%d\n",
2412 Safefree(save_input_locale);
2416 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));
2422 #endif /* the code that is compiled when no nl_langinfo */
2424 #ifndef EBCDIC /* On os390, even if the name ends with "UTF-8', it isn't a
2426 /* As a last resort, look at the locale name to see if it matches
2427 * qr/UTF -? * 8 /ix, or some other common locale names. This "name", the
2428 * return of setlocale(), is actually defined to be opaque, so we can't
2429 * really rely on the absence of various substrings in the name to indicate
2430 * its UTF-8ness, but if it has UTF8 in the name, it is extremely likely to
2431 * be a UTF-8 locale. Similarly for the other common names */
2433 final_pos = strlen(save_input_locale) - 1;
2434 if (final_pos >= 3) {
2435 char *name = save_input_locale;
2437 /* Find next 'U' or 'u' and look from there */
2438 while ((name += strcspn(name, "Uu") + 1)
2439 <= save_input_locale + final_pos - 2)
2441 if (!isALPHA_FOLD_NE(*name, 't')
2442 || isALPHA_FOLD_NE(*(name + 1), 'f'))
2447 if (*(name) == '-') {
2448 if ((name > save_input_locale + final_pos - 1)) {
2453 if (*(name) == '8') {
2454 DEBUG_L(PerlIO_printf(Perl_debug_log,
2455 "Locale %s ends with UTF-8 in name\n",
2456 save_input_locale));
2457 Safefree(save_input_locale);
2461 DEBUG_L(PerlIO_printf(Perl_debug_log,
2462 "Locale %s doesn't end with UTF-8 in name\n",
2463 save_input_locale));
2468 /* http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756.aspx */
2470 && *(save_input_locale + final_pos - 0) == '1'
2471 && *(save_input_locale + final_pos - 1) == '0'
2472 && *(save_input_locale + final_pos - 2) == '0'
2473 && *(save_input_locale + final_pos - 3) == '5'
2474 && *(save_input_locale + final_pos - 4) == '6')
2476 DEBUG_L(PerlIO_printf(Perl_debug_log,
2477 "Locale %s ends with 10056 in name, is UTF-8 locale\n",
2478 save_input_locale));
2479 Safefree(save_input_locale);
2484 /* Other common encodings are the ISO 8859 series, which aren't UTF-8. But
2485 * since we are about to return FALSE anyway, there is no point in doing
2486 * this extra work */
2488 if (instr(save_input_locale, "8859")) {
2489 DEBUG_L(PerlIO_printf(Perl_debug_log,
2490 "Locale %s has 8859 in name, not UTF-8 locale\n",
2491 save_input_locale));
2492 Safefree(save_input_locale);
2497 DEBUG_L(PerlIO_printf(Perl_debug_log,
2498 "Assuming locale %s is not a UTF-8 locale\n",
2499 save_input_locale));
2500 Safefree(save_input_locale);
2508 Perl__is_in_locale_category(pTHX_ const bool compiling, const int category)
2511 /* Internal function which returns if we are in the scope of a pragma that
2512 * enables the locale category 'category'. 'compiling' should indicate if
2513 * this is during the compilation phase (TRUE) or not (FALSE). */
2515 const COP * const cop = (compiling) ? &PL_compiling : PL_curcop;
2517 SV *categories = cop_hints_fetch_pvs(cop, "locale", 0);
2518 if (! categories || categories == &PL_sv_placeholder) {
2522 /* The pseudo-category 'not_characters' is -1, so just add 1 to each to get
2523 * a valid unsigned */
2524 assert(category >= -1);
2525 return cBOOL(SvUV(categories) & (1U << (category + 1)));
2529 Perl_my_strerror(pTHX_ const int errnum)
2531 /* Returns a mortalized copy of the text of the error message associated
2532 * with 'errnum'. It uses the current locale's text unless the platform
2533 * doesn't have the LC_MESSAGES category or we are not being called from
2534 * within the scope of 'use locale'. In the former case, it uses whatever
2535 * strerror returns; in the latter case it uses the text from the C locale.
2537 * The function just calls strerror(), but temporarily switches, if needed,
2538 * to the C locale */
2542 #ifdef USE_LOCALE_MESSAGES /* If platform doesn't have messages category, we
2543 don't do any switching to the C locale; we just
2544 use whatever strerror() returns */
2545 const bool within_locale_scope = IN_LC(LC_MESSAGES);
2549 # ifdef USE_THREAD_SAFE_LOCALE
2550 locale_t save_locale = NULL;
2552 char * save_locale = NULL;
2553 bool locale_is_C = FALSE;
2555 /* We have a critical section to prevent another thread from changing the
2556 * locale out from under us (or zapping the buffer returned from
2562 if (! within_locale_scope) {
2565 # ifdef USE_THREAD_SAFE_LOCALE /* Use the thread-safe locale functions */
2567 save_locale = uselocale(PL_C_locale_obj);
2568 if (! save_locale) {
2569 DEBUG_L(PerlIO_printf(Perl_debug_log,
2570 "uselocale failed, errno=%d\n", errno));
2573 # else /* Not thread-safe build */
2575 save_locale = setlocale(LC_MESSAGES, NULL);
2576 if (! save_locale) {
2577 DEBUG_L(PerlIO_printf(Perl_debug_log,
2578 "setlocale failed, errno=%d\n", errno));
2581 locale_is_C = isNAME_C_OR_POSIX(save_locale);
2583 /* Switch to the C locale if not already in it */
2584 if (! locale_is_C) {
2586 /* The setlocale() just below likely will zap 'save_locale', so
2588 save_locale = savepv(save_locale);
2589 setlocale(LC_MESSAGES, "C");
2595 } /* end of ! within_locale_scope */
2599 errstr = Strerror(errnum);
2601 errstr = savepv(errstr);
2605 #ifdef USE_LOCALE_MESSAGES
2607 if (! within_locale_scope) {
2610 # ifdef USE_THREAD_SAFE_LOCALE
2612 if (save_locale && ! uselocale(save_locale)) {
2613 DEBUG_L(PerlIO_printf(Perl_debug_log,
2614 "uselocale restore failed, errno=%d\n", errno));
2620 if (save_locale && ! locale_is_C) {
2621 if (! setlocale(LC_MESSAGES, save_locale)) {
2622 DEBUG_L(PerlIO_printf(Perl_debug_log,
2623 "setlocale restore failed, errno=%d\n", errno));
2625 Safefree(save_locale);
2639 =head1 Locale-related functions and macros
2641 =for apidoc sync_locale
2643 Changing the program's locale should be avoided by XS code. Nevertheless,
2644 certain non-Perl libraries called from XS, such as C<Gtk> do so. When this
2645 happens, Perl needs to be told that the locale has changed. Use this function
2646 to do so, before returning to Perl.
2652 Perl_sync_locale(pTHX)
2655 #ifdef USE_LOCALE_CTYPE
2656 new_ctype(setlocale(LC_CTYPE, NULL));
2657 #endif /* USE_LOCALE_CTYPE */
2659 #ifdef USE_LOCALE_COLLATE
2660 new_collate(setlocale(LC_COLLATE, NULL));
2663 #ifdef USE_LOCALE_NUMERIC
2664 set_numeric_local(); /* Switch from "C" to underlying LC_NUMERIC */
2665 new_numeric(setlocale(LC_NUMERIC, NULL));
2666 #endif /* USE_LOCALE_NUMERIC */
2670 #if defined(DEBUGGING) && defined(USE_LOCALE)
2673 Perl__setlocale_debug_string(const int category, /* category number,
2675 const char* const locale, /* locale name */
2677 /* return value from setlocale() when attempting to
2678 * set 'category' to 'locale' */
2679 const char* const retval)
2681 /* Returns a pointer to a NUL-terminated string in static storage with
2682 * added text about the info passed in. This is not thread safe and will
2683 * be overwritten by the next call, so this should be used just to
2684 * formulate a string to immediately print or savepv() on. */
2686 /* initialise to a non-null value to keep it out of BSS and so keep
2687 * -DPERL_GLOBAL_STRUCT_PRIVATE happy */
2688 static char ret[128] = "If you can read this, thank your buggy C"
2689 " library strlcpy(), and change your hints file"
2691 my_strlcpy(ret, "setlocale(", sizeof(ret));
2695 my_snprintf(ret, sizeof(ret), "%s? %d", ret, category);
2699 my_strlcat(ret, "LC_ALL", sizeof(ret));
2704 my_strlcat(ret, "LC_CTYPE", sizeof(ret));
2709 my_strlcat(ret, "LC_NUMERIC", sizeof(ret));
2714 my_strlcat(ret, "LC_COLLATE", sizeof(ret));
2719 my_strlcat(ret, "LC_TIME", sizeof(ret));
2724 my_strlcat(ret, "LC_MONETARY", sizeof(ret));
2729 my_strlcat(ret, "LC_MESSAGES", sizeof(ret));
2734 my_strlcat(ret, ", ", sizeof(ret));
2737 my_strlcat(ret, "\"", sizeof(ret));
2738 my_strlcat(ret, locale, sizeof(ret));
2739 my_strlcat(ret, "\"", sizeof(ret));
2742 my_strlcat(ret, "NULL", sizeof(ret));
2745 my_strlcat(ret, ") returned ", sizeof(ret));
2748 my_strlcat(ret, "\"", sizeof(ret));
2749 my_strlcat(ret, retval, sizeof(ret));
2750 my_strlcat(ret, "\"", sizeof(ret));
2753 my_strlcat(ret, "NULL", sizeof(ret));
2756 assert(strlen(ret) < sizeof(ret));
2765 * ex: set ts=8 sts=4 sw=4 et: