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 static bool debug_initialization = FALSE;
57 * Standardize the locale name from a string returned by 'setlocale', possibly
58 * modifying that string.
60 * The typical return value of setlocale() is either
61 * (1) "xx_YY" if the first argument of setlocale() is not LC_ALL
62 * (2) "xa_YY xb_YY ..." if the first argument of setlocale() is LC_ALL
63 * (the space-separated values represent the various sublocales,
64 * in some unspecified order). This is not handled by this function.
66 * In some platforms it has a form like "LC_SOMETHING=Lang_Country.866\n",
67 * which is harmful for further use of the string in setlocale(). This
68 * function removes the trailing new line and everything up through the '='
72 S_stdize_locale(pTHX_ char *locs)
74 const char * const s = strchr(locs, '=');
77 PERL_ARGS_ASSERT_STDIZE_LOCALE;
80 const char * const t = strchr(s, '.');
83 const char * const u = strchr(t, '\n');
84 if (u && (u[1] == 0)) {
85 const STRLEN len = u - s;
86 Move(s + 1, locs, len, char);
94 Perl_croak(aTHX_ "Can't fix broken locale name \"%s\"", locs);
102 Perl_set_numeric_radix(pTHX)
104 #ifdef USE_LOCALE_NUMERIC
105 # ifdef HAS_LOCALECONV
106 const struct lconv* const lc = localeconv();
108 if (lc && lc->decimal_point) {
109 if (lc->decimal_point[0] == '.' && lc->decimal_point[1] == 0) {
110 SvREFCNT_dec(PL_numeric_radix_sv);
111 PL_numeric_radix_sv = NULL;
114 if (PL_numeric_radix_sv)
115 sv_setpv(PL_numeric_radix_sv, lc->decimal_point);
117 PL_numeric_radix_sv = newSVpv(lc->decimal_point, 0);
118 if (! is_invariant_string((U8 *) lc->decimal_point, 0)
119 && is_utf8_string((U8 *) lc->decimal_point, 0)
120 && _is_cur_LC_category_utf8(LC_NUMERIC))
122 SvUTF8_on(PL_numeric_radix_sv);
127 PL_numeric_radix_sv = NULL;
130 if (DEBUG_L_TEST || debug_initialization) {
131 PerlIO_printf(Perl_debug_log, "Locale radix is '%s', ?UTF-8=%d\n",
132 (PL_numeric_radix_sv)
133 ? SvPVX(PL_numeric_radix_sv)
135 (PL_numeric_radix_sv)
136 ? cBOOL(SvUTF8(PL_numeric_radix_sv))
141 # endif /* HAS_LOCALECONV */
142 #endif /* USE_LOCALE_NUMERIC */
145 /* Is the C string input 'name' "C" or "POSIX"? If so, and 'name' is the
146 * return of setlocale(), then this is extremely likely to be the C or POSIX
147 * locale. However, the output of setlocale() is documented to be opaque, but
148 * the odds are extremely small that it would return these two strings for some
149 * other locale. Note that VMS in these two locales includes many non-ASCII
150 * characters as controls and punctuation (below are hex bytes):
151 * cntrl: 00-1F 7F 84-97 9B-9F
152 * 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
153 * Oddly, none there are listed as alphas, though some represent alphabetics
154 * http://www.nntp.perl.org/group/perl.perl5.porters/2013/02/msg198753.html */
155 #define isNAME_C_OR_POSIX(name) ((name) != NULL \
156 && ((*(name) == 'C' && (*(name + 1)) == '\0') \
157 || strEQ((name), "POSIX")))
160 Perl_new_numeric(pTHX_ const char *newnum)
162 #ifdef USE_LOCALE_NUMERIC
164 /* Called after all libc setlocale() calls affecting LC_NUMERIC, to tell
165 * core Perl this and that 'newnum' is the name of the new locale.
166 * It installs this locale as the current underlying default.
168 * The default locale and the C locale can be toggled between by use of the
169 * set_numeric_local() and set_numeric_standard() functions, which should
170 * probably not be called directly, but only via macros like
171 * SET_NUMERIC_STANDARD() in perl.h.
173 * The toggling is necessary mainly so that a non-dot radix decimal point
174 * character can be output, while allowing internal calculations to use a
177 * This sets several interpreter-level variables:
178 * PL_numeric_name The underlying locale's name: a copy of 'newnum'
179 * PL_numeric_local A boolean indicating if the toggled state is such
180 * that the current locale is the program's underlying
182 * PL_numeric_standard An int indicating if the toggled state is such
183 * that the current locale is the C locale. If non-zero,
184 * it is in C; if > 1, it means it may not be toggled away
186 * Note that both of the last two variables can be true at the same time,
187 * if the underlying locale is C. (Toggling is a no-op under these
190 * Any code changing the locale (outside this file) should use
191 * POSIX::setlocale, which calls this function. Therefore this function
192 * should be called directly only from this file and from
193 * POSIX::setlocale() */
198 Safefree(PL_numeric_name);
199 PL_numeric_name = NULL;
200 PL_numeric_standard = TRUE;
201 PL_numeric_local = TRUE;
205 save_newnum = stdize_locale(savepv(newnum));
207 PL_numeric_standard = isNAME_C_OR_POSIX(save_newnum);
208 PL_numeric_local = TRUE;
210 if (! PL_numeric_name || strNE(PL_numeric_name, save_newnum)) {
211 Safefree(PL_numeric_name);
212 PL_numeric_name = save_newnum;
215 Safefree(save_newnum);
218 /* Keep LC_NUMERIC in the C locale. This is for XS modules, so they don't
219 * have to worry about the radix being a non-dot. (Core operations that
220 * need the underlying locale change to it temporarily). */
221 set_numeric_standard();
226 PERL_UNUSED_ARG(newnum);
227 #endif /* USE_LOCALE_NUMERIC */
231 Perl_set_numeric_standard(pTHX)
233 #ifdef USE_LOCALE_NUMERIC
234 /* Toggle the LC_NUMERIC locale to C. Most code should use the macros like
235 * SET_NUMERIC_STANDARD() in perl.h instead of calling this directly. The
236 * macro avoids calling this routine if toggling isn't necessary according
237 * to our records (which could be wrong if some XS code has changed the
238 * locale behind our back) */
240 setlocale(LC_NUMERIC, "C");
241 PL_numeric_standard = TRUE;
242 PL_numeric_local = isNAME_C_OR_POSIX(PL_numeric_name);
245 if (DEBUG_L_TEST || debug_initialization) {
246 PerlIO_printf(Perl_debug_log,
247 "Underlying LC_NUMERIC locale now is C\n");
251 #endif /* USE_LOCALE_NUMERIC */
255 Perl_set_numeric_local(pTHX)
257 #ifdef USE_LOCALE_NUMERIC
258 /* Toggle the LC_NUMERIC locale to the current underlying default. Most
259 * code should use the macros like SET_NUMERIC_LOCAL() in perl.h instead of
260 * calling this directly. The macro avoids calling this routine if
261 * toggling isn't necessary according to our records (which could be wrong
262 * if some XS code has changed the locale behind our back) */
264 setlocale(LC_NUMERIC, PL_numeric_name);
265 PL_numeric_standard = isNAME_C_OR_POSIX(PL_numeric_name);
266 PL_numeric_local = TRUE;
269 if (DEBUG_L_TEST || debug_initialization) {
270 PerlIO_printf(Perl_debug_log,
271 "Underlying LC_NUMERIC locale now is %s\n",
276 #endif /* USE_LOCALE_NUMERIC */
280 * Set up for a new ctype locale.
283 Perl_new_ctype(pTHX_ const char *newctype)
285 #ifdef USE_LOCALE_CTYPE
287 /* Called after all libc setlocale() calls affecting LC_CTYPE, to tell
288 * core Perl this and that 'newctype' is the name of the new locale.
290 * This function sets up the folding arrays for all 256 bytes, assuming
291 * that tofold() is tolc() since fold case is not a concept in POSIX,
293 * Any code changing the locale (outside this file) should use
294 * POSIX::setlocale, which calls this function. Therefore this function
295 * should be called directly only from this file and from
296 * POSIX::setlocale() */
301 PERL_ARGS_ASSERT_NEW_CTYPE;
303 /* We will replace any bad locale warning with 1) nothing if the new one is
304 * ok; or 2) a new warning for the bad new locale */
305 if (PL_warn_locale) {
306 SvREFCNT_dec_NN(PL_warn_locale);
307 PL_warn_locale = NULL;
310 PL_in_utf8_CTYPE_locale = _is_cur_LC_category_utf8(LC_CTYPE);
312 /* A UTF-8 locale gets standard rules. But note that code still has to
313 * handle this specially because of the three problematic code points */
314 if (PL_in_utf8_CTYPE_locale) {
315 Copy(PL_fold_latin1, PL_fold_locale, 256, U8);
318 /* Assume enough space for every character being bad. 4 spaces each
319 * for the 94 printable characters that are output like "'x' "; and 5
320 * spaces each for "'\\' ", "'\t' ", and "'\n' "; plus a terminating
322 char bad_chars_list[ (94 * 4) + (3 * 5) + 1 ];
324 bool check_for_problems = ckWARN_d(WARN_LOCALE); /* No warnings means
326 bool multi_byte_locale = FALSE; /* Assume is a single-byte locale
328 unsigned int bad_count = 0; /* Count of bad characters */
330 for (i = 0; i < 256; i++) {
331 if (isUPPER_LC((U8) i))
332 PL_fold_locale[i] = (U8) toLOWER_LC((U8) i);
333 else if (isLOWER_LC((U8) i))
334 PL_fold_locale[i] = (U8) toUPPER_LC((U8) i);
336 PL_fold_locale[i] = (U8) i;
338 /* If checking for locale problems, see if the native ASCII-range
339 * printables plus \n and \t are in their expected categories in
340 * the new locale. If not, this could mean big trouble, upending
341 * Perl's and most programs' assumptions, like having a
342 * metacharacter with special meaning become a \w. Fortunately,
343 * it's very rare to find locales that aren't supersets of ASCII
344 * nowadays. It isn't a problem for most controls to be changed
345 * into something else; we check only \n and \t, though perhaps \r
346 * could be an issue as well. */
347 if (check_for_problems
348 && (isGRAPH_A(i) || isBLANK_A(i) || i == '\n'))
350 if ((isALPHANUMERIC_A(i) && ! isALPHANUMERIC_LC(i))
351 || (isPUNCT_A(i) && ! isPUNCT_LC(i))
352 || (isBLANK_A(i) && ! isBLANK_LC(i))
353 || (i == '\n' && ! isCNTRL_LC(i)))
355 if (bad_count) { /* Separate multiple entries with a
357 bad_chars_list[bad_count++] = ' ';
359 bad_chars_list[bad_count++] = '\'';
361 bad_chars_list[bad_count++] = (char) i;
364 bad_chars_list[bad_count++] = '\\';
366 bad_chars_list[bad_count++] = 'n';
370 bad_chars_list[bad_count++] = 't';
373 bad_chars_list[bad_count++] = '\'';
374 bad_chars_list[bad_count] = '\0';
380 /* We only handle single-byte locales (outside of UTF-8 ones; so if
381 * this locale requires more than one byte, there are going to be
383 if (check_for_problems && MB_CUR_MAX > 1
385 /* Some platforms return MB_CUR_MAX > 1 for even the "C"
386 * locale. Just assume that the implementation for them (plus
387 * for POSIX) is correct and the > 1 value is spurious. (Since
388 * these are specially handled to never be considered UTF-8
389 * locales, as long as this is the only problem, everything
390 * should work fine */
391 && strNE(newctype, "C") && strNE(newctype, "POSIX"))
393 multi_byte_locale = TRUE;
397 if (bad_count || multi_byte_locale) {
398 PL_warn_locale = Perl_newSVpvf(aTHX_
399 "Locale '%s' may not work well.%s%s%s\n",
402 ? " Some characters in it are not recognized by"
406 ? "\nThe following characters (and maybe others)"
407 " may not have the same meaning as the Perl"
408 " program expects:\n"
414 /* If we are actually in the scope of the locale, output the
415 * message now. Otherwise we save it to be output at the first
416 * operation using this locale, if that actually happens. Most
417 * programs don't use locales, so they are immune to bad ones */
418 if (IN_LC(LC_CTYPE)) {
420 /* We have to save 'newctype' because the setlocale() just
421 * below may destroy it. The next setlocale() further down
422 * should restore it properly so that the intermediate change
423 * here is transparent to this function's caller */
424 const char * const badlocale = savepv(newctype);
426 setlocale(LC_CTYPE, "C");
428 /* The '0' below suppresses a bogus gcc compiler warning */
429 Perl_warner(aTHX_ packWARN(WARN_LOCALE), SvPVX(PL_warn_locale), 0);
430 setlocale(LC_CTYPE, badlocale);
432 SvREFCNT_dec_NN(PL_warn_locale);
433 PL_warn_locale = NULL;
438 #endif /* USE_LOCALE_CTYPE */
439 PERL_ARGS_ASSERT_NEW_CTYPE;
440 PERL_UNUSED_ARG(newctype);
445 Perl__warn_problematic_locale()
448 #ifdef USE_LOCALE_CTYPE
452 /* Internal-to-core function that outputs the message in PL_warn_locale,
453 * and then NULLS it. Should be called only through the macro
454 * _CHECK_AND_WARN_PROBLEMATIC_LOCALE */
456 if (PL_warn_locale) {
457 /*GCC_DIAG_IGNORE(-Wformat-security); Didn't work */
458 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
459 SvPVX(PL_warn_locale),
460 0 /* dummy to avoid compiler warning */ );
461 /* GCC_DIAG_RESTORE; */
462 SvREFCNT_dec_NN(PL_warn_locale);
463 PL_warn_locale = NULL;
471 Perl_new_collate(pTHX_ const char *newcoll)
473 #ifdef USE_LOCALE_COLLATE
475 /* Called after all libc setlocale() calls affecting LC_COLLATE, to tell
476 * core Perl this and that 'newcoll' is the name of the new locale.
478 * Any code changing the locale (outside this file) should use
479 * POSIX::setlocale, which calls this function. Therefore this function
480 * should be called directly only from this file and from
481 * POSIX::setlocale().
483 * The design of locale collation is that every locale change is given an
484 * index 'PL_collation_ix'. The first time a string particpates in an
485 * operation that requires collation while locale collation is active, it
486 * is given PERL_MAGIC_collxfrm magic (via sv_collxfrm_flags()). That
487 * magic includes the collation index, and the transformation of the string
488 * by strxfrm(), q.v. That transformation is used when doing comparisons,
489 * instead of the string itself. If a string changes, the magic is
490 * cleared. The next time the locale changes, the index is incremented,
491 * and so we know during a comparison that the transformation is not
492 * necessarily still valid, and so is recomputed. Note that if the locale
493 * changes enough times, the index could wrap (a U32), and it is possible
494 * that a transformation would improperly be considered valid, leading to
498 if (PL_collation_name) {
500 Safefree(PL_collation_name);
501 PL_collation_name = NULL;
503 PL_collation_standard = TRUE;
504 is_standard_collation:
505 PL_collxfrm_base = 0;
506 PL_collxfrm_mult = 2;
507 PL_in_utf8_COLLATE_locale = FALSE;
508 *PL_strxfrm_min_char = '\0';
509 PL_strxfrm_max_cp = 0;
513 /* If this is not the same locale as currently, set the new one up */
514 if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
516 Safefree(PL_collation_name);
517 PL_collation_name = stdize_locale(savepv(newcoll));
518 PL_collation_standard = isNAME_C_OR_POSIX(newcoll);
519 if (PL_collation_standard) {
520 goto is_standard_collation;
523 PL_in_utf8_COLLATE_locale = _is_cur_LC_category_utf8(LC_COLLATE);
524 *PL_strxfrm_min_char = '\0';
525 PL_strxfrm_max_cp = 0;
527 /* A locale collation definition includes primary, secondary, tertiary,
528 * etc. weights for each character. To sort, the primary weights are
529 * used, and only if they compare equal, then the secondary weights are
530 * used, and only if they compare equal, then the tertiary, etc.
532 * strxfrm() works by taking the input string, say ABC, and creating an
533 * output transformed string consisting of first the primary weights,
534 * A¹B¹C¹ followed by the secondary ones, A²B²C²; and then the
535 * tertiary, etc, yielding A¹B¹C¹ A²B²C² A³B³C³ .... Some characters
536 * may not have weights at every level. In our example, let's say B
537 * doesn't have a tertiary weight, and A doesn't have a secondary
538 * weight. The constructed string is then going to be
539 * A¹B¹C¹ B²C² A³C³ ....
540 * This has the desired effect that strcmp() will look at the secondary
541 * or tertiary weights only if the strings compare equal at all higher
542 * priority weights. The spaces shown here, like in
544 * are not just for readability. In the general case, these must
545 * actually be bytes, which we will call here 'separator weights'; and
546 * they must be smaller than any other weight value, but since these
547 * are C strings, only the terminating one can be a NUL (some
548 * implementations may include a non-NUL separator weight just before
549 * the NUL). Implementations tend to reserve 01 for the separator
550 * weights. They are needed so that a shorter string's secondary
551 * weights won't be misconstrued as primary weights of a longer string,
552 * etc. By making them smaller than any other weight, the shorter
553 * string will sort first. (Actually, if all secondary weights are
554 * smaller than all primary ones, there is no need for a separator
555 * weight between those two levels, etc.)
557 * The length of the transformed string is roughly a linear function of
558 * the input string. It's not exactly linear because some characters
559 * don't have weights at all levels. When we call strxfrm() we have to
560 * allocate some memory to hold the transformed string. The
561 * calculations below try to find coefficients 'm' and 'b' for this
562 * locale so that m*x + b equals how much space we need, given the size
563 * of the input string in 'x'. If we calculate too small, we increase
564 * the size as needed, and call strxfrm() again, but it is better to
565 * get it right the first time to avoid wasted expensive string
566 * transformations. */
569 /* We use the string below to find how long the tranformation of it
570 * is. Almost all locales are supersets of ASCII, or at least the
571 * ASCII letters. We use all of them, half upper half lower,
572 * because if we used fewer, we might hit just the ones that are
573 * outliers in a particular locale. Most of the strings being
574 * collated will contain a preponderance of letters, and even if
575 * they are above-ASCII, they are likely to have the same number of
576 * weight levels as the ASCII ones. It turns out that digits tend
577 * to have fewer levels, and some punctuation has more, but those
578 * are relatively sparse in text, and khw believes this gives a
579 * reasonable result, but it could be changed if experience so
581 const char longer[] = "ABCDEFGHIJKLMnopqrstuvwxyz";
582 char * x_longer; /* Transformed 'longer' */
583 Size_t x_len_longer; /* Length of 'x_longer' */
585 char * x_shorter; /* We also transform a substring of 'longer' */
586 Size_t x_len_shorter;
588 /* _mem_collxfrm() is used get the transformation (though here we
589 * are interested only in its length). It is used because it has
590 * the intelligence to handle all cases, but to work, it needs some
591 * values of 'm' and 'b' to get it started. For the purposes of
592 * this calculation we use a very conservative estimate of 'm' and
593 * 'b'. This assumes a weight can be multiple bytes, enough to
594 * hold any UV on the platform, and there are 5 levels, 4 weight
595 * bytes, and a trailing NUL. */
596 PL_collxfrm_base = 5;
597 PL_collxfrm_mult = 5 * sizeof(UV);
599 /* Find out how long the transformation really is */
600 x_longer = _mem_collxfrm(longer,
604 /* We avoid converting to UTF-8 in the
605 * called function by telling it the
606 * string is in UTF-8 if the locale is a
607 * UTF-8 one. Since the string passed
608 * here is invariant under UTF-8, we can
609 * claim it's UTF-8 even though it isn't.
611 PL_in_utf8_COLLATE_locale);
614 /* Find out how long the transformation of a substring of 'longer'
615 * is. Together the lengths of these transformations are
616 * sufficient to calculate 'm' and 'b'. The substring is all of
617 * 'longer' except the first character. This minimizes the chances
618 * of being swayed by outliers */
619 x_shorter = _mem_collxfrm(longer + 1,
622 PL_in_utf8_COLLATE_locale);
625 /* If the results are nonsensical for this simple test, the whole
626 * locale definition is suspect. Mark it so that locale collation
627 * is not active at all for it. XXX Should we warn? */
628 if ( x_len_shorter == 0
630 || x_len_shorter >= x_len_longer)
632 PL_collxfrm_mult = 0;
633 PL_collxfrm_base = 0;
636 SSize_t base; /* Temporary */
638 /* We have both: m * strlen(longer) + b = x_len_longer
639 * m * strlen(shorter) + b = x_len_shorter;
640 * subtracting yields:
641 * m * (strlen(longer) - strlen(shorter))
642 * = x_len_longer - x_len_shorter
643 * But we have set things up so that 'shorter' is 1 byte smaller
644 * than 'longer'. Hence:
645 * m = x_len_longer - x_len_shorter
647 * But if something went wrong, make sure the multiplier is at
650 if (x_len_longer > x_len_shorter) {
651 PL_collxfrm_mult = (STRLEN) x_len_longer - x_len_shorter;
654 PL_collxfrm_mult = 1;
659 * but in case something has gone wrong, make sure it is
661 base = x_len_longer - PL_collxfrm_mult * (sizeof(longer) - 1);
666 /* Add 1 for the trailing NUL */
667 PL_collxfrm_base = base + 1;
671 if (DEBUG_L_TEST || debug_initialization) {
672 PerlIO_printf(Perl_debug_log,
673 "%s:%d: ?UTF-8 locale=%d; x_len_shorter=%"UVuf", "
674 "x_len_longer=%"UVuf","
675 " collate multipler=%"UVuf", collate base=%"UVuf"\n",
677 PL_in_utf8_COLLATE_locale,
678 x_len_shorter, x_len_longer,
679 PL_collxfrm_mult, PL_collxfrm_base);
686 PERL_UNUSED_ARG(newcoll);
687 #endif /* USE_LOCALE_COLLATE */
693 Perl_my_setlocale(pTHX_ int category, const char* locale)
695 /* This, for Windows, emulates POSIX setlocale() behavior. There is no
696 * difference unless the input locale is "", which means on Windows to get
697 * the machine default, which is set via the computer's "Regional and
698 * Language Options" (or its current equivalent). In POSIX, it instead
699 * means to find the locale from the user's environment. This routine
700 * looks in the environment, and, if anything is found, uses that instead
701 * of going to the machine default. If there is no environment override,
702 * the machine default is used, as normal, by calling the real setlocale()
703 * with "". The POSIX behavior is to use the LC_ALL variable if set;
704 * otherwise to use the particular category's variable if set; otherwise to
705 * use the LANG variable. */
707 bool override_LC_ALL = FALSE;
710 if (locale && strEQ(locale, "")) {
712 locale = PerlEnv_getenv("LC_ALL");
718 override_LC_ALL = TRUE;
719 break; /* We already know its variable isn't set */
721 # ifdef USE_LOCALE_TIME
723 locale = PerlEnv_getenv("LC_TIME");
726 # ifdef USE_LOCALE_CTYPE
728 locale = PerlEnv_getenv("LC_CTYPE");
731 # ifdef USE_LOCALE_COLLATE
733 locale = PerlEnv_getenv("LC_COLLATE");
736 # ifdef USE_LOCALE_MONETARY
738 locale = PerlEnv_getenv("LC_MONETARY");
741 # ifdef USE_LOCALE_NUMERIC
743 locale = PerlEnv_getenv("LC_NUMERIC");
746 # ifdef USE_LOCALE_MESSAGES
748 locale = PerlEnv_getenv("LC_MESSAGES");
752 /* This is a category, like PAPER_SIZE that we don't
753 * know about; and so can't provide a wrapper. */
757 locale = PerlEnv_getenv("LANG");
767 result = setlocale(category, locale);
768 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n", __FILE__, __LINE__,
769 _setlocale_debug_string(category, locale, result)));
771 if (! override_LC_ALL) {
775 /* Here the input category was LC_ALL, and we have set it to what is in the
776 * LANG variable or the system default if there is no LANG. But these have
777 * lower priority than the other LC_foo variables, so override it for each
778 * one that is set. (If they are set to "", it means to use the same thing
779 * we just set LC_ALL to, so can skip) */
780 # ifdef USE_LOCALE_TIME
781 result = PerlEnv_getenv("LC_TIME");
782 if (result && strNE(result, "")) {
783 setlocale(LC_TIME, result);
784 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
786 _setlocale_debug_string(LC_TIME, result, "not captured")));
789 # ifdef USE_LOCALE_CTYPE
790 result = PerlEnv_getenv("LC_CTYPE");
791 if (result && strNE(result, "")) {
792 setlocale(LC_CTYPE, result);
793 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
795 _setlocale_debug_string(LC_CTYPE, result, "not captured")));
798 # ifdef USE_LOCALE_COLLATE
799 result = PerlEnv_getenv("LC_COLLATE");
800 if (result && strNE(result, "")) {
801 setlocale(LC_COLLATE, result);
802 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
804 _setlocale_debug_string(LC_COLLATE, result, "not captured")));
807 # ifdef USE_LOCALE_MONETARY
808 result = PerlEnv_getenv("LC_MONETARY");
809 if (result && strNE(result, "")) {
810 setlocale(LC_MONETARY, result);
811 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
813 _setlocale_debug_string(LC_MONETARY, result, "not captured")));
816 # ifdef USE_LOCALE_NUMERIC
817 result = PerlEnv_getenv("LC_NUMERIC");
818 if (result && strNE(result, "")) {
819 setlocale(LC_NUMERIC, result);
820 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
822 _setlocale_debug_string(LC_NUMERIC, result, "not captured")));
825 # ifdef USE_LOCALE_MESSAGES
826 result = PerlEnv_getenv("LC_MESSAGES");
827 if (result && strNE(result, "")) {
828 setlocale(LC_MESSAGES, result);
829 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
831 _setlocale_debug_string(LC_MESSAGES, result, "not captured")));
835 result = setlocale(LC_ALL, NULL);
836 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
838 _setlocale_debug_string(LC_ALL, NULL, result)));
847 * Initialize locale awareness.
850 Perl_init_i18nl10n(pTHX_ int printwarn)
854 * 0 if not to output warning when setup locale is bad
855 * 1 if to output warning based on value of PERL_BADLANG
856 * >1 if to output regardless of PERL_BADLANG
859 * 1 = set ok or not applicable,
860 * 0 = fallback to a locale of lower priority
861 * -1 = fallback to all locales failed, not even to the C locale
863 * Under -DDEBUGGING, if the environment variable PERL_DEBUG_LOCALE_INIT is
864 * set, debugging information is output.
866 * This looks more complicated than it is, mainly due to the #ifdefs.
868 * We try to set LC_ALL to the value determined by the environment. If
869 * there is no LC_ALL on this platform, we try the individual categories we
870 * know about. If this works, we are done.
872 * But if it doesn't work, we have to do something else. We search the
873 * environment variables ourselves instead of relying on the system to do
874 * it. We look at, in order, LC_ALL, LANG, a system default locale (if we
875 * think there is one), and the ultimate fallback "C". This is all done in
876 * the same loop as above to avoid duplicating code, but it makes things
877 * more complex. After the original failure, we add the fallback
878 * possibilities to the list of locales to try, and iterate the loop
879 * through them all until one succeeds.
881 * On Ultrix, the locale MUST come from the environment, so there is
882 * preliminary code to set it. I (khw) am not sure that it is necessary,
883 * and that this couldn't be folded into the loop, but barring any real
884 * platforms to test on, it's staying as-is
886 * A slight complication is that in embedded Perls, the locale may already
887 * be set-up, and we don't want to get it from the normal environment
888 * variables. This is handled by having a special environment variable
889 * indicate we're in this situation. We simply set setlocale's 2nd
890 * parameter to be a NULL instead of "". That indicates to setlocale that
891 * it is not to change anything, but to return the current value,
892 * effectively initializing perl's db to what the locale already is.
894 * We play the same trick with NULL if a LC_ALL succeeds. We call
895 * setlocale() on the individual categores with NULL to get their existing
896 * values for our db, instead of trying to change them.
901 #if defined(USE_LOCALE)
902 #ifdef USE_LOCALE_CTYPE
903 char *curctype = NULL;
904 #endif /* USE_LOCALE_CTYPE */
905 #ifdef USE_LOCALE_COLLATE
906 char *curcoll = NULL;
907 #endif /* USE_LOCALE_COLLATE */
908 #ifdef USE_LOCALE_NUMERIC
910 #endif /* USE_LOCALE_NUMERIC */
912 const char * const language = savepv(PerlEnv_getenv("LANGUAGE"));
915 /* NULL uses the existing already set up locale */
916 const char * const setlocale_init = (PerlEnv_getenv("PERL_SKIP_LOCALE_INIT"))
919 const char* trial_locales[5]; /* 5 = 1 each for "", LC_ALL, LANG, "", C */
920 unsigned int trial_locales_count;
921 const char * const lc_all = savepv(PerlEnv_getenv("LC_ALL"));
922 const char * const lang = savepv(PerlEnv_getenv("LANG"));
923 bool setlocale_failure = FALSE;
927 /* A later getenv() could zap this, so only use here */
928 const char * const bad_lang_use_once = PerlEnv_getenv("PERL_BADLANG");
930 const bool locwarn = (printwarn > 1
932 && (! bad_lang_use_once
934 /* disallow with "" or "0" */
936 && strNE("0", bad_lang_use_once)))));
938 char * sl_result; /* return from setlocale() */
941 /* In some systems you can find out the system default locale
942 * and use that as the fallback locale. */
943 # define SYSTEM_DEFAULT_LOCALE
945 #ifdef SYSTEM_DEFAULT_LOCALE
946 const char *system_default_locale = NULL;
950 debug_initialization = (PerlEnv_getenv("PERL_DEBUG_LOCALE_INIT"))
953 # define DEBUG_LOCALE_INIT(category, locale, result) \
955 if (debug_initialization) { \
956 PerlIO_printf(Perl_debug_log, \
958 __FILE__, __LINE__, \
959 _setlocale_debug_string(category, \
965 # define DEBUG_LOCALE_INIT(a,b,c)
968 #ifndef LOCALE_ENVIRON_REQUIRED
969 PERL_UNUSED_VAR(done);
970 PERL_UNUSED_VAR(locale_param);
974 * Ultrix setlocale(..., "") fails if there are no environment
975 * variables from which to get a locale name.
980 sl_result = my_setlocale(LC_ALL, setlocale_init);
981 DEBUG_LOCALE_INIT(LC_ALL, setlocale_init, sl_result);
985 setlocale_failure = TRUE;
987 if (! setlocale_failure) {
988 # ifdef USE_LOCALE_CTYPE
989 locale_param = (! done && (lang || PerlEnv_getenv("LC_CTYPE")))
992 curctype = my_setlocale(LC_CTYPE, locale_param);
993 DEBUG_LOCALE_INIT(LC_CTYPE, locale_param, sl_result);
995 setlocale_failure = TRUE;
997 curctype = savepv(curctype);
998 # endif /* USE_LOCALE_CTYPE */
999 # ifdef USE_LOCALE_COLLATE
1000 locale_param = (! done && (lang || PerlEnv_getenv("LC_COLLATE")))
1003 curcoll = my_setlocale(LC_COLLATE, locale_param);
1004 DEBUG_LOCALE_INIT(LC_COLLATE, locale_param, sl_result);
1006 setlocale_failure = TRUE;
1008 curcoll = savepv(curcoll);
1009 # endif /* USE_LOCALE_COLLATE */
1010 # ifdef USE_LOCALE_NUMERIC
1011 locale_param = (! done && (lang || PerlEnv_getenv("LC_NUMERIC")))
1014 curnum = my_setlocale(LC_NUMERIC, locale_param);
1015 DEBUG_LOCALE_INIT(LC_NUMERIC, locale_param, sl_result);
1017 setlocale_failure = TRUE;
1019 curnum = savepv(curnum);
1020 # endif /* USE_LOCALE_NUMERIC */
1021 # ifdef USE_LOCALE_MESSAGES
1022 locale_param = (! done && (lang || PerlEnv_getenv("LC_MESSAGES")))
1025 sl_result = my_setlocale(LC_MESSAGES, locale_param);
1026 DEBUG_LOCALE_INIT(LC_MESSAGES, locale_param, sl_result);
1028 setlocale_failure = TRUE;
1030 # endif /* USE_LOCALE_MESSAGES */
1031 # ifdef USE_LOCALE_MONETARY
1032 locale_param = (! done && (lang || PerlEnv_getenv("LC_MONETARY")))
1035 sl_result = my_setlocale(LC_MONETARY, locale_param);
1036 DEBUG_LOCALE_INIT(LC_MONETARY, locale_param, sl_result);
1038 setlocale_failure = TRUE;
1040 # endif /* USE_LOCALE_MONETARY */
1043 # endif /* LC_ALL */
1045 #endif /* !LOCALE_ENVIRON_REQUIRED */
1047 /* We try each locale in the list until we get one that works, or exhaust
1048 * the list. Normally the loop is executed just once. But if setting the
1049 * locale fails, inside the loop we add fallback trials to the array and so
1050 * will execute the loop multiple times */
1051 trial_locales[0] = setlocale_init;
1052 trial_locales_count = 1;
1053 for (i= 0; i < trial_locales_count; i++) {
1054 const char * trial_locale = trial_locales[i];
1058 /* XXX This is to preserve old behavior for LOCALE_ENVIRON_REQUIRED
1059 * when i==0, but I (khw) don't think that behavior makes much
1061 setlocale_failure = FALSE;
1063 #ifdef SYSTEM_DEFAULT_LOCALE
1065 /* On Windows machines, an entry of "" after the 0th means to use
1066 * the system default locale, which we now proceed to get. */
1067 if (strEQ(trial_locale, "")) {
1070 /* Note that this may change the locale, but we are going to do
1071 * that anyway just below */
1072 system_default_locale = setlocale(LC_ALL, "");
1073 DEBUG_LOCALE_INIT(LC_ALL, "", system_default_locale);
1075 /* Skip if invalid or it's already on the list of locales to
1077 if (! system_default_locale) {
1078 goto next_iteration;
1080 for (j = 0; j < trial_locales_count; j++) {
1081 if (strEQ(system_default_locale, trial_locales[j])) {
1082 goto next_iteration;
1086 trial_locale = system_default_locale;
1089 #endif /* SYSTEM_DEFAULT_LOCALE */
1093 sl_result = my_setlocale(LC_ALL, trial_locale);
1094 DEBUG_LOCALE_INIT(LC_ALL, trial_locale, sl_result);
1096 setlocale_failure = TRUE;
1099 /* Since LC_ALL succeeded, it should have changed all the other
1100 * categories it can to its value; so we massage things so that the
1101 * setlocales below just return their category's current values.
1102 * This adequately handles the case in NetBSD where LC_COLLATE may
1103 * not be defined for a locale, and setting it individually will
1104 * fail, whereas setting LC_ALL suceeds, leaving LC_COLLATE set to
1105 * the POSIX locale. */
1106 trial_locale = NULL;
1110 if (!setlocale_failure) {
1111 #ifdef USE_LOCALE_CTYPE
1113 curctype = my_setlocale(LC_CTYPE, trial_locale);
1114 DEBUG_LOCALE_INIT(LC_CTYPE, trial_locale, curctype);
1116 setlocale_failure = TRUE;
1118 curctype = savepv(curctype);
1119 #endif /* USE_LOCALE_CTYPE */
1120 #ifdef USE_LOCALE_COLLATE
1122 curcoll = my_setlocale(LC_COLLATE, trial_locale);
1123 DEBUG_LOCALE_INIT(LC_COLLATE, trial_locale, curcoll);
1125 setlocale_failure = TRUE;
1127 curcoll = savepv(curcoll);
1128 #endif /* USE_LOCALE_COLLATE */
1129 #ifdef USE_LOCALE_NUMERIC
1131 curnum = my_setlocale(LC_NUMERIC, trial_locale);
1132 DEBUG_LOCALE_INIT(LC_NUMERIC, trial_locale, curnum);
1134 setlocale_failure = TRUE;
1136 curnum = savepv(curnum);
1137 #endif /* USE_LOCALE_NUMERIC */
1138 #ifdef USE_LOCALE_MESSAGES
1139 sl_result = my_setlocale(LC_MESSAGES, trial_locale);
1140 DEBUG_LOCALE_INIT(LC_MESSAGES, trial_locale, sl_result);
1142 setlocale_failure = TRUE;
1143 #endif /* USE_LOCALE_MESSAGES */
1144 #ifdef USE_LOCALE_MONETARY
1145 sl_result = my_setlocale(LC_MONETARY, trial_locale);
1146 DEBUG_LOCALE_INIT(LC_MONETARY, trial_locale, sl_result);
1148 setlocale_failure = TRUE;
1149 #endif /* USE_LOCALE_MONETARY */
1151 if (! setlocale_failure) { /* Success */
1156 /* Here, something failed; will need to try a fallback. */
1162 if (locwarn) { /* Output failure info only on the first one */
1165 PerlIO_printf(Perl_error_log,
1166 "perl: warning: Setting locale failed.\n");
1170 PerlIO_printf(Perl_error_log,
1171 "perl: warning: Setting locale failed for the categories:\n\t");
1172 # ifdef USE_LOCALE_CTYPE
1174 PerlIO_printf(Perl_error_log, "LC_CTYPE ");
1175 # endif /* USE_LOCALE_CTYPE */
1176 # ifdef USE_LOCALE_COLLATE
1178 PerlIO_printf(Perl_error_log, "LC_COLLATE ");
1179 # endif /* USE_LOCALE_COLLATE */
1180 # ifdef USE_LOCALE_NUMERIC
1182 PerlIO_printf(Perl_error_log, "LC_NUMERIC ");
1183 # endif /* USE_LOCALE_NUMERIC */
1184 PerlIO_printf(Perl_error_log, "and possibly others\n");
1188 PerlIO_printf(Perl_error_log,
1189 "perl: warning: Please check that your locale settings:\n");
1192 PerlIO_printf(Perl_error_log,
1193 "\tLANGUAGE = %c%s%c,\n",
1194 language ? '"' : '(',
1195 language ? language : "unset",
1196 language ? '"' : ')');
1199 PerlIO_printf(Perl_error_log,
1200 "\tLC_ALL = %c%s%c,\n",
1202 lc_all ? lc_all : "unset",
1203 lc_all ? '"' : ')');
1205 #if defined(USE_ENVIRON_ARRAY)
1208 for (e = environ; *e; e++) {
1209 if (strnEQ(*e, "LC_", 3)
1210 && strnNE(*e, "LC_ALL=", 7)
1211 && (p = strchr(*e, '=')))
1212 PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
1213 (int)(p - *e), *e, p + 1);
1217 PerlIO_printf(Perl_error_log,
1218 "\t(possibly more locale environment variables)\n");
1221 PerlIO_printf(Perl_error_log,
1222 "\tLANG = %c%s%c\n",
1224 lang ? lang : "unset",
1227 PerlIO_printf(Perl_error_log,
1228 " are supported and installed on your system.\n");
1231 /* Calculate what fallback locales to try. We have avoided this
1232 * until we have to, because failure is quite unlikely. This will
1233 * usually change the upper bound of the loop we are in.
1235 * Since the system's default way of setting the locale has not
1236 * found one that works, We use Perl's defined ordering: LC_ALL,
1237 * LANG, and the C locale. We don't try the same locale twice, so
1238 * don't add to the list if already there. (On POSIX systems, the
1239 * LC_ALL element will likely be a repeat of the 0th element "",
1240 * but there's no harm done by doing it explicitly.
1242 * Note that this tries the LC_ALL environment variable even on
1243 * systems which have no LC_ALL locale setting. This may or may
1244 * not have been originally intentional, but there's no real need
1245 * to change the behavior. */
1247 for (j = 0; j < trial_locales_count; j++) {
1248 if (strEQ(lc_all, trial_locales[j])) {
1252 trial_locales[trial_locales_count++] = lc_all;
1257 for (j = 0; j < trial_locales_count; j++) {
1258 if (strEQ(lang, trial_locales[j])) {
1262 trial_locales[trial_locales_count++] = lang;
1266 #if defined(WIN32) && defined(LC_ALL)
1267 /* For Windows, we also try the system default locale before "C".
1268 * (If there exists a Windows without LC_ALL we skip this because
1269 * it gets too complicated. For those, the "C" is the next
1270 * fallback possibility). The "" is the same as the 0th element of
1271 * the array, but the code at the loop above knows to treat it
1272 * differently when not the 0th */
1273 trial_locales[trial_locales_count++] = "";
1276 for (j = 0; j < trial_locales_count; j++) {
1277 if (strEQ("C", trial_locales[j])) {
1281 trial_locales[trial_locales_count++] = "C";
1284 } /* end of first time through the loop */
1290 } /* end of looping through the trial locales */
1292 if (ok < 1) { /* If we tried to fallback */
1294 if (! setlocale_failure) { /* fallback succeeded */
1295 msg = "Falling back to";
1297 else { /* fallback failed */
1299 /* We dropped off the end of the loop, so have to decrement i to
1300 * get back to the value the last time through */
1304 msg = "Failed to fall back to";
1306 /* To continue, we should use whatever values we've got */
1307 #ifdef USE_LOCALE_CTYPE
1309 curctype = savepv(setlocale(LC_CTYPE, NULL));
1310 DEBUG_LOCALE_INIT(LC_CTYPE, NULL, curctype);
1311 #endif /* USE_LOCALE_CTYPE */
1312 #ifdef USE_LOCALE_COLLATE
1314 curcoll = savepv(setlocale(LC_COLLATE, NULL));
1315 DEBUG_LOCALE_INIT(LC_COLLATE, NULL, curcoll);
1316 #endif /* USE_LOCALE_COLLATE */
1317 #ifdef USE_LOCALE_NUMERIC
1319 curnum = savepv(setlocale(LC_NUMERIC, NULL));
1320 DEBUG_LOCALE_INIT(LC_NUMERIC, NULL, curnum);
1321 #endif /* USE_LOCALE_NUMERIC */
1325 const char * description;
1326 const char * name = "";
1327 if (strEQ(trial_locales[i], "C")) {
1328 description = "the standard locale";
1331 #ifdef SYSTEM_DEFAULT_LOCALE
1332 else if (strEQ(trial_locales[i], "")) {
1333 description = "the system default locale";
1334 if (system_default_locale) {
1335 name = system_default_locale;
1338 #endif /* SYSTEM_DEFAULT_LOCALE */
1340 description = "a fallback locale";
1341 name = trial_locales[i];
1343 if (name && strNE(name, "")) {
1344 PerlIO_printf(Perl_error_log,
1345 "perl: warning: %s %s (\"%s\").\n", msg, description, name);
1348 PerlIO_printf(Perl_error_log,
1349 "perl: warning: %s %s.\n", msg, description);
1352 } /* End of tried to fallback */
1354 #ifdef USE_LOCALE_CTYPE
1355 new_ctype(curctype);
1356 #endif /* USE_LOCALE_CTYPE */
1358 #ifdef USE_LOCALE_COLLATE
1359 new_collate(curcoll);
1360 #endif /* USE_LOCALE_COLLATE */
1362 #ifdef USE_LOCALE_NUMERIC
1363 new_numeric(curnum);
1364 #endif /* USE_LOCALE_NUMERIC */
1366 #if defined(USE_PERLIO) && defined(USE_LOCALE_CTYPE)
1367 /* Set PL_utf8locale to TRUE if using PerlIO _and_ the current LC_CTYPE
1368 * locale is UTF-8. If PL_utf8locale and PL_unicode (set by -C or by
1369 * $ENV{PERL_UNICODE}) are true, perl.c:S_parse_body() will turn on the
1370 * PerlIO :utf8 layer on STDIN, STDOUT, STDERR, _and_ the default open
1372 PL_utf8locale = _is_cur_LC_category_utf8(LC_CTYPE);
1374 /* Set PL_unicode to $ENV{PERL_UNICODE} if using PerlIO.
1375 This is an alternative to using the -C command line switch
1376 (the -C if present will override this). */
1378 const char *p = PerlEnv_getenv("PERL_UNICODE");
1379 PL_unicode = p ? parse_unicode_opts(&p) : 0;
1380 if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
1385 #ifdef USE_LOCALE_CTYPE
1387 #endif /* USE_LOCALE_CTYPE */
1388 #ifdef USE_LOCALE_COLLATE
1390 #endif /* USE_LOCALE_COLLATE */
1391 #ifdef USE_LOCALE_NUMERIC
1393 #endif /* USE_LOCALE_NUMERIC */
1402 #else /* !USE_LOCALE */
1403 PERL_UNUSED_ARG(printwarn);
1404 #endif /* USE_LOCALE */
1407 /* So won't continue to output stuff */
1408 debug_initialization = FALSE;
1414 #ifdef USE_LOCALE_COLLATE
1417 Perl__mem_collxfrm(pTHX_ const char *input_string,
1418 STRLEN len, /* Length of 'input_string' */
1419 STRLEN *xlen, /* Set to length of returned string
1420 (not including the collation index
1422 bool utf8 /* Is the input in UTF-8? */
1426 /* _mem_collxfrm() is a bit like strxfrm() but with two important
1427 * differences. First, it handles embedded NULs. Second, it allocates a bit
1428 * more memory than needed for the transformed data itself. The real
1429 * transformed data begins at offset COLLXFRM_HDR_LEN. *xlen is set to
1430 * the length of that, and doesn't include the collation index size.
1431 * Please see sv_collxfrm() to see how this is used. */
1433 #define COLLXFRM_HDR_LEN sizeof(PL_collation_ix)
1435 char * s = (char *) input_string;
1436 STRLEN s_strlen = strlen(input_string);
1438 STRLEN xAlloc; /* xalloc is a reserved word in VC */
1439 STRLEN length_in_chars;
1440 bool first_time = TRUE; /* Cleared after first loop iteration */
1442 PERL_ARGS_ASSERT__MEM_COLLXFRM;
1444 /* Must be NUL-terminated */
1445 assert(*(input_string + len) == '\0');
1447 /* If this locale has defective collation, skip */
1448 if (PL_collxfrm_base == 0 && PL_collxfrm_mult == 0) {
1452 /* Replace any embedded NULs with the control that sorts before any others.
1453 * This will give as good as possible results on strings that don't
1454 * otherwise contain that character, but otherwise there may be
1455 * less-than-perfect results with that character and NUL. This is
1456 * unavoidable unless we replace strxfrm with our own implementation.
1458 * XXX This code may be overkill. khw wrote it before realizing that if
1459 * you change a NUL into some other character, that that may change the
1460 * strxfrm results if that character is part of a sequence with other
1461 * characters for weight calculations. To minimize the chances of this,
1462 * now the replacement is restricted to another control (likely to be
1463 * \001). But the full generality has been retained.
1465 * This is one of the few places in the perl core, where we can use
1466 * standard functions like strlen() and strcat(). It's because we're
1467 * looking for NULs. */
1468 if (s_strlen < len) {
1471 STRLEN cur_min_char_len;
1473 /* If we don't know what control character sorts lowest for this
1474 * locale, find it */
1475 if (*PL_strxfrm_min_char == '\0') {
1478 U8 cur_min_cp = 1; /* The code point that sorts lowest, so far */
1480 char * cur_min_x = NULL; /* And its xfrm, (except it also
1481 includes the collation index
1484 /* Look through all legal code points (NUL isn't) */
1485 for (j = 1; j < 256; j++) {
1486 char * x; /* j's xfrm plus collation index */
1487 STRLEN x_len; /* length of 'x' */
1488 STRLEN trial_len = 1;
1490 /* Create a 1 byte string of the current code point, but with
1491 * room to be 2 bytes */
1492 char cur_source[] = { (char) j, '\0' , '\0' };
1494 if (PL_in_utf8_COLLATE_locale) {
1495 if (! isCNTRL_L1(j)) {
1499 /* If needs to be 2 bytes, find them */
1500 if (! UVCHR_IS_INVARIANT(j)) {
1501 char * d = cur_source;
1502 append_utf8_from_native_byte((U8) j, (U8 **) &d);
1506 else if (! isCNTRL_LC(j)) {
1510 /* Then transform it */
1511 x = _mem_collxfrm(cur_source, trial_len, &x_len,
1512 PL_in_utf8_COLLATE_locale);
1514 /* If something went wrong (which it shouldn't), just
1515 * ignore this code point */
1517 || strlen(x + COLLXFRM_HDR_LEN) < x_len)
1522 /* If this character's transformation is lower than
1523 * the current lowest, this one becomes the lowest */
1524 if ( cur_min_x == NULL
1525 || strLT(x + COLLXFRM_HDR_LEN,
1526 cur_min_x + COLLXFRM_HDR_LEN))
1528 PL_strxfrm_min_char[0] = cur_source[0];
1529 PL_strxfrm_min_char[1] = cur_source[1];
1530 PL_strxfrm_min_char[2] = cur_source[2];
1539 } /* end of loop through all bytes */
1541 /* Unlikely, but possible, if there aren't any controls in the
1542 * locale, arbitrarily use \001 */
1543 if (cur_min_x == NULL) {
1544 STRLEN x_len; /* temporary */
1545 cur_min_x = _mem_collxfrm("\001", 1, &x_len,
1546 PL_in_utf8_COLLATE_locale);
1547 /* cur_min_cp was already initialized to 1 */
1550 DEBUG_L(PerlIO_printf(Perl_debug_log,
1551 "_mem_collxfrm: lowest collating control in the 0-255 "
1552 "range in locale %s is 0x%02X\n",
1555 if (DEBUG_Lv_TEST) {
1557 PerlIO_printf(Perl_debug_log, "Its xfrm is");
1558 for (i = 0; i < strlen(cur_min_x + COLLXFRM_HDR_LEN); i ++) {
1559 PerlIO_printf(Perl_debug_log, " %02x",
1560 (U8) *(cur_min_x + COLLXFRM_HDR_LEN + i));
1562 PerlIO_printf(Perl_debug_log, "\n");
1565 Safefree(cur_min_x);
1568 /* The worst case length for the replaced string would be if every
1569 * character in it is NUL. Multiply that by the length of each
1570 * replacement, and allow for a trailing NUL */
1571 cur_min_char_len = strlen(PL_strxfrm_min_char);
1572 Newx(sans_nuls, (len * cur_min_char_len) + 1, char);
1576 /* Replace each NUL with the lowest collating control. Loop until have
1577 * exhausted all the NULs */
1578 while (s + s_strlen < e) {
1579 strcat(sans_nuls, s);
1581 /* Do the actual replacement */
1582 strcat(sans_nuls, PL_strxfrm_min_char);
1584 /* Move past the input NUL */
1586 s_strlen = strlen(s);
1589 /* And add anything that trails the final NUL */
1590 strcat(sans_nuls, s);
1592 /* Switch so below we transform this modified string */
1597 /* Make sure the UTF8ness of the string and locale match */
1598 if (utf8 != PL_in_utf8_COLLATE_locale) {
1599 const char * const t = s; /* Temporary so we can later find where the
1602 /* Here they don't match. Change the string's to be what the locale is
1605 if (! utf8) { /* locale is UTF-8, but input isn't; upgrade the input */
1606 s = (char *) bytes_to_utf8((const U8 *) s, &len);
1609 else { /* locale is not UTF-8; but input is; downgrade the input */
1611 s = (char *) bytes_from_utf8((const U8 *) s, &len, &utf8);
1613 /* If the downgrade was successful we are done, but if the input
1614 * contains things that require UTF-8 to represent, have to do
1615 * damage control ... */
1616 if (UNLIKELY(utf8)) {
1618 /* What we do is construct a non-UTF-8 string with
1619 * 1) the characters representable by a single byte converted
1620 * to be so (if necessary);
1621 * 2) and the rest converted to collate the same as the
1622 * highest collating representable character. That makes
1623 * them collate at the end. This is similar to how we
1624 * handle embedded NULs, but we use the highest collating
1625 * code point instead of the smallest. Like the NUL case,
1626 * this isn't perfect, but is the best we can reasonably
1627 * do. Every above-255 code point will sort the same as
1628 * the highest-sorting 0-255 code point. If that code
1629 * point can combine in a sequence with some other code
1630 * points for weight calculations, us changing something to
1631 * be it can adversely affect the results. But in most
1632 * cases, it should work reasonably. And note that this is
1633 * really an illegal situation: using code points above 255
1634 * on a locale where only 0-255 are valid. If two strings
1635 * sort entirely equal, then the sort order for the
1636 * above-255 code points will be in code point order. */
1640 /* If we haven't calculated the code point with the maximum
1641 * collating order for this locale, do so now */
1642 if (! PL_strxfrm_max_cp) {
1645 /* The current transformed string that collates the
1646 * highest (except it also includes the prefixed collation
1648 char * cur_max_x = NULL;
1650 /* Look through all legal code points (NUL isn't) */
1651 for (j = 1; j < 256; j++) {
1655 /* Create a 1-char string of the current code point. */
1656 char cur_source[] = { (char) j, '\0' };
1658 /* Then transform it */
1659 x = _mem_collxfrm(cur_source, 1, &x_len, FALSE);
1661 /* If something went wrong (which it shouldn't), just
1662 * ignore this code point */
1668 /* If this character's transformation is higher than
1669 * the current highest, this one becomes the highest */
1670 if ( cur_max_x == NULL
1671 || strGT(x + COLLXFRM_HDR_LEN,
1672 cur_max_x + COLLXFRM_HDR_LEN))
1674 PL_strxfrm_max_cp = j;
1682 DEBUG_L(PerlIO_printf(Perl_debug_log,
1683 "_mem_collxfrm: highest 1-byte collating character"
1684 " in locale %s is 0x%02X\n",
1686 PL_strxfrm_max_cp));
1687 if (DEBUG_Lv_TEST) {
1689 PerlIO_printf(Perl_debug_log, "Its xfrm is ");
1691 i < strlen(cur_max_x + COLLXFRM_HDR_LEN);
1694 PerlIO_printf(Perl_debug_log, " %02x",
1695 (U8) cur_max_x[i + COLLXFRM_HDR_LEN]);
1697 PerlIO_printf(Perl_debug_log, "\n");
1700 Safefree(cur_max_x);
1703 /* Here we know which legal code point collates the highest.
1704 * We are ready to construct the non-UTF-8 string. The length
1705 * will be at least 1 byte smaller than the input string
1706 * (because we changed at least one 2-byte character into a
1707 * single byte), but that is eaten up by the trailing NUL */
1714 for (i = 0; i < len; i+= UTF8SKIP(t + i)) {
1716 if (UTF8_IS_INVARIANT(cur_char)) {
1719 else if (UTF8_IS_DOWNGRADEABLE_START(cur_char)) {
1720 s[d++] = EIGHT_BIT_UTF8_TO_NATIVE(cur_char, t[i+1]);
1722 else { /* Replace illegal cp with highest collating
1724 s[d++] = PL_strxfrm_max_cp;
1728 Renew(s, d, char); /* Free up unused space */
1733 /* Here, we have constructed a modified version of the input. It could
1734 * be that we already had a modified copy before we did this version.
1735 * If so, that copy is no longer needed */
1736 if (t != input_string) {
1741 length_in_chars = (utf8)
1742 ? utf8_length((U8 *) s, (U8 *) s + len)
1745 /* The first element in the output is the collation id, used by
1746 * sv_collxfrm(); then comes the space for the transformed string. The
1747 * equation should give us a good estimate as to how much is needed */
1748 xAlloc = COLLXFRM_HDR_LEN
1750 + (PL_collxfrm_mult * length_in_chars);
1751 Newx(xbuf, xAlloc, char);
1752 if (UNLIKELY(! xbuf))
1755 /* Store the collation id */
1756 *(U32*)xbuf = PL_collation_ix;
1758 /* Then the transformation of the input. We loop until successful, or we
1761 *xlen = strxfrm(xbuf + COLLXFRM_HDR_LEN, s, xAlloc - COLLXFRM_HDR_LEN);
1763 /* If the transformed string occupies less space than we told strxfrm()
1764 * was available, it means it successfully transformed the whole
1766 if (*xlen < xAlloc - COLLXFRM_HDR_LEN) {
1768 /* If the first try didn't get it, it means our prediction was low.
1769 * Modify the coefficients so that we predict a larger value in any
1770 * future transformations */
1772 STRLEN needed = *xlen + 1; /* +1 For trailing NUL */
1773 STRLEN computed_guess = PL_collxfrm_base
1774 + (PL_collxfrm_mult * length_in_chars);
1775 const STRLEN new_m = needed / length_in_chars;
1777 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
1778 "%s: %d: initial size of %"UVuf" bytes for a length "
1779 "%"UVuf" string was insufficient, %"UVuf" needed\n",
1781 (UV) computed_guess, (UV) length_in_chars, (UV) needed));
1783 /* If slope increased, use it, but discard this result for
1784 * length 1 strings, as we can't be sure that it's a real slope
1786 if (length_in_chars > 1 && new_m > PL_collxfrm_mult) {
1788 STRLEN old_m = PL_collxfrm_mult;
1789 STRLEN old_b = PL_collxfrm_base;
1791 PL_collxfrm_mult = new_m;
1792 PL_collxfrm_base = 1; /* +1 For trailing NUL */
1793 computed_guess = PL_collxfrm_base
1794 + (PL_collxfrm_mult * length_in_chars);
1795 if (computed_guess < needed) {
1796 PL_collxfrm_base += needed - computed_guess;
1799 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
1800 "%s: %d: slope is now %"UVuf"; was %"UVuf", base "
1801 "is now %"UVuf"; was %"UVuf"\n",
1803 (UV) PL_collxfrm_mult, (UV) old_m,
1804 (UV) PL_collxfrm_base, (UV) old_b));
1806 else { /* Slope didn't change, but 'b' did */
1807 const STRLEN new_b = needed
1810 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
1811 "%s: %d: base is now %"UVuf"; was %"UVuf"\n",
1813 (UV) new_b, (UV) PL_collxfrm_base));
1814 PL_collxfrm_base = new_b;
1821 if (UNLIKELY(*xlen >= PERL_INT_MAX))
1824 /* A well-behaved strxfrm() returns exactly how much space it needs
1825 * (not including the trailing NUL) when it fails due to not enough
1826 * space being provided. Assume that this is the case unless it's been
1827 * proven otherwise */
1828 if (LIKELY(PL_strxfrm_is_behaved) && first_time) {
1829 xAlloc = *xlen + COLLXFRM_HDR_LEN + 1;
1831 else { /* Here, either:
1832 * 1) The strxfrm() has previously shown bad behavior; or
1833 * 2) It isn't the first time through the loop, which means
1834 * that the strxfrm() is now showing bad behavior, because
1835 * we gave it what it said was needed in the previous
1836 * iteration, and it came back saying it needed still more.
1837 * (Many versions of cygwin fit this. When the buffer size
1838 * isn't sufficient, they return the input size instead of
1839 * how much is needed.)
1840 * Increase the buffer size by a fixed percentage and try again. */
1841 xAlloc += (xAlloc / 4) + 1;
1842 PL_strxfrm_is_behaved = FALSE;
1845 if (DEBUG_Lv_TEST || debug_initialization) {
1846 PerlIO_printf(Perl_debug_log,
1847 "_mem_collxfrm required more space than previously calculated"
1848 " for locale %s, trying again with new guess=%d+%"UVuf"\n",
1849 PL_collation_name, (int) COLLXFRM_HDR_LEN,
1850 (UV) xAlloc - COLLXFRM_HDR_LEN);
1855 Renew(xbuf, xAlloc, char);
1856 if (UNLIKELY(! xbuf))
1864 if (DEBUG_Lv_TEST || debug_initialization) {
1866 PerlIO_printf(Perl_debug_log,
1867 "_mem_collxfrm[%d]: returning %"UVuf" for locale %s '%s'\n",
1868 PL_collation_ix, *xlen, PL_collation_name, input_string);
1869 PerlIO_printf(Perl_debug_log, "Its xfrm is");
1870 for (i = COLLXFRM_HDR_LEN; i < *xlen + COLLXFRM_HDR_LEN; i++) {
1871 PerlIO_printf(Perl_debug_log, " %02x", (U8) xbuf[i]);
1873 PerlIO_printf(Perl_debug_log, "\n");
1877 /* Free up unneeded space; retain ehough for trailing NUL */
1878 Renew(xbuf, COLLXFRM_HDR_LEN + *xlen + 1, char);
1880 if (s != input_string) {
1888 if (s != input_string) {
1893 if (DEBUG_Lv_TEST || debug_initialization) {
1894 PerlIO_printf(Perl_debug_log, "_mem_collxfrm[%d] returning NULL\n",
1901 #endif /* USE_LOCALE_COLLATE */
1906 Perl__is_cur_LC_category_utf8(pTHX_ int category)
1908 /* Returns TRUE if the current locale for 'category' is UTF-8; FALSE
1909 * otherwise. 'category' may not be LC_ALL. If the platform doesn't have
1910 * nl_langinfo(), nor MB_CUR_MAX, this employs a heuristic, which hence
1911 * could give the wrong result. The result will very likely be correct for
1912 * languages that have commonly used non-ASCII characters, but for notably
1913 * English, it comes down to if the locale's name ends in something like
1914 * "UTF-8". It errs on the side of not being a UTF-8 locale. */
1916 char *save_input_locale = NULL;
1920 assert(category != LC_ALL);
1923 /* First dispose of the trivial cases */
1924 save_input_locale = setlocale(category, NULL);
1925 if (! save_input_locale) {
1926 DEBUG_L(PerlIO_printf(Perl_debug_log,
1927 "Could not find current locale for category %d\n",
1929 return FALSE; /* XXX maybe should croak */
1931 save_input_locale = stdize_locale(savepv(save_input_locale));
1932 if (isNAME_C_OR_POSIX(save_input_locale)) {
1933 DEBUG_L(PerlIO_printf(Perl_debug_log,
1934 "Current locale for category %d is %s\n",
1935 category, save_input_locale));
1936 Safefree(save_input_locale);
1940 #if defined(USE_LOCALE_CTYPE) \
1941 && (defined(MB_CUR_MAX) || (defined(HAS_NL_LANGINFO) && defined(CODESET)))
1943 { /* Next try nl_langinfo or MB_CUR_MAX if available */
1945 char *save_ctype_locale = NULL;
1948 if (category != LC_CTYPE) { /* These work only on LC_CTYPE */
1950 /* Get the current LC_CTYPE locale */
1951 save_ctype_locale = setlocale(LC_CTYPE, NULL);
1952 if (! save_ctype_locale) {
1953 DEBUG_L(PerlIO_printf(Perl_debug_log,
1954 "Could not find current locale for LC_CTYPE\n"));
1955 goto cant_use_nllanginfo;
1957 save_ctype_locale = stdize_locale(savepv(save_ctype_locale));
1959 /* If LC_CTYPE and the desired category use the same locale, this
1960 * means that finding the value for LC_CTYPE is the same as finding
1961 * the value for the desired category. Otherwise, switch LC_CTYPE
1962 * to the desired category's locale */
1963 if (strEQ(save_ctype_locale, save_input_locale)) {
1964 Safefree(save_ctype_locale);
1965 save_ctype_locale = NULL;
1967 else if (! setlocale(LC_CTYPE, save_input_locale)) {
1968 DEBUG_L(PerlIO_printf(Perl_debug_log,
1969 "Could not change LC_CTYPE locale to %s\n",
1970 save_input_locale));
1971 Safefree(save_ctype_locale);
1972 goto cant_use_nllanginfo;
1976 DEBUG_L(PerlIO_printf(Perl_debug_log, "Current LC_CTYPE locale=%s\n",
1977 save_input_locale));
1979 /* Here the current LC_CTYPE is set to the locale of the category whose
1980 * information is desired. This means that nl_langinfo() and MB_CUR_MAX
1981 * should give the correct results */
1983 # if defined(HAS_NL_LANGINFO) && defined(CODESET)
1985 char *codeset = nl_langinfo(CODESET);
1986 if (codeset && strNE(codeset, "")) {
1987 codeset = savepv(codeset);
1989 /* If we switched LC_CTYPE, switch back */
1990 if (save_ctype_locale) {
1991 setlocale(LC_CTYPE, save_ctype_locale);
1992 Safefree(save_ctype_locale);
1995 is_utf8 = foldEQ(codeset, STR_WITH_LEN("UTF-8"))
1996 || foldEQ(codeset, STR_WITH_LEN("UTF8"));
1998 DEBUG_L(PerlIO_printf(Perl_debug_log,
1999 "\tnllanginfo returned CODESET '%s'; ?UTF8 locale=%d\n",
2002 Safefree(save_input_locale);
2010 /* Here, either we don't have nl_langinfo, or it didn't return a
2011 * codeset. Try MB_CUR_MAX */
2013 /* Standard UTF-8 needs at least 4 bytes to represent the maximum
2014 * Unicode code point. Since UTF-8 is the only non-single byte
2015 * encoding we handle, we just say any such encoding is UTF-8, and if
2016 * turns out to be wrong, other things will fail */
2017 is_utf8 = MB_CUR_MAX >= 4;
2019 DEBUG_L(PerlIO_printf(Perl_debug_log,
2020 "\tMB_CUR_MAX=%d; ?UTF8 locale=%d\n",
2021 (int) MB_CUR_MAX, is_utf8));
2023 Safefree(save_input_locale);
2027 /* ... But, most system that have MB_CUR_MAX will also have mbtowc(),
2028 * since they are both in the C99 standard. We can feed a known byte
2029 * string to the latter function, and check that it gives the expected
2033 PERL_UNUSED_RESULT(mbtowc(&wc, NULL, 0));/* Reset any shift state */
2035 if ((size_t)mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8))
2036 != strlen(HYPHEN_UTF8)
2037 || wc != (wchar_t) 0x2010)
2040 DEBUG_L(PerlIO_printf(Perl_debug_log, "\thyphen=U+%x\n", (unsigned int)wc));
2041 DEBUG_L(PerlIO_printf(Perl_debug_log,
2042 "\treturn from mbtowc=%d; errno=%d; ?UTF8 locale=0\n",
2043 mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8)), errno));
2048 /* If we switched LC_CTYPE, switch back */
2049 if (save_ctype_locale) {
2050 setlocale(LC_CTYPE, save_ctype_locale);
2051 Safefree(save_ctype_locale);
2058 cant_use_nllanginfo:
2060 #else /* nl_langinfo should work if available, so don't bother compiling this
2061 fallback code. The final fallback of looking at the name is
2062 compiled, and will be executed if nl_langinfo fails */
2064 /* nl_langinfo not available or failed somehow. Next try looking at the
2065 * currency symbol to see if it disambiguates things. Often that will be
2066 * in the native script, and if the symbol isn't in UTF-8, we know that the
2067 * locale isn't. If it is non-ASCII UTF-8, we infer that the locale is
2068 * too, as the odds of a non-UTF8 string being valid UTF-8 are quite small
2071 #ifdef HAS_LOCALECONV
2072 # ifdef USE_LOCALE_MONETARY
2074 char *save_monetary_locale = NULL;
2075 bool only_ascii = FALSE;
2076 bool is_utf8 = FALSE;
2079 /* Like above for LC_CTYPE, we first set LC_MONETARY to the locale of
2080 * the desired category, if it isn't that locale already */
2082 if (category != LC_MONETARY) {
2084 save_monetary_locale = setlocale(LC_MONETARY, NULL);
2085 if (! save_monetary_locale) {
2086 DEBUG_L(PerlIO_printf(Perl_debug_log,
2087 "Could not find current locale for LC_MONETARY\n"));
2088 goto cant_use_monetary;
2090 save_monetary_locale = stdize_locale(savepv(save_monetary_locale));
2092 if (strEQ(save_monetary_locale, save_input_locale)) {
2093 Safefree(save_monetary_locale);
2094 save_monetary_locale = NULL;
2096 else if (! setlocale(LC_MONETARY, save_input_locale)) {
2097 DEBUG_L(PerlIO_printf(Perl_debug_log,
2098 "Could not change LC_MONETARY locale to %s\n",
2099 save_input_locale));
2100 Safefree(save_monetary_locale);
2101 goto cant_use_monetary;
2105 /* Here the current LC_MONETARY is set to the locale of the category
2106 * whose information is desired. */
2110 || ! lc->currency_symbol
2111 || is_invariant_string((U8 *) lc->currency_symbol, 0))
2113 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));
2117 is_utf8 = is_utf8_string((U8 *) lc->currency_symbol, 0);
2120 /* If we changed it, restore LC_MONETARY to its original locale */
2121 if (save_monetary_locale) {
2122 setlocale(LC_MONETARY, save_monetary_locale);
2123 Safefree(save_monetary_locale);
2128 /* It isn't a UTF-8 locale if the symbol is not legal UTF-8;
2129 * otherwise assume the locale is UTF-8 if and only if the symbol
2130 * is non-ascii UTF-8. */
2131 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?Currency symbol for %s is UTF-8=%d\n",
2132 save_input_locale, is_utf8));
2133 Safefree(save_input_locale);
2139 # endif /* USE_LOCALE_MONETARY */
2140 #endif /* HAS_LOCALECONV */
2142 #if defined(HAS_STRFTIME) && defined(USE_LOCALE_TIME)
2144 /* Still haven't found a non-ASCII string to disambiguate UTF-8 or not. Try
2145 * the names of the months and weekdays, timezone, and am/pm indicator */
2147 char *save_time_locale = NULL;
2149 bool is_dst = FALSE;
2153 char * formatted_time;
2156 /* Like above for LC_MONETARY, we set LC_TIME to the locale of the
2157 * desired category, if it isn't that locale already */
2159 if (category != LC_TIME) {
2161 save_time_locale = setlocale(LC_TIME, NULL);
2162 if (! save_time_locale) {
2163 DEBUG_L(PerlIO_printf(Perl_debug_log,
2164 "Could not find current locale for LC_TIME\n"));
2167 save_time_locale = stdize_locale(savepv(save_time_locale));
2169 if (strEQ(save_time_locale, save_input_locale)) {
2170 Safefree(save_time_locale);
2171 save_time_locale = NULL;
2173 else if (! setlocale(LC_TIME, save_input_locale)) {
2174 DEBUG_L(PerlIO_printf(Perl_debug_log,
2175 "Could not change LC_TIME locale to %s\n",
2176 save_input_locale));
2177 Safefree(save_time_locale);
2182 /* Here the current LC_TIME is set to the locale of the category
2183 * whose information is desired. Look at all the days of the week and
2184 * month names, and the timezone and am/pm indicator for UTF-8 variant
2185 * characters. The first such a one found will tell us if the locale
2186 * is UTF-8 or not */
2188 for (i = 0; i < 7 + 12; i++) { /* 7 days; 12 months */
2189 formatted_time = my_strftime("%A %B %Z %p",
2190 0, 0, hour, dom, month, 112, 0, 0, is_dst);
2191 if (! formatted_time || is_invariant_string((U8 *) formatted_time, 0)) {
2193 /* Here, we didn't find a non-ASCII. Try the next time through
2194 * with the complemented dst and am/pm, and try with the next
2195 * weekday. After we have gotten all weekdays, try the next
2198 hour = (hour + 12) % 24;
2206 /* Here, we have a non-ASCII. Return TRUE is it is valid UTF8;
2207 * false otherwise. But first, restore LC_TIME to its original
2208 * locale if we changed it */
2209 if (save_time_locale) {
2210 setlocale(LC_TIME, save_time_locale);
2211 Safefree(save_time_locale);
2214 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?time-related strings for %s are UTF-8=%d\n",
2216 is_utf8_string((U8 *) formatted_time, 0)));
2217 Safefree(save_input_locale);
2218 return is_utf8_string((U8 *) formatted_time, 0);
2221 /* Falling off the end of the loop indicates all the names were just
2222 * ASCII. Go on to the next test. If we changed it, restore LC_TIME
2223 * to its original locale */
2224 if (save_time_locale) {
2225 setlocale(LC_TIME, save_time_locale);
2226 Safefree(save_time_locale);
2228 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));
2234 #if 0 && defined(USE_LOCALE_MESSAGES) && defined(HAS_SYS_ERRLIST)
2236 /* This code is ifdefd out because it was found to not be necessary in testing
2237 * on our dromedary test machine, which has over 700 locales. There, this
2238 * added no value to looking at the currency symbol and the time strings. I
2239 * left it in so as to avoid rewriting it if real-world experience indicates
2240 * that dromedary is an outlier. Essentially, instead of returning abpve if we
2241 * haven't found illegal utf8, we continue on and examine all the strerror()
2242 * messages on the platform for utf8ness. If all are ASCII, we still don't
2243 * know the answer; but otherwise we have a pretty good indication of the
2244 * utf8ness. The reason this doesn't help much is that the messages may not
2245 * have been translated into the locale. The currency symbol and time strings
2246 * are much more likely to have been translated. */
2249 bool is_utf8 = FALSE;
2250 bool non_ascii = FALSE;
2251 char *save_messages_locale = NULL;
2252 const char * errmsg = NULL;
2254 /* Like above, we set LC_MESSAGES to the locale of the desired
2255 * category, if it isn't that locale already */
2257 if (category != LC_MESSAGES) {
2259 save_messages_locale = setlocale(LC_MESSAGES, NULL);
2260 if (! save_messages_locale) {
2261 DEBUG_L(PerlIO_printf(Perl_debug_log,
2262 "Could not find current locale for LC_MESSAGES\n"));
2263 goto cant_use_messages;
2265 save_messages_locale = stdize_locale(savepv(save_messages_locale));
2267 if (strEQ(save_messages_locale, save_input_locale)) {
2268 Safefree(save_messages_locale);
2269 save_messages_locale = NULL;
2271 else if (! setlocale(LC_MESSAGES, save_input_locale)) {
2272 DEBUG_L(PerlIO_printf(Perl_debug_log,
2273 "Could not change LC_MESSAGES locale to %s\n",
2274 save_input_locale));
2275 Safefree(save_messages_locale);
2276 goto cant_use_messages;
2280 /* Here the current LC_MESSAGES is set to the locale of the category
2281 * whose information is desired. Look through all the messages. We
2282 * can't use Strerror() here because it may expand to code that
2283 * segfaults in miniperl */
2285 for (e = 0; e <= sys_nerr; e++) {
2287 errmsg = sys_errlist[e];
2288 if (errno || !errmsg) {
2291 errmsg = savepv(errmsg);
2292 if (! is_invariant_string((U8 *) errmsg, 0)) {
2294 is_utf8 = is_utf8_string((U8 *) errmsg, 0);
2300 /* And, if we changed it, restore LC_MESSAGES to its original locale */
2301 if (save_messages_locale) {
2302 setlocale(LC_MESSAGES, save_messages_locale);
2303 Safefree(save_messages_locale);
2308 /* Any non-UTF-8 message means not a UTF-8 locale; if all are valid,
2309 * any non-ascii means it is one; otherwise we assume it isn't */
2310 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?error messages for %s are UTF-8=%d\n",
2313 Safefree(save_input_locale);
2317 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));
2323 #endif /* the code that is compiled when no nl_langinfo */
2325 #ifndef EBCDIC /* On os390, even if the name ends with "UTF-8', it isn't a
2327 /* As a last resort, look at the locale name to see if it matches
2328 * qr/UTF -? * 8 /ix, or some other common locale names. This "name", the
2329 * return of setlocale(), is actually defined to be opaque, so we can't
2330 * really rely on the absence of various substrings in the name to indicate
2331 * its UTF-8ness, but if it has UTF8 in the name, it is extremely likely to
2332 * be a UTF-8 locale. Similarly for the other common names */
2334 final_pos = strlen(save_input_locale) - 1;
2335 if (final_pos >= 3) {
2336 char *name = save_input_locale;
2338 /* Find next 'U' or 'u' and look from there */
2339 while ((name += strcspn(name, "Uu") + 1)
2340 <= save_input_locale + final_pos - 2)
2342 if (!isALPHA_FOLD_NE(*name, 't')
2343 || isALPHA_FOLD_NE(*(name + 1), 'f'))
2348 if (*(name) == '-') {
2349 if ((name > save_input_locale + final_pos - 1)) {
2354 if (*(name) == '8') {
2355 DEBUG_L(PerlIO_printf(Perl_debug_log,
2356 "Locale %s ends with UTF-8 in name\n",
2357 save_input_locale));
2358 Safefree(save_input_locale);
2362 DEBUG_L(PerlIO_printf(Perl_debug_log,
2363 "Locale %s doesn't end with UTF-8 in name\n",
2364 save_input_locale));
2369 /* http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756.aspx */
2371 && *(save_input_locale + final_pos - 0) == '1'
2372 && *(save_input_locale + final_pos - 1) == '0'
2373 && *(save_input_locale + final_pos - 2) == '0'
2374 && *(save_input_locale + final_pos - 3) == '5'
2375 && *(save_input_locale + final_pos - 4) == '6')
2377 DEBUG_L(PerlIO_printf(Perl_debug_log,
2378 "Locale %s ends with 10056 in name, is UTF-8 locale\n",
2379 save_input_locale));
2380 Safefree(save_input_locale);
2385 /* Other common encodings are the ISO 8859 series, which aren't UTF-8. But
2386 * since we are about to return FALSE anyway, there is no point in doing
2387 * this extra work */
2389 if (instr(save_input_locale, "8859")) {
2390 DEBUG_L(PerlIO_printf(Perl_debug_log,
2391 "Locale %s has 8859 in name, not UTF-8 locale\n",
2392 save_input_locale));
2393 Safefree(save_input_locale);
2398 DEBUG_L(PerlIO_printf(Perl_debug_log,
2399 "Assuming locale %s is not a UTF-8 locale\n",
2400 save_input_locale));
2401 Safefree(save_input_locale);
2409 Perl__is_in_locale_category(pTHX_ const bool compiling, const int category)
2412 /* Internal function which returns if we are in the scope of a pragma that
2413 * enables the locale category 'category'. 'compiling' should indicate if
2414 * this is during the compilation phase (TRUE) or not (FALSE). */
2416 const COP * const cop = (compiling) ? &PL_compiling : PL_curcop;
2418 SV *categories = cop_hints_fetch_pvs(cop, "locale", 0);
2419 if (! categories || categories == &PL_sv_placeholder) {
2423 /* The pseudo-category 'not_characters' is -1, so just add 1 to each to get
2424 * a valid unsigned */
2425 assert(category >= -1);
2426 return cBOOL(SvUV(categories) & (1U << (category + 1)));
2430 Perl_my_strerror(pTHX_ const int errnum) {
2433 /* Uses C locale for the error text unless within scope of 'use locale' for
2436 #ifdef USE_LOCALE_MESSAGES
2437 if (! IN_LC(LC_MESSAGES)) {
2440 /* We have a critical section to prevent another thread from changing
2441 * the locale out from under us (or zapping the buffer returned from
2445 save_locale = setlocale(LC_MESSAGES, NULL);
2446 if (! isNAME_C_OR_POSIX(save_locale)) {
2449 /* The next setlocale likely will zap this, so create a copy */
2450 save_locale = savepv(save_locale);
2452 setlocale(LC_MESSAGES, "C");
2454 /* This points to the static space in Strerror, with all its
2456 errstr = Strerror(errnum);
2458 setlocale(LC_MESSAGES, save_locale);
2459 Safefree(save_locale);
2470 return Strerror(errnum);
2475 =head1 Locale-related functions and macros
2477 =for apidoc sync_locale
2479 Changing the program's locale should be avoided by XS code. Nevertheless,
2480 certain non-Perl libraries called from XS, such as C<Gtk> do so. When this
2481 happens, Perl needs to be told that the locale has changed. Use this function
2482 to do so, before returning to Perl.
2488 Perl_sync_locale(pTHX)
2491 #ifdef USE_LOCALE_CTYPE
2492 new_ctype(setlocale(LC_CTYPE, NULL));
2493 #endif /* USE_LOCALE_CTYPE */
2495 #ifdef USE_LOCALE_COLLATE
2496 new_collate(setlocale(LC_COLLATE, NULL));
2499 #ifdef USE_LOCALE_NUMERIC
2500 set_numeric_local(); /* Switch from "C" to underlying LC_NUMERIC */
2501 new_numeric(setlocale(LC_NUMERIC, NULL));
2502 #endif /* USE_LOCALE_NUMERIC */
2506 #if defined(DEBUGGING) && defined(USE_LOCALE)
2509 Perl__setlocale_debug_string(const int category, /* category number,
2511 const char* const locale, /* locale name */
2513 /* return value from setlocale() when attempting to
2514 * set 'category' to 'locale' */
2515 const char* const retval)
2517 /* Returns a pointer to a NUL-terminated string in static storage with
2518 * added text about the info passed in. This is not thread safe and will
2519 * be overwritten by the next call, so this should be used just to
2520 * formulate a string to immediately print or savepv() on. */
2522 /* initialise to a non-null value to keep it out of BSS and so keep
2523 * -DPERL_GLOBAL_STRUCT_PRIVATE happy */
2524 static char ret[128] = "x";
2526 my_strlcpy(ret, "setlocale(", sizeof(ret));
2530 my_snprintf(ret, sizeof(ret), "%s? %d", ret, category);
2534 my_strlcat(ret, "LC_ALL", sizeof(ret));
2539 my_strlcat(ret, "LC_CTYPE", sizeof(ret));
2544 my_strlcat(ret, "LC_NUMERIC", sizeof(ret));
2549 my_strlcat(ret, "LC_COLLATE", sizeof(ret));
2554 my_strlcat(ret, "LC_TIME", sizeof(ret));
2559 my_strlcat(ret, "LC_MONETARY", sizeof(ret));
2564 my_strlcat(ret, "LC_MESSAGES", sizeof(ret));
2569 my_strlcat(ret, ", ", sizeof(ret));
2572 my_strlcat(ret, "\"", sizeof(ret));
2573 my_strlcat(ret, locale, sizeof(ret));
2574 my_strlcat(ret, "\"", sizeof(ret));
2577 my_strlcat(ret, "NULL", sizeof(ret));
2580 my_strlcat(ret, ") returned ", sizeof(ret));
2583 my_strlcat(ret, "\"", sizeof(ret));
2584 my_strlcat(ret, retval, sizeof(ret));
2585 my_strlcat(ret, "\"", sizeof(ret));
2588 my_strlcat(ret, "NULL", sizeof(ret));
2591 assert(strlen(ret) < sizeof(ret));
2600 * ex: set ts=8 sts=4 sw=4 et: