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 bool first_time = TRUE; /* Cleared after first loop iteration */
1441 PERL_ARGS_ASSERT__MEM_COLLXFRM;
1443 /* Must be NUL-terminated */
1444 assert(*(input_string + len) == '\0');
1446 /* If this locale has defective collation, skip */
1447 if (PL_collxfrm_base == 0 && PL_collxfrm_mult == 0) {
1451 /* Replace any embedded NULs with the control that sorts before any others.
1452 * This will give as good as possible results on strings that don't
1453 * otherwise contain that character, but otherwise there may be
1454 * less-than-perfect results with that character and NUL. This is
1455 * unavoidable unless we replace strxfrm with our own implementation.
1457 * XXX This code may be overkill. khw wrote it before realizing that if
1458 * you change a NUL into some other character, that that may change the
1459 * strxfrm results if that character is part of a sequence with other
1460 * characters for weight calculations. To minimize the chances of this,
1461 * now the replacement is restricted to another control (likely to be
1462 * \001). But the full generality has been retained.
1464 * This is one of the few places in the perl core, where we can use
1465 * standard functions like strlen() and strcat(). It's because we're
1466 * looking for NULs. */
1467 if (s_strlen < len) {
1470 STRLEN cur_min_char_len;
1472 /* If we don't know what control character sorts lowest for this
1473 * locale, find it */
1474 if (*PL_strxfrm_min_char == '\0') {
1477 U8 cur_min_cp = 1; /* The code point that sorts lowest, so far */
1479 char * cur_min_x = NULL; /* And its xfrm, (except it also
1480 includes the collation index
1483 /* Look through all legal code points (NUL isn't) */
1484 for (j = 1; j < 256; j++) {
1485 char * x; /* j's xfrm plus collation index */
1486 STRLEN x_len; /* length of 'x' */
1487 STRLEN trial_len = 1;
1489 /* Create a 1 byte string of the current code point, but with
1490 * room to be 2 bytes */
1491 char cur_source[] = { (char) j, '\0' , '\0' };
1493 if (PL_in_utf8_COLLATE_locale) {
1494 if (! isCNTRL_L1(j)) {
1498 /* If needs to be 2 bytes, find them */
1499 if (! UVCHR_IS_INVARIANT(j)) {
1500 char * d = cur_source;
1501 append_utf8_from_native_byte((U8) j, (U8 **) &d);
1505 else if (! isCNTRL_LC(j)) {
1509 /* Then transform it */
1510 x = _mem_collxfrm(cur_source, trial_len, &x_len,
1511 PL_in_utf8_COLLATE_locale);
1513 /* If something went wrong (which it shouldn't), just
1514 * ignore this code point */
1516 || strlen(x + COLLXFRM_HDR_LEN) < x_len)
1521 /* If this character's transformation is lower than
1522 * the current lowest, this one becomes the lowest */
1523 if ( cur_min_x == NULL
1524 || strLT(x + COLLXFRM_HDR_LEN,
1525 cur_min_x + COLLXFRM_HDR_LEN))
1527 strcpy(PL_strxfrm_min_char, cur_source);
1536 } /* end of loop through all bytes */
1538 /* Unlikely, but possible, if there aren't any controls in the
1539 * locale, arbitrarily use \001 */
1540 if (cur_min_x == NULL) {
1541 STRLEN x_len; /* temporary */
1542 cur_min_x = _mem_collxfrm("\001", 1, &x_len,
1543 PL_in_utf8_COLLATE_locale);
1544 /* cur_min_cp was already initialized to 1 */
1547 DEBUG_L(PerlIO_printf(Perl_debug_log,
1548 "_mem_collxfrm: lowest collating control in the 0-255 "
1549 "range in locale %s is 0x%02X\n",
1552 if (DEBUG_Lv_TEST) {
1554 PerlIO_printf(Perl_debug_log, "Its xfrm is");
1555 for (i = 0; i < strlen(cur_min_x + COLLXFRM_HDR_LEN); i ++) {
1556 PerlIO_printf(Perl_debug_log, " %02x",
1557 (U8) *(cur_min_x + COLLXFRM_HDR_LEN + i));
1559 PerlIO_printf(Perl_debug_log, "\n");
1562 Safefree(cur_min_x);
1565 /* The worst case length for the replaced string would be if every
1566 * character in it is NUL. Multiply that by the length of each
1567 * replacement, and allow for a trailing NUL */
1568 cur_min_char_len = strlen(PL_strxfrm_min_char);
1569 Newx(sans_nuls, (len * cur_min_char_len) + 1, char);
1573 /* Replace each NUL with the lowest collating control. Loop until have
1574 * exhausted all the NULs */
1575 while (s + s_strlen < e) {
1576 strcat(sans_nuls, s);
1578 /* Do the actual replacement */
1579 strcat(sans_nuls, PL_strxfrm_min_char);
1581 /* Move past the input NUL */
1583 s_strlen = strlen(s);
1586 /* And add anything that trails the final NUL */
1587 strcat(sans_nuls, s);
1589 /* Switch so below we transform this modified string */
1594 /* Make sure the UTF8ness of the string and locale match */
1595 if (utf8 != PL_in_utf8_COLLATE_locale) {
1596 const char * const t = s; /* Temporary so we can later find where the
1599 /* Here they don't match. Change the string's to be what the locale is
1602 if (! utf8) { /* locale is UTF-8, but input isn't; upgrade the input */
1603 s = (char *) bytes_to_utf8((const U8 *) s, &len);
1606 else { /* locale is not UTF-8; but input is; downgrade the input */
1608 s = (char *) bytes_from_utf8((const U8 *) s, &len, &utf8);
1610 /* If the downgrade was successful we are done, but if the input
1611 * contains things that require UTF-8 to represent, have to do
1612 * damage control ... */
1613 if (UNLIKELY(utf8)) {
1615 /* What we do is construct a non-UTF-8 string with
1616 * 1) the characters representable by a single byte converted
1617 * to be so (if necessary);
1618 * 2) and the rest converted to collate the same as the
1619 * highest collating representable character. That makes
1620 * them collate at the end. This is similar to how we
1621 * handle embedded NULs, but we use the highest collating
1622 * code point instead of the smallest. Like the NUL case,
1623 * this isn't perfect, but is the best we can reasonably
1624 * do. Every above-255 code point will sort the same as
1625 * the highest-sorting 0-255 code point. If that code
1626 * point can combine in a sequence with some other code
1627 * points for weight calculations, us changing something to
1628 * be it can adversely affect the results. But in most
1629 * cases, it should work reasonably. And note that this is
1630 * really an illegal situation: using code points above 255
1631 * on a locale where only 0-255 are valid. If two strings
1632 * sort entirely equal, then the sort order for the
1633 * above-255 code points will be in code point order. */
1637 /* If we haven't calculated the code point with the maximum
1638 * collating order for this locale, do so now */
1639 if (! PL_strxfrm_max_cp) {
1642 /* The current transformed string that collates the
1643 * highest (except it also includes the prefixed collation
1645 char * cur_max_x = NULL;
1647 /* Look through all legal code points (NUL isn't) */
1648 for (j = 1; j < 256; j++) {
1652 /* Create a 1-char string of the current code point. */
1653 char cur_source[] = { (char) j, '\0' };
1655 /* Then transform it */
1656 x = _mem_collxfrm(cur_source, 1, &x_len, FALSE);
1658 /* If something went wrong (which it shouldn't), just
1659 * ignore this code point */
1665 /* If this character's transformation is higher than
1666 * the current highest, this one becomes the highest */
1667 if ( cur_max_x == NULL
1668 || strGT(x + COLLXFRM_HDR_LEN,
1669 cur_max_x + COLLXFRM_HDR_LEN))
1671 PL_strxfrm_max_cp = j;
1679 DEBUG_L(PerlIO_printf(Perl_debug_log,
1680 "_mem_collxfrm: highest 1-byte collating character"
1681 " in locale %s is 0x%02X\n",
1683 PL_strxfrm_max_cp));
1684 if (DEBUG_Lv_TEST) {
1686 PerlIO_printf(Perl_debug_log, "Its xfrm is ");
1688 i < strlen(cur_max_x + COLLXFRM_HDR_LEN);
1691 PerlIO_printf(Perl_debug_log, " %02x",
1692 (U8) cur_max_x[i + COLLXFRM_HDR_LEN]);
1694 PerlIO_printf(Perl_debug_log, "\n");
1697 Safefree(cur_max_x);
1700 /* Here we know which legal code point collates the highest.
1701 * We are ready to construct the non-UTF-8 string. The length
1702 * will be at least 1 byte smaller than the input string
1703 * (because we changed at least one 2-byte character into a
1704 * single byte), but that is eaten up by the trailing NUL */
1711 for (i = 0; i < len; i+= UTF8SKIP(t + i)) {
1713 if (UTF8_IS_INVARIANT(cur_char)) {
1716 else if (UTF8_IS_DOWNGRADEABLE_START(cur_char)) {
1717 s[d++] = EIGHT_BIT_UTF8_TO_NATIVE(cur_char, t[i+1]);
1719 else { /* Replace illegal cp with highest collating
1721 s[d++] = PL_strxfrm_max_cp;
1725 Renew(s, d, char); /* Free up unused space */
1730 /* Here, we have constructed a modified version of the input. It could
1731 * be that we already had a modified copy before we did this version.
1732 * If so, that copy is no longer needed */
1733 if (t != input_string) {
1738 /* The first element in the output is the collation id, used by
1739 * sv_collxfrm(); then comes the space for the transformed string. The
1740 * equation should give us a good estimate as to how much is needed */
1741 xAlloc = COLLXFRM_HDR_LEN
1743 + (PL_collxfrm_mult * ((utf8)
1744 ? utf8_length((U8 *) s, (U8 *) s + len)
1746 Newx(xbuf, xAlloc, char);
1747 if (UNLIKELY(! xbuf))
1750 /* Store the collation id */
1751 *(U32*)xbuf = PL_collation_ix;
1753 /* Then the transformation of the input. We loop until successful, or we
1756 *xlen = strxfrm(xbuf + COLLXFRM_HDR_LEN, s, xAlloc - COLLXFRM_HDR_LEN);
1758 /* If the transformed string occupies less space than we told strxfrm()
1759 * was available, it means it successfully transformed the whole
1761 if (*xlen < xAlloc - COLLXFRM_HDR_LEN) {
1765 if (UNLIKELY(*xlen >= PERL_INT_MAX))
1768 /* A well-behaved strxfrm() returns exactly how much space it needs
1769 * (not including the trailing NUL) when it fails due to not enough
1770 * space being provided. Assume that this is the case unless it's been
1771 * proven otherwise */
1772 if (LIKELY(PL_strxfrm_is_behaved) && first_time) {
1773 xAlloc = *xlen + COLLXFRM_HDR_LEN + 1;
1775 else { /* Here, either:
1776 * 1) The strxfrm() has previously shown bad behavior; or
1777 * 2) It isn't the first time through the loop, which means
1778 * that the strxfrm() is now showing bad behavior, because
1779 * we gave it what it said was needed in the previous
1780 * iteration, and it came back saying it needed still more.
1781 * (Many versions of cygwin fit this. When the buffer size
1782 * isn't sufficient, they return the input size instead of
1783 * how much is needed.)
1784 * Increase the buffer size by a fixed percentage and try again. */
1785 xAlloc = (2 * xAlloc) + 1;
1786 PL_strxfrm_is_behaved = FALSE;
1789 if (DEBUG_Lv_TEST || debug_initialization) {
1790 PerlIO_printf(Perl_debug_log,
1791 "_mem_collxfrm required more space than previously calculated"
1792 " for locale %s, trying again with new guess=%d+%"UVuf"\n",
1793 PL_collation_name, (int) COLLXFRM_HDR_LEN,
1794 (UV) xAlloc - COLLXFRM_HDR_LEN);
1799 Renew(xbuf, xAlloc, char);
1800 if (UNLIKELY(! xbuf))
1808 if (DEBUG_Lv_TEST || debug_initialization) {
1810 PerlIO_printf(Perl_debug_log,
1811 "_mem_collxfrm[%d]: returning %"UVuf" for locale %s '%s'\n",
1812 PL_collation_ix, *xlen, PL_collation_name, input_string);
1813 PerlIO_printf(Perl_debug_log, "Its xfrm is");
1814 for (i = COLLXFRM_HDR_LEN; i < *xlen + COLLXFRM_HDR_LEN; i++) {
1815 PerlIO_printf(Perl_debug_log, " %02x", (U8) xbuf[i]);
1817 PerlIO_printf(Perl_debug_log, "\n");
1821 /* Free up unneeded space; retain ehough for trailing NUL */
1822 Renew(xbuf, COLLXFRM_HDR_LEN + *xlen + 1, char);
1824 if (s != input_string) {
1832 if (s != input_string) {
1837 if (DEBUG_Lv_TEST || debug_initialization) {
1838 PerlIO_printf(Perl_debug_log, "_mem_collxfrm[%d] returning NULL\n",
1845 #endif /* USE_LOCALE_COLLATE */
1850 Perl__is_cur_LC_category_utf8(pTHX_ int category)
1852 /* Returns TRUE if the current locale for 'category' is UTF-8; FALSE
1853 * otherwise. 'category' may not be LC_ALL. If the platform doesn't have
1854 * nl_langinfo(), nor MB_CUR_MAX, this employs a heuristic, which hence
1855 * could give the wrong result. The result will very likely be correct for
1856 * languages that have commonly used non-ASCII characters, but for notably
1857 * English, it comes down to if the locale's name ends in something like
1858 * "UTF-8". It errs on the side of not being a UTF-8 locale. */
1860 char *save_input_locale = NULL;
1864 assert(category != LC_ALL);
1867 /* First dispose of the trivial cases */
1868 save_input_locale = setlocale(category, NULL);
1869 if (! save_input_locale) {
1870 DEBUG_L(PerlIO_printf(Perl_debug_log,
1871 "Could not find current locale for category %d\n",
1873 return FALSE; /* XXX maybe should croak */
1875 save_input_locale = stdize_locale(savepv(save_input_locale));
1876 if (isNAME_C_OR_POSIX(save_input_locale)) {
1877 DEBUG_L(PerlIO_printf(Perl_debug_log,
1878 "Current locale for category %d is %s\n",
1879 category, save_input_locale));
1880 Safefree(save_input_locale);
1884 #if defined(USE_LOCALE_CTYPE) \
1885 && (defined(MB_CUR_MAX) || (defined(HAS_NL_LANGINFO) && defined(CODESET)))
1887 { /* Next try nl_langinfo or MB_CUR_MAX if available */
1889 char *save_ctype_locale = NULL;
1892 if (category != LC_CTYPE) { /* These work only on LC_CTYPE */
1894 /* Get the current LC_CTYPE locale */
1895 save_ctype_locale = setlocale(LC_CTYPE, NULL);
1896 if (! save_ctype_locale) {
1897 DEBUG_L(PerlIO_printf(Perl_debug_log,
1898 "Could not find current locale for LC_CTYPE\n"));
1899 goto cant_use_nllanginfo;
1901 save_ctype_locale = stdize_locale(savepv(save_ctype_locale));
1903 /* If LC_CTYPE and the desired category use the same locale, this
1904 * means that finding the value for LC_CTYPE is the same as finding
1905 * the value for the desired category. Otherwise, switch LC_CTYPE
1906 * to the desired category's locale */
1907 if (strEQ(save_ctype_locale, save_input_locale)) {
1908 Safefree(save_ctype_locale);
1909 save_ctype_locale = NULL;
1911 else if (! setlocale(LC_CTYPE, save_input_locale)) {
1912 DEBUG_L(PerlIO_printf(Perl_debug_log,
1913 "Could not change LC_CTYPE locale to %s\n",
1914 save_input_locale));
1915 Safefree(save_ctype_locale);
1916 goto cant_use_nllanginfo;
1920 DEBUG_L(PerlIO_printf(Perl_debug_log, "Current LC_CTYPE locale=%s\n",
1921 save_input_locale));
1923 /* Here the current LC_CTYPE is set to the locale of the category whose
1924 * information is desired. This means that nl_langinfo() and MB_CUR_MAX
1925 * should give the correct results */
1927 # if defined(HAS_NL_LANGINFO) && defined(CODESET)
1929 char *codeset = nl_langinfo(CODESET);
1930 if (codeset && strNE(codeset, "")) {
1931 codeset = savepv(codeset);
1933 /* If we switched LC_CTYPE, switch back */
1934 if (save_ctype_locale) {
1935 setlocale(LC_CTYPE, save_ctype_locale);
1936 Safefree(save_ctype_locale);
1939 is_utf8 = foldEQ(codeset, STR_WITH_LEN("UTF-8"))
1940 || foldEQ(codeset, STR_WITH_LEN("UTF8"));
1942 DEBUG_L(PerlIO_printf(Perl_debug_log,
1943 "\tnllanginfo returned CODESET '%s'; ?UTF8 locale=%d\n",
1946 Safefree(save_input_locale);
1954 /* Here, either we don't have nl_langinfo, or it didn't return a
1955 * codeset. Try MB_CUR_MAX */
1957 /* Standard UTF-8 needs at least 4 bytes to represent the maximum
1958 * Unicode code point. Since UTF-8 is the only non-single byte
1959 * encoding we handle, we just say any such encoding is UTF-8, and if
1960 * turns out to be wrong, other things will fail */
1961 is_utf8 = MB_CUR_MAX >= 4;
1963 DEBUG_L(PerlIO_printf(Perl_debug_log,
1964 "\tMB_CUR_MAX=%d; ?UTF8 locale=%d\n",
1965 (int) MB_CUR_MAX, is_utf8));
1967 Safefree(save_input_locale);
1971 /* ... But, most system that have MB_CUR_MAX will also have mbtowc(),
1972 * since they are both in the C99 standard. We can feed a known byte
1973 * string to the latter function, and check that it gives the expected
1977 PERL_UNUSED_RESULT(mbtowc(&wc, NULL, 0));/* Reset any shift state */
1979 if ((size_t)mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8))
1980 != strlen(HYPHEN_UTF8)
1981 || wc != (wchar_t) 0x2010)
1984 DEBUG_L(PerlIO_printf(Perl_debug_log, "\thyphen=U+%x\n", (unsigned int)wc));
1985 DEBUG_L(PerlIO_printf(Perl_debug_log,
1986 "\treturn from mbtowc=%d; errno=%d; ?UTF8 locale=0\n",
1987 mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8)), errno));
1992 /* If we switched LC_CTYPE, switch back */
1993 if (save_ctype_locale) {
1994 setlocale(LC_CTYPE, save_ctype_locale);
1995 Safefree(save_ctype_locale);
2002 cant_use_nllanginfo:
2004 #else /* nl_langinfo should work if available, so don't bother compiling this
2005 fallback code. The final fallback of looking at the name is
2006 compiled, and will be executed if nl_langinfo fails */
2008 /* nl_langinfo not available or failed somehow. Next try looking at the
2009 * currency symbol to see if it disambiguates things. Often that will be
2010 * in the native script, and if the symbol isn't in UTF-8, we know that the
2011 * locale isn't. If it is non-ASCII UTF-8, we infer that the locale is
2012 * too, as the odds of a non-UTF8 string being valid UTF-8 are quite small
2015 #ifdef HAS_LOCALECONV
2016 # ifdef USE_LOCALE_MONETARY
2018 char *save_monetary_locale = NULL;
2019 bool only_ascii = FALSE;
2020 bool is_utf8 = FALSE;
2023 /* Like above for LC_CTYPE, we first set LC_MONETARY to the locale of
2024 * the desired category, if it isn't that locale already */
2026 if (category != LC_MONETARY) {
2028 save_monetary_locale = setlocale(LC_MONETARY, NULL);
2029 if (! save_monetary_locale) {
2030 DEBUG_L(PerlIO_printf(Perl_debug_log,
2031 "Could not find current locale for LC_MONETARY\n"));
2032 goto cant_use_monetary;
2034 save_monetary_locale = stdize_locale(savepv(save_monetary_locale));
2036 if (strEQ(save_monetary_locale, save_input_locale)) {
2037 Safefree(save_monetary_locale);
2038 save_monetary_locale = NULL;
2040 else if (! setlocale(LC_MONETARY, save_input_locale)) {
2041 DEBUG_L(PerlIO_printf(Perl_debug_log,
2042 "Could not change LC_MONETARY locale to %s\n",
2043 save_input_locale));
2044 Safefree(save_monetary_locale);
2045 goto cant_use_monetary;
2049 /* Here the current LC_MONETARY is set to the locale of the category
2050 * whose information is desired. */
2054 || ! lc->currency_symbol
2055 || is_invariant_string((U8 *) lc->currency_symbol, 0))
2057 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));
2061 is_utf8 = is_utf8_string((U8 *) lc->currency_symbol, 0);
2064 /* If we changed it, restore LC_MONETARY to its original locale */
2065 if (save_monetary_locale) {
2066 setlocale(LC_MONETARY, save_monetary_locale);
2067 Safefree(save_monetary_locale);
2072 /* It isn't a UTF-8 locale if the symbol is not legal UTF-8;
2073 * otherwise assume the locale is UTF-8 if and only if the symbol
2074 * is non-ascii UTF-8. */
2075 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?Currency symbol for %s is UTF-8=%d\n",
2076 save_input_locale, is_utf8));
2077 Safefree(save_input_locale);
2083 # endif /* USE_LOCALE_MONETARY */
2084 #endif /* HAS_LOCALECONV */
2086 #if defined(HAS_STRFTIME) && defined(USE_LOCALE_TIME)
2088 /* Still haven't found a non-ASCII string to disambiguate UTF-8 or not. Try
2089 * the names of the months and weekdays, timezone, and am/pm indicator */
2091 char *save_time_locale = NULL;
2093 bool is_dst = FALSE;
2097 char * formatted_time;
2100 /* Like above for LC_MONETARY, we set LC_TIME to the locale of the
2101 * desired category, if it isn't that locale already */
2103 if (category != LC_TIME) {
2105 save_time_locale = setlocale(LC_TIME, NULL);
2106 if (! save_time_locale) {
2107 DEBUG_L(PerlIO_printf(Perl_debug_log,
2108 "Could not find current locale for LC_TIME\n"));
2111 save_time_locale = stdize_locale(savepv(save_time_locale));
2113 if (strEQ(save_time_locale, save_input_locale)) {
2114 Safefree(save_time_locale);
2115 save_time_locale = NULL;
2117 else if (! setlocale(LC_TIME, save_input_locale)) {
2118 DEBUG_L(PerlIO_printf(Perl_debug_log,
2119 "Could not change LC_TIME locale to %s\n",
2120 save_input_locale));
2121 Safefree(save_time_locale);
2126 /* Here the current LC_TIME is set to the locale of the category
2127 * whose information is desired. Look at all the days of the week and
2128 * month names, and the timezone and am/pm indicator for UTF-8 variant
2129 * characters. The first such a one found will tell us if the locale
2130 * is UTF-8 or not */
2132 for (i = 0; i < 7 + 12; i++) { /* 7 days; 12 months */
2133 formatted_time = my_strftime("%A %B %Z %p",
2134 0, 0, hour, dom, month, 112, 0, 0, is_dst);
2135 if (! formatted_time || is_invariant_string((U8 *) formatted_time, 0)) {
2137 /* Here, we didn't find a non-ASCII. Try the next time through
2138 * with the complemented dst and am/pm, and try with the next
2139 * weekday. After we have gotten all weekdays, try the next
2142 hour = (hour + 12) % 24;
2150 /* Here, we have a non-ASCII. Return TRUE is it is valid UTF8;
2151 * false otherwise. But first, restore LC_TIME to its original
2152 * locale if we changed it */
2153 if (save_time_locale) {
2154 setlocale(LC_TIME, save_time_locale);
2155 Safefree(save_time_locale);
2158 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?time-related strings for %s are UTF-8=%d\n",
2160 is_utf8_string((U8 *) formatted_time, 0)));
2161 Safefree(save_input_locale);
2162 return is_utf8_string((U8 *) formatted_time, 0);
2165 /* Falling off the end of the loop indicates all the names were just
2166 * ASCII. Go on to the next test. If we changed it, restore LC_TIME
2167 * to its original locale */
2168 if (save_time_locale) {
2169 setlocale(LC_TIME, save_time_locale);
2170 Safefree(save_time_locale);
2172 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));
2178 #if 0 && defined(USE_LOCALE_MESSAGES) && defined(HAS_SYS_ERRLIST)
2180 /* This code is ifdefd out because it was found to not be necessary in testing
2181 * on our dromedary test machine, which has over 700 locales. There, this
2182 * added no value to looking at the currency symbol and the time strings. I
2183 * left it in so as to avoid rewriting it if real-world experience indicates
2184 * that dromedary is an outlier. Essentially, instead of returning abpve if we
2185 * haven't found illegal utf8, we continue on and examine all the strerror()
2186 * messages on the platform for utf8ness. If all are ASCII, we still don't
2187 * know the answer; but otherwise we have a pretty good indication of the
2188 * utf8ness. The reason this doesn't help much is that the messages may not
2189 * have been translated into the locale. The currency symbol and time strings
2190 * are much more likely to have been translated. */
2193 bool is_utf8 = FALSE;
2194 bool non_ascii = FALSE;
2195 char *save_messages_locale = NULL;
2196 const char * errmsg = NULL;
2198 /* Like above, we set LC_MESSAGES to the locale of the desired
2199 * category, if it isn't that locale already */
2201 if (category != LC_MESSAGES) {
2203 save_messages_locale = setlocale(LC_MESSAGES, NULL);
2204 if (! save_messages_locale) {
2205 DEBUG_L(PerlIO_printf(Perl_debug_log,
2206 "Could not find current locale for LC_MESSAGES\n"));
2207 goto cant_use_messages;
2209 save_messages_locale = stdize_locale(savepv(save_messages_locale));
2211 if (strEQ(save_messages_locale, save_input_locale)) {
2212 Safefree(save_messages_locale);
2213 save_messages_locale = NULL;
2215 else if (! setlocale(LC_MESSAGES, save_input_locale)) {
2216 DEBUG_L(PerlIO_printf(Perl_debug_log,
2217 "Could not change LC_MESSAGES locale to %s\n",
2218 save_input_locale));
2219 Safefree(save_messages_locale);
2220 goto cant_use_messages;
2224 /* Here the current LC_MESSAGES is set to the locale of the category
2225 * whose information is desired. Look through all the messages. We
2226 * can't use Strerror() here because it may expand to code that
2227 * segfaults in miniperl */
2229 for (e = 0; e <= sys_nerr; e++) {
2231 errmsg = sys_errlist[e];
2232 if (errno || !errmsg) {
2235 errmsg = savepv(errmsg);
2236 if (! is_invariant_string((U8 *) errmsg, 0)) {
2238 is_utf8 = is_utf8_string((U8 *) errmsg, 0);
2244 /* And, if we changed it, restore LC_MESSAGES to its original locale */
2245 if (save_messages_locale) {
2246 setlocale(LC_MESSAGES, save_messages_locale);
2247 Safefree(save_messages_locale);
2252 /* Any non-UTF-8 message means not a UTF-8 locale; if all are valid,
2253 * any non-ascii means it is one; otherwise we assume it isn't */
2254 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?error messages for %s are UTF-8=%d\n",
2257 Safefree(save_input_locale);
2261 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));
2267 #endif /* the code that is compiled when no nl_langinfo */
2269 #ifndef EBCDIC /* On os390, even if the name ends with "UTF-8', it isn't a
2271 /* As a last resort, look at the locale name to see if it matches
2272 * qr/UTF -? * 8 /ix, or some other common locale names. This "name", the
2273 * return of setlocale(), is actually defined to be opaque, so we can't
2274 * really rely on the absence of various substrings in the name to indicate
2275 * its UTF-8ness, but if it has UTF8 in the name, it is extremely likely to
2276 * be a UTF-8 locale. Similarly for the other common names */
2278 final_pos = strlen(save_input_locale) - 1;
2279 if (final_pos >= 3) {
2280 char *name = save_input_locale;
2282 /* Find next 'U' or 'u' and look from there */
2283 while ((name += strcspn(name, "Uu") + 1)
2284 <= save_input_locale + final_pos - 2)
2286 if (!isALPHA_FOLD_NE(*name, 't')
2287 || isALPHA_FOLD_NE(*(name + 1), 'f'))
2292 if (*(name) == '-') {
2293 if ((name > save_input_locale + final_pos - 1)) {
2298 if (*(name) == '8') {
2299 DEBUG_L(PerlIO_printf(Perl_debug_log,
2300 "Locale %s ends with UTF-8 in name\n",
2301 save_input_locale));
2302 Safefree(save_input_locale);
2306 DEBUG_L(PerlIO_printf(Perl_debug_log,
2307 "Locale %s doesn't end with UTF-8 in name\n",
2308 save_input_locale));
2313 /* http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756.aspx */
2315 && *(save_input_locale + final_pos - 0) == '1'
2316 && *(save_input_locale + final_pos - 1) == '0'
2317 && *(save_input_locale + final_pos - 2) == '0'
2318 && *(save_input_locale + final_pos - 3) == '5'
2319 && *(save_input_locale + final_pos - 4) == '6')
2321 DEBUG_L(PerlIO_printf(Perl_debug_log,
2322 "Locale %s ends with 10056 in name, is UTF-8 locale\n",
2323 save_input_locale));
2324 Safefree(save_input_locale);
2329 /* Other common encodings are the ISO 8859 series, which aren't UTF-8. But
2330 * since we are about to return FALSE anyway, there is no point in doing
2331 * this extra work */
2333 if (instr(save_input_locale, "8859")) {
2334 DEBUG_L(PerlIO_printf(Perl_debug_log,
2335 "Locale %s has 8859 in name, not UTF-8 locale\n",
2336 save_input_locale));
2337 Safefree(save_input_locale);
2342 DEBUG_L(PerlIO_printf(Perl_debug_log,
2343 "Assuming locale %s is not a UTF-8 locale\n",
2344 save_input_locale));
2345 Safefree(save_input_locale);
2353 Perl__is_in_locale_category(pTHX_ const bool compiling, const int category)
2356 /* Internal function which returns if we are in the scope of a pragma that
2357 * enables the locale category 'category'. 'compiling' should indicate if
2358 * this is during the compilation phase (TRUE) or not (FALSE). */
2360 const COP * const cop = (compiling) ? &PL_compiling : PL_curcop;
2362 SV *categories = cop_hints_fetch_pvs(cop, "locale", 0);
2363 if (! categories || categories == &PL_sv_placeholder) {
2367 /* The pseudo-category 'not_characters' is -1, so just add 1 to each to get
2368 * a valid unsigned */
2369 assert(category >= -1);
2370 return cBOOL(SvUV(categories) & (1U << (category + 1)));
2374 Perl_my_strerror(pTHX_ const int errnum) {
2377 /* Uses C locale for the error text unless within scope of 'use locale' for
2380 #ifdef USE_LOCALE_MESSAGES
2381 if (! IN_LC(LC_MESSAGES)) {
2384 /* We have a critical section to prevent another thread from changing
2385 * the locale out from under us (or zapping the buffer returned from
2389 save_locale = setlocale(LC_MESSAGES, NULL);
2390 if (! isNAME_C_OR_POSIX(save_locale)) {
2393 /* The next setlocale likely will zap this, so create a copy */
2394 save_locale = savepv(save_locale);
2396 setlocale(LC_MESSAGES, "C");
2398 /* This points to the static space in Strerror, with all its
2400 errstr = Strerror(errnum);
2402 setlocale(LC_MESSAGES, save_locale);
2403 Safefree(save_locale);
2414 return Strerror(errnum);
2419 =head1 Locale-related functions and macros
2421 =for apidoc sync_locale
2423 Changing the program's locale should be avoided by XS code. Nevertheless,
2424 certain non-Perl libraries called from XS, such as C<Gtk> do so. When this
2425 happens, Perl needs to be told that the locale has changed. Use this function
2426 to do so, before returning to Perl.
2432 Perl_sync_locale(pTHX)
2435 #ifdef USE_LOCALE_CTYPE
2436 new_ctype(setlocale(LC_CTYPE, NULL));
2437 #endif /* USE_LOCALE_CTYPE */
2439 #ifdef USE_LOCALE_COLLATE
2440 new_collate(setlocale(LC_COLLATE, NULL));
2443 #ifdef USE_LOCALE_NUMERIC
2444 set_numeric_local(); /* Switch from "C" to underlying LC_NUMERIC */
2445 new_numeric(setlocale(LC_NUMERIC, NULL));
2446 #endif /* USE_LOCALE_NUMERIC */
2450 #if defined(DEBUGGING) && defined(USE_LOCALE)
2453 Perl__setlocale_debug_string(const int category, /* category number,
2455 const char* const locale, /* locale name */
2457 /* return value from setlocale() when attempting to
2458 * set 'category' to 'locale' */
2459 const char* const retval)
2461 /* Returns a pointer to a NUL-terminated string in static storage with
2462 * added text about the info passed in. This is not thread safe and will
2463 * be overwritten by the next call, so this should be used just to
2464 * formulate a string to immediately print or savepv() on. */
2466 /* initialise to a non-null value to keep it out of BSS and so keep
2467 * -DPERL_GLOBAL_STRUCT_PRIVATE happy */
2468 static char ret[128] = "x";
2470 my_strlcpy(ret, "setlocale(", sizeof(ret));
2474 my_snprintf(ret, sizeof(ret), "%s? %d", ret, category);
2478 my_strlcat(ret, "LC_ALL", sizeof(ret));
2483 my_strlcat(ret, "LC_CTYPE", sizeof(ret));
2488 my_strlcat(ret, "LC_NUMERIC", sizeof(ret));
2493 my_strlcat(ret, "LC_COLLATE", sizeof(ret));
2498 my_strlcat(ret, "LC_TIME", sizeof(ret));
2503 my_strlcat(ret, "LC_MONETARY", sizeof(ret));
2508 my_strlcat(ret, "LC_MESSAGES", sizeof(ret));
2513 my_strlcat(ret, ", ", sizeof(ret));
2516 my_strlcat(ret, "\"", sizeof(ret));
2517 my_strlcat(ret, locale, sizeof(ret));
2518 my_strlcat(ret, "\"", sizeof(ret));
2521 my_strlcat(ret, "NULL", sizeof(ret));
2524 my_strlcat(ret, ") returned ", sizeof(ret));
2527 my_strlcat(ret, "\"", sizeof(ret));
2528 my_strlcat(ret, retval, sizeof(ret));
2529 my_strlcat(ret, "\"", sizeof(ret));
2532 my_strlcat(ret, "NULL", sizeof(ret));
2535 assert(strlen(ret) < sizeof(ret));
2544 * ex: set ts=8 sts=4 sw=4 et: