This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Revert "perl.h: Use STMT_START { ... } STMT_END"
[perl5.git] / locale.c
CommitLineData
98994639
HS
1/* locale.c
2 *
1129b882
NC
3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
4 * 2002, 2003, 2005, 2006, 2007, 2008 by Larry Wall and others
98994639
HS
5 *
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.
8 *
9 */
10
11/*
4ac71550 12 * A Elbereth Gilthoniel,
cdad3b53 13 * silivren penna míriel
4ac71550 14 * o menel aglar elenath!
cdad3b53 15 * Na-chaered palan-díriel
4ac71550
TC
16 * o galadhremmin ennorath,
17 * Fanuilos, le linnathon
18 * nef aear, si nef aearon!
19 *
20 * [p.238 of _The Lord of the Rings_, II/i: "Many Meetings"]
98994639
HS
21 */
22
166f8a29
DM
23/* utility functions for handling locale-specific stuff like what
24 * character represents the decimal point.
0d071d52 25 *
7d4bcc4a
KW
26 * All C programs have an underlying locale. Perl code generally doesn't pay
27 * any attention to it except within the scope of a 'use locale'. For most
0d071d52
KW
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
a9ad02a8
KW
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
34 * of 'use locale'.
166f8a29
DM
35 */
36
98994639
HS
37#include "EXTERN.h"
38#define PERL_IN_LOCALE_C
f7416781 39#include "perl_langinfo.h"
98994639
HS
40#include "perl.h"
41
a4af207c
JH
42#include "reentr.h"
43
2fcc0ca9
KW
44/* If the environment says to, we can output debugging information during
45 * initialization. This is done before option parsing, and before any thread
46 * creation, so can be a file-level static */
47#ifdef DEBUGGING
7d4bcc4a 48# ifdef PERL_GLOBAL_STRUCT
27cdc72e 49 /* no global syms allowed */
7d4bcc4a
KW
50# define debug_initialization 0
51# define DEBUG_INITIALIZATION_set(v)
52# else
2fcc0ca9 53static bool debug_initialization = FALSE;
7d4bcc4a
KW
54# define DEBUG_INITIALIZATION_set(v) (debug_initialization = v)
55# endif
2fcc0ca9
KW
56#endif
57
ff1b739b
KW
58/* strlen() of a literal string constant. XXX We might want this more general,
59 * but using it in just this file for now */
60#define STRLENs(s) (sizeof("" s "") - 1)
61
8ef6e574
KW
62#ifdef USE_LOCALE
63
98994639 64/*
0d071d52
KW
65 * Standardize the locale name from a string returned by 'setlocale', possibly
66 * modifying that string.
98994639 67 *
0ef2a2b2 68 * The typical return value of setlocale() is either
98994639
HS
69 * (1) "xx_YY" if the first argument of setlocale() is not LC_ALL
70 * (2) "xa_YY xb_YY ..." if the first argument of setlocale() is LC_ALL
71 * (the space-separated values represent the various sublocales,
0ef2a2b2 72 * in some unspecified order). This is not handled by this function.
98994639
HS
73 *
74 * In some platforms it has a form like "LC_SOMETHING=Lang_Country.866\n",
0ef2a2b2
KW
75 * which is harmful for further use of the string in setlocale(). This
76 * function removes the trailing new line and everything up through the '='
98994639
HS
77 *
78 */
79STATIC char *
80S_stdize_locale(pTHX_ char *locs)
81{
7452cf6a 82 const char * const s = strchr(locs, '=');
98994639
HS
83 bool okay = TRUE;
84
7918f24d
NC
85 PERL_ARGS_ASSERT_STDIZE_LOCALE;
86
8772537c
AL
87 if (s) {
88 const char * const t = strchr(s, '.');
98994639 89 okay = FALSE;
8772537c
AL
90 if (t) {
91 const char * const u = strchr(t, '\n');
92 if (u && (u[1] == 0)) {
93 const STRLEN len = u - s;
94 Move(s + 1, locs, len, char);
95 locs[len] = 0;
96 okay = TRUE;
98994639
HS
97 }
98 }
99 }
100
101 if (!okay)
102 Perl_croak(aTHX_ "Can't fix broken locale name \"%s\"", locs);
103
104 return locs;
105}
106
8ef6e574
KW
107#endif
108
d2b24094
KW
109/* Windows requres a customized base-level setlocale() */
110# ifdef WIN32
111# define my_setlocale(cat, locale) win32_setlocale(cat, locale)
112# else
113# define my_setlocale(cat, locale) setlocale(cat, locale)
114# endif
115
837ce802
KW
116/* Just placeholders for now. "_c" is intended to be called when the category
117 * is a constant known at compile time; "_r", not known until run time */
d2b24094
KW
118# define do_setlocale_c(category, locale) my_setlocale(category, locale)
119# define do_setlocale_r(category, locale) my_setlocale(category, locale)
837ce802 120
a4f00dcc 121STATIC void
86799d2d 122S_set_numeric_radix(pTHX_ const bool use_locale)
98994639 123{
86799d2d
KW
124 /* If 'use_locale' is FALSE, set to use a dot for the radix character. If
125 * TRUE, use the radix character derived from the current locale */
7d4bcc4a 126
86799d2d
KW
127#if defined(USE_LOCALE_NUMERIC) && ( defined(HAS_LOCALECONV) \
128 || defined(HAS_NL_LANGINFO))
98994639 129
86799d2d
KW
130 /* We only set up the radix SV if we are to use a locale radix ... */
131 if (use_locale) {
132 const char * radix = my_nl_langinfo(PERL_RADIXCHAR, FALSE);
133 /* FALSE => already in dest locale */
134
135 /* ... and the character being used isn't a dot */
136 if (strNE(radix, ".")) {
137 if (PL_numeric_radix_sv) {
138 sv_setpv(PL_numeric_radix_sv, radix);
139 }
140 else {
141 PL_numeric_radix_sv = newSVpv(radix, 0);
142 }
143
144 if ( ! is_utf8_invariant_string(
145 (U8 *) SvPVX(PL_numeric_radix_sv), SvCUR(PL_numeric_radix_sv))
146 && is_utf8_string(
147 (U8 *) SvPVX(PL_numeric_radix_sv), SvCUR(PL_numeric_radix_sv))
c1284011 148 && _is_cur_LC_category_utf8(LC_NUMERIC))
28acfe03 149 {
86799d2d 150 SvUTF8_on(PL_numeric_radix_sv);
28acfe03 151 }
86799d2d
KW
152 goto done;
153 }
98994639 154 }
69014004 155
86799d2d
KW
156 SvREFCNT_dec(PL_numeric_radix_sv);
157 PL_numeric_radix_sv = NULL;
158
159 done: ;
160
161# ifdef DEBUGGING
7d4bcc4a 162
2fcc0ca9
KW
163 if (DEBUG_L_TEST || debug_initialization) {
164 PerlIO_printf(Perl_debug_log, "Locale radix is '%s', ?UTF-8=%d\n",
69014004 165 (PL_numeric_radix_sv)
37b7e435
KW
166 ? SvPVX(PL_numeric_radix_sv)
167 : "NULL",
168 (PL_numeric_radix_sv)
39eb7305 169 ? cBOOL(SvUTF8(PL_numeric_radix_sv))
2fcc0ca9
KW
170 : 0);
171 }
69014004 172
86799d2d
KW
173# endif
174#endif /* USE_LOCALE_NUMERIC and can find the radix char */
7d4bcc4a 175
98994639
HS
176}
177
a39edc4c
KW
178/* Is the C string input 'name' "C" or "POSIX"? If so, and 'name' is the
179 * return of setlocale(), then this is extremely likely to be the C or POSIX
180 * locale. However, the output of setlocale() is documented to be opaque, but
181 * the odds are extremely small that it would return these two strings for some
182 * other locale. Note that VMS in these two locales includes many non-ASCII
183 * characters as controls and punctuation (below are hex bytes):
e70d440c
KW
184 * cntrl: 84-97 9B-9F
185 * punct: A1-A3 A5 A7-AB B0-B3 B5-B7 B9-BD BF-CF D1-DD DF-EF F1-FD
a39edc4c
KW
186 * Oddly, none there are listed as alphas, though some represent alphabetics
187 * http://www.nntp.perl.org/group/perl.perl5.porters/2013/02/msg198753.html */
7d4bcc4a
KW
188#define isNAME_C_OR_POSIX(name) \
189 ( (name) != NULL \
190 && (( *(name) == 'C' && (*(name + 1)) == '\0') \
191 || strEQ((name), "POSIX")))
a39edc4c 192
98994639 193void
8772537c 194Perl_new_numeric(pTHX_ const char *newnum)
98994639 195{
7d4bcc4a
KW
196
197#ifndef USE_LOCALE_NUMERIC
198
199 PERL_UNUSED_ARG(newnum);
200
201#else
0d071d52
KW
202
203 /* Called after all libc setlocale() calls affecting LC_NUMERIC, to tell
204 * core Perl this and that 'newnum' is the name of the new locale.
205 * It installs this locale as the current underlying default.
206 *
207 * The default locale and the C locale can be toggled between by use of the
5792c642
KW
208 * set_numeric_underlying() and set_numeric_standard() functions, which
209 * should probably not be called directly, but only via macros like
0d071d52
KW
210 * SET_NUMERIC_STANDARD() in perl.h.
211 *
212 * The toggling is necessary mainly so that a non-dot radix decimal point
213 * character can be output, while allowing internal calculations to use a
214 * dot.
215 *
216 * This sets several interpreter-level variables:
bb304765 217 * PL_numeric_name The underlying locale's name: a copy of 'newnum'
892e6465 218 * PL_numeric_underlying A boolean indicating if the toggled state is such
7738054c
KW
219 * that the current locale is the program's underlying
220 * locale
221 * PL_numeric_standard An int indicating if the toggled state is such
222 * that the current locale is the C locale. If non-zero,
223 * it is in C; if > 1, it means it may not be toggled away
224 * from C.
0d071d52
KW
225 * Note that both of the last two variables can be true at the same time,
226 * if the underlying locale is C. (Toggling is a no-op under these
227 * circumstances.)
228 *
229 * Any code changing the locale (outside this file) should use
230 * POSIX::setlocale, which calls this function. Therefore this function
231 * should be called directly only from this file and from
232 * POSIX::setlocale() */
233
b03f34cf 234 char *save_newnum;
98994639
HS
235
236 if (! newnum) {
43c5f42d
NC
237 Safefree(PL_numeric_name);
238 PL_numeric_name = NULL;
98994639 239 PL_numeric_standard = TRUE;
892e6465 240 PL_numeric_underlying = TRUE;
98994639
HS
241 return;
242 }
243
b03f34cf 244 save_newnum = stdize_locale(savepv(newnum));
abe1abcf
KW
245
246 PL_numeric_standard = isNAME_C_OR_POSIX(save_newnum);
892e6465 247 PL_numeric_underlying = TRUE;
abe1abcf 248
b03f34cf 249 if (! PL_numeric_name || strNE(PL_numeric_name, save_newnum)) {
98994639 250 Safefree(PL_numeric_name);
b03f34cf 251 PL_numeric_name = save_newnum;
b03f34cf 252 }
abe1abcf
KW
253 else {
254 Safefree(save_newnum);
255 }
4c28b29c
KW
256
257 /* Keep LC_NUMERIC in the C locale. This is for XS modules, so they don't
258 * have to worry about the radix being a non-dot. (Core operations that
259 * need the underlying locale change to it temporarily). */
260 set_numeric_standard();
261
98994639 262#endif /* USE_LOCALE_NUMERIC */
7d4bcc4a 263
98994639
HS
264}
265
266void
267Perl_set_numeric_standard(pTHX)
268{
7d4bcc4a 269
98994639 270#ifdef USE_LOCALE_NUMERIC
7d4bcc4a 271
28c1bf33
KW
272 /* Toggle the LC_NUMERIC locale to C. Most code should use the macros like
273 * SET_NUMERIC_STANDARD() in perl.h instead of calling this directly. The
274 * macro avoids calling this routine if toggling isn't necessary according
275 * to our records (which could be wrong if some XS code has changed the
276 * locale behind our back) */
0d071d52 277
837ce802 278 do_setlocale_c(LC_NUMERIC, "C");
a9b8c0d8 279 PL_numeric_standard = TRUE;
892e6465 280 PL_numeric_underlying = isNAME_C_OR_POSIX(PL_numeric_name);
86799d2d 281 set_numeric_radix(0);
7d4bcc4a
KW
282
283# ifdef DEBUGGING
284
2fcc0ca9
KW
285 if (DEBUG_L_TEST || debug_initialization) {
286 PerlIO_printf(Perl_debug_log,
58e4a467 287 "LC_NUMERIC locale now is standard C\n");
2fcc0ca9 288 }
98994639 289
7d4bcc4a 290# endif
98994639 291#endif /* USE_LOCALE_NUMERIC */
7d4bcc4a 292
98994639
HS
293}
294
295void
5792c642 296Perl_set_numeric_underlying(pTHX)
98994639 297{
7d4bcc4a 298
98994639 299#ifdef USE_LOCALE_NUMERIC
7d4bcc4a 300
28c1bf33 301 /* Toggle the LC_NUMERIC locale to the current underlying default. Most
7d4bcc4a
KW
302 * code should use the macros like SET_NUMERIC_UNDERLYING() in perl.h
303 * instead of calling this directly. The macro avoids calling this routine
304 * if toggling isn't necessary according to our records (which could be
305 * wrong if some XS code has changed the locale behind our back) */
a9b8c0d8 306
837ce802 307 do_setlocale_c(LC_NUMERIC, PL_numeric_name);
a9b8c0d8 308 PL_numeric_standard = isNAME_C_OR_POSIX(PL_numeric_name);
892e6465 309 PL_numeric_underlying = TRUE;
86799d2d 310 set_numeric_radix(1);
7d4bcc4a
KW
311
312# ifdef DEBUGGING
313
2fcc0ca9
KW
314 if (DEBUG_L_TEST || debug_initialization) {
315 PerlIO_printf(Perl_debug_log,
58e4a467 316 "LC_NUMERIC locale now is %s\n",
2fcc0ca9
KW
317 PL_numeric_name);
318 }
98994639 319
7d4bcc4a 320# endif
98994639 321#endif /* USE_LOCALE_NUMERIC */
7d4bcc4a 322
98994639
HS
323}
324
325/*
326 * Set up for a new ctype locale.
327 */
a4f00dcc
KW
328STATIC void
329S_new_ctype(pTHX_ const char *newctype)
98994639 330{
7d4bcc4a
KW
331
332#ifndef USE_LOCALE_CTYPE
333
334 PERL_ARGS_ASSERT_NEW_CTYPE;
335 PERL_UNUSED_ARG(newctype);
336 PERL_UNUSED_CONTEXT;
337
338#else
0d071d52
KW
339
340 /* Called after all libc setlocale() calls affecting LC_CTYPE, to tell
341 * core Perl this and that 'newctype' is the name of the new locale.
342 *
343 * This function sets up the folding arrays for all 256 bytes, assuming
344 * that tofold() is tolc() since fold case is not a concept in POSIX,
345 *
346 * Any code changing the locale (outside this file) should use
347 * POSIX::setlocale, which calls this function. Therefore this function
348 * should be called directly only from this file and from
349 * POSIX::setlocale() */
350
27da23d5 351 dVAR;
68067e4e 352 UV i;
98994639 353
7918f24d
NC
354 PERL_ARGS_ASSERT_NEW_CTYPE;
355
215c5139
KW
356 /* We will replace any bad locale warning with 1) nothing if the new one is
357 * ok; or 2) a new warning for the bad new locale */
358 if (PL_warn_locale) {
359 SvREFCNT_dec_NN(PL_warn_locale);
360 PL_warn_locale = NULL;
361 }
362
c1284011 363 PL_in_utf8_CTYPE_locale = _is_cur_LC_category_utf8(LC_CTYPE);
31f05a37
KW
364
365 /* A UTF-8 locale gets standard rules. But note that code still has to
366 * handle this specially because of the three problematic code points */
367 if (PL_in_utf8_CTYPE_locale) {
368 Copy(PL_fold_latin1, PL_fold_locale, 256, U8);
369 }
370 else {
8c6180a9
KW
371 /* Assume enough space for every character being bad. 4 spaces each
372 * for the 94 printable characters that are output like "'x' "; and 5
373 * spaces each for "'\\' ", "'\t' ", and "'\n' "; plus a terminating
374 * NUL */
375 char bad_chars_list[ (94 * 4) + (3 * 5) + 1 ];
376
cc9eaeb0
KW
377 /* Don't check for problems if we are suppressing the warnings */
378 bool check_for_problems = ckWARN_d(WARN_LOCALE)
379 || UNLIKELY(DEBUG_L_TEST);
8c6180a9
KW
380 bool multi_byte_locale = FALSE; /* Assume is a single-byte locale
381 to start */
382 unsigned int bad_count = 0; /* Count of bad characters */
383
baa60164
KW
384 for (i = 0; i < 256; i++) {
385 if (isUPPER_LC((U8) i))
386 PL_fold_locale[i] = (U8) toLOWER_LC((U8) i);
387 else if (isLOWER_LC((U8) i))
388 PL_fold_locale[i] = (U8) toUPPER_LC((U8) i);
389 else
390 PL_fold_locale[i] = (U8) i;
8c6180a9
KW
391
392 /* If checking for locale problems, see if the native ASCII-range
393 * printables plus \n and \t are in their expected categories in
394 * the new locale. If not, this could mean big trouble, upending
395 * Perl's and most programs' assumptions, like having a
396 * metacharacter with special meaning become a \w. Fortunately,
397 * it's very rare to find locales that aren't supersets of ASCII
398 * nowadays. It isn't a problem for most controls to be changed
399 * into something else; we check only \n and \t, though perhaps \r
400 * could be an issue as well. */
7d4bcc4a 401 if ( check_for_problems
8c6180a9
KW
402 && (isGRAPH_A(i) || isBLANK_A(i) || i == '\n'))
403 {
7d4bcc4a 404 if (( isALPHANUMERIC_A(i) && ! isALPHANUMERIC_LC(i))
8c6180a9
KW
405 || (isPUNCT_A(i) && ! isPUNCT_LC(i))
406 || (isBLANK_A(i) && ! isBLANK_LC(i))
407 || (i == '\n' && ! isCNTRL_LC(i)))
408 {
409 if (bad_count) { /* Separate multiple entries with a
410 blank */
411 bad_chars_list[bad_count++] = ' ';
412 }
413 bad_chars_list[bad_count++] = '\'';
414 if (isPRINT_A(i)) {
415 bad_chars_list[bad_count++] = (char) i;
416 }
417 else {
418 bad_chars_list[bad_count++] = '\\';
419 if (i == '\n') {
420 bad_chars_list[bad_count++] = 'n';
421 }
422 else {
423 assert(i == '\t');
424 bad_chars_list[bad_count++] = 't';
425 }
426 }
427 bad_chars_list[bad_count++] = '\'';
428 bad_chars_list[bad_count] = '\0';
429 }
430 }
431 }
432
7d4bcc4a
KW
433# ifdef MB_CUR_MAX
434
8c6180a9 435 /* We only handle single-byte locales (outside of UTF-8 ones; so if
d35fca5f 436 * this locale requires more than one byte, there are going to be
8c6180a9 437 * problems. */
9c8a6dc2
KW
438 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
439 "%s:%d: check_for_problems=%d, MB_CUR_MAX=%d\n",
440 __FILE__, __LINE__, check_for_problems, (int) MB_CUR_MAX));
441
ba1a4362
KW
442 if (check_for_problems && MB_CUR_MAX > 1
443
444 /* Some platforms return MB_CUR_MAX > 1 for even the "C"
445 * locale. Just assume that the implementation for them (plus
446 * for POSIX) is correct and the > 1 value is spurious. (Since
447 * these are specially handled to never be considered UTF-8
448 * locales, as long as this is the only problem, everything
449 * should work fine */
450 && strNE(newctype, "C") && strNE(newctype, "POSIX"))
451 {
8c6180a9
KW
452 multi_byte_locale = TRUE;
453 }
7d4bcc4a
KW
454
455# endif
8c6180a9
KW
456
457 if (bad_count || multi_byte_locale) {
780fcc9f 458 PL_warn_locale = Perl_newSVpvf(aTHX_
8c6180a9 459 "Locale '%s' may not work well.%s%s%s\n",
780fcc9f 460 newctype,
8c6180a9
KW
461 (multi_byte_locale)
462 ? " Some characters in it are not recognized by"
463 " Perl."
464 : "",
465 (bad_count)
466 ? "\nThe following characters (and maybe others)"
467 " may not have the same meaning as the Perl"
468 " program expects:\n"
469 : "",
470 (bad_count)
471 ? bad_chars_list
472 : ""
473 );
cc9eaeb0 474 /* If we are actually in the scope of the locale or are debugging,
bddebb56
KW
475 * output the message now. If not in that scope, we save the
476 * message to be output at the first operation using this locale,
477 * if that actually happens. Most programs don't use locales, so
478 * they are immune to bad ones. */
cc9eaeb0 479 if (IN_LC(LC_CTYPE) || UNLIKELY(DEBUG_L_TEST)) {
780fcc9f
KW
480
481 /* We have to save 'newctype' because the setlocale() just
482 * below may destroy it. The next setlocale() further down
483 * should restore it properly so that the intermediate change
484 * here is transparent to this function's caller */
485 const char * const badlocale = savepv(newctype);
486
837ce802 487 do_setlocale_c(LC_CTYPE, "C");
780fcc9f
KW
488
489 /* The '0' below suppresses a bogus gcc compiler warning */
490 Perl_warner(aTHX_ packWARN(WARN_LOCALE), SvPVX(PL_warn_locale), 0);
bddebb56 491
837ce802 492 do_setlocale_c(LC_CTYPE, badlocale);
c0f3a893 493 Safefree(badlocale);
bddebb56
KW
494
495 if (IN_LC(LC_CTYPE)) {
496 SvREFCNT_dec_NN(PL_warn_locale);
497 PL_warn_locale = NULL;
498 }
780fcc9f 499 }
baa60164 500 }
31f05a37 501 }
98994639
HS
502
503#endif /* USE_LOCALE_CTYPE */
7d4bcc4a 504
98994639
HS
505}
506
98994639 507void
2726666d
KW
508Perl__warn_problematic_locale()
509{
2726666d
KW
510
511#ifdef USE_LOCALE_CTYPE
512
5f04a188
KW
513 dTHX;
514
515 /* Internal-to-core function that outputs the message in PL_warn_locale,
516 * and then NULLS it. Should be called only through the macro
517 * _CHECK_AND_WARN_PROBLEMATIC_LOCALE */
518
2726666d
KW
519 if (PL_warn_locale) {
520 /*GCC_DIAG_IGNORE(-Wformat-security); Didn't work */
521 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
522 SvPVX(PL_warn_locale),
523 0 /* dummy to avoid compiler warning */ );
524 /* GCC_DIAG_RESTORE; */
525 SvREFCNT_dec_NN(PL_warn_locale);
526 PL_warn_locale = NULL;
527 }
528
529#endif
530
531}
532
a4f00dcc
KW
533STATIC void
534S_new_collate(pTHX_ const char *newcoll)
98994639 535{
7d4bcc4a
KW
536
537#ifndef USE_LOCALE_COLLATE
538
539 PERL_UNUSED_ARG(newcoll);
540 PERL_UNUSED_CONTEXT;
541
542#else
0d071d52
KW
543
544 /* Called after all libc setlocale() calls affecting LC_COLLATE, to tell
545 * core Perl this and that 'newcoll' is the name of the new locale.
546 *
d35fca5f
KW
547 * The design of locale collation is that every locale change is given an
548 * index 'PL_collation_ix'. The first time a string particpates in an
549 * operation that requires collation while locale collation is active, it
550 * is given PERL_MAGIC_collxfrm magic (via sv_collxfrm_flags()). That
551 * magic includes the collation index, and the transformation of the string
552 * by strxfrm(), q.v. That transformation is used when doing comparisons,
553 * instead of the string itself. If a string changes, the magic is
554 * cleared. The next time the locale changes, the index is incremented,
555 * and so we know during a comparison that the transformation is not
556 * necessarily still valid, and so is recomputed. Note that if the locale
557 * changes enough times, the index could wrap (a U32), and it is possible
558 * that a transformation would improperly be considered valid, leading to
559 * an unlikely bug */
0d071d52 560
98994639
HS
561 if (! newcoll) {
562 if (PL_collation_name) {
563 ++PL_collation_ix;
564 Safefree(PL_collation_name);
565 PL_collation_name = NULL;
566 }
567 PL_collation_standard = TRUE;
00bf60ca 568 is_standard_collation:
98994639
HS
569 PL_collxfrm_base = 0;
570 PL_collxfrm_mult = 2;
165a1c52 571 PL_in_utf8_COLLATE_locale = FALSE;
f28f4d2a 572 PL_strxfrm_NUL_replacement = '\0';
a4a439fb 573 PL_strxfrm_max_cp = 0;
98994639
HS
574 return;
575 }
576
d35fca5f 577 /* If this is not the same locale as currently, set the new one up */
98994639
HS
578 if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
579 ++PL_collation_ix;
580 Safefree(PL_collation_name);
581 PL_collation_name = stdize_locale(savepv(newcoll));
a39edc4c 582 PL_collation_standard = isNAME_C_OR_POSIX(newcoll);
00bf60ca
KW
583 if (PL_collation_standard) {
584 goto is_standard_collation;
585 }
98994639 586
165a1c52 587 PL_in_utf8_COLLATE_locale = _is_cur_LC_category_utf8(LC_COLLATE);
f28f4d2a 588 PL_strxfrm_NUL_replacement = '\0';
a4a439fb 589 PL_strxfrm_max_cp = 0;
165a1c52 590
59c018b9
KW
591 /* A locale collation definition includes primary, secondary, tertiary,
592 * etc. weights for each character. To sort, the primary weights are
593 * used, and only if they compare equal, then the secondary weights are
594 * used, and only if they compare equal, then the tertiary, etc.
595 *
596 * strxfrm() works by taking the input string, say ABC, and creating an
597 * output transformed string consisting of first the primary weights,
598 * A¹B¹C¹ followed by the secondary ones, A²B²C²; and then the
599 * tertiary, etc, yielding A¹B¹C¹ A²B²C² A³B³C³ .... Some characters
600 * may not have weights at every level. In our example, let's say B
601 * doesn't have a tertiary weight, and A doesn't have a secondary
602 * weight. The constructed string is then going to be
603 * A¹B¹C¹ B²C² A³C³ ....
604 * This has the desired effect that strcmp() will look at the secondary
605 * or tertiary weights only if the strings compare equal at all higher
606 * priority weights. The spaces shown here, like in
c342d20e 607 * "A¹B¹C¹ A²B²C² "
59c018b9
KW
608 * are not just for readability. In the general case, these must
609 * actually be bytes, which we will call here 'separator weights'; and
610 * they must be smaller than any other weight value, but since these
611 * are C strings, only the terminating one can be a NUL (some
612 * implementations may include a non-NUL separator weight just before
613 * the NUL). Implementations tend to reserve 01 for the separator
614 * weights. They are needed so that a shorter string's secondary
615 * weights won't be misconstrued as primary weights of a longer string,
616 * etc. By making them smaller than any other weight, the shorter
617 * string will sort first. (Actually, if all secondary weights are
618 * smaller than all primary ones, there is no need for a separator
619 * weight between those two levels, etc.)
620 *
621 * The length of the transformed string is roughly a linear function of
622 * the input string. It's not exactly linear because some characters
623 * don't have weights at all levels. When we call strxfrm() we have to
624 * allocate some memory to hold the transformed string. The
625 * calculations below try to find coefficients 'm' and 'b' for this
626 * locale so that m*x + b equals how much space we need, given the size
627 * of the input string in 'x'. If we calculate too small, we increase
628 * the size as needed, and call strxfrm() again, but it is better to
629 * get it right the first time to avoid wasted expensive string
630 * transformations. */
631
98994639 632 {
79f120c8
KW
633 /* We use the string below to find how long the tranformation of it
634 * is. Almost all locales are supersets of ASCII, or at least the
635 * ASCII letters. We use all of them, half upper half lower,
636 * because if we used fewer, we might hit just the ones that are
637 * outliers in a particular locale. Most of the strings being
638 * collated will contain a preponderance of letters, and even if
639 * they are above-ASCII, they are likely to have the same number of
640 * weight levels as the ASCII ones. It turns out that digits tend
641 * to have fewer levels, and some punctuation has more, but those
642 * are relatively sparse in text, and khw believes this gives a
643 * reasonable result, but it could be changed if experience so
644 * dictates. */
645 const char longer[] = "ABCDEFGHIJKLMnopqrstuvwxyz";
646 char * x_longer; /* Transformed 'longer' */
647 Size_t x_len_longer; /* Length of 'x_longer' */
648
649 char * x_shorter; /* We also transform a substring of 'longer' */
650 Size_t x_len_shorter;
651
a4a439fb 652 /* _mem_collxfrm() is used get the transformation (though here we
79f120c8
KW
653 * are interested only in its length). It is used because it has
654 * the intelligence to handle all cases, but to work, it needs some
655 * values of 'm' and 'b' to get it started. For the purposes of
656 * this calculation we use a very conservative estimate of 'm' and
657 * 'b'. This assumes a weight can be multiple bytes, enough to
658 * hold any UV on the platform, and there are 5 levels, 4 weight
659 * bytes, and a trailing NUL. */
660 PL_collxfrm_base = 5;
661 PL_collxfrm_mult = 5 * sizeof(UV);
662
663 /* Find out how long the transformation really is */
a4a439fb
KW
664 x_longer = _mem_collxfrm(longer,
665 sizeof(longer) - 1,
666 &x_len_longer,
667
668 /* We avoid converting to UTF-8 in the
669 * called function by telling it the
670 * string is in UTF-8 if the locale is a
671 * UTF-8 one. Since the string passed
672 * here is invariant under UTF-8, we can
673 * claim it's UTF-8 even though it isn't.
674 * */
675 PL_in_utf8_COLLATE_locale);
79f120c8
KW
676 Safefree(x_longer);
677
678 /* Find out how long the transformation of a substring of 'longer'
679 * is. Together the lengths of these transformations are
680 * sufficient to calculate 'm' and 'b'. The substring is all of
681 * 'longer' except the first character. This minimizes the chances
682 * of being swayed by outliers */
a4a439fb 683 x_shorter = _mem_collxfrm(longer + 1,
79f120c8 684 sizeof(longer) - 2,
a4a439fb
KW
685 &x_len_shorter,
686 PL_in_utf8_COLLATE_locale);
79f120c8
KW
687 Safefree(x_shorter);
688
689 /* If the results are nonsensical for this simple test, the whole
690 * locale definition is suspect. Mark it so that locale collation
691 * is not active at all for it. XXX Should we warn? */
692 if ( x_len_shorter == 0
693 || x_len_longer == 0
694 || x_len_shorter >= x_len_longer)
695 {
696 PL_collxfrm_mult = 0;
697 PL_collxfrm_base = 0;
698 }
699 else {
700 SSize_t base; /* Temporary */
701
702 /* We have both: m * strlen(longer) + b = x_len_longer
703 * m * strlen(shorter) + b = x_len_shorter;
704 * subtracting yields:
705 * m * (strlen(longer) - strlen(shorter))
706 * = x_len_longer - x_len_shorter
707 * But we have set things up so that 'shorter' is 1 byte smaller
708 * than 'longer'. Hence:
709 * m = x_len_longer - x_len_shorter
710 *
711 * But if something went wrong, make sure the multiplier is at
712 * least 1.
713 */
714 if (x_len_longer > x_len_shorter) {
715 PL_collxfrm_mult = (STRLEN) x_len_longer - x_len_shorter;
716 }
717 else {
718 PL_collxfrm_mult = 1;
719 }
720
721 /* mx + b = len
722 * so: b = len - mx
723 * but in case something has gone wrong, make sure it is
724 * non-negative */
725 base = x_len_longer - PL_collxfrm_mult * (sizeof(longer) - 1);
726 if (base < 0) {
727 base = 0;
728 }
729
730 /* Add 1 for the trailing NUL */
731 PL_collxfrm_base = base + 1;
732 }
58eebef2 733
7d4bcc4a
KW
734# ifdef DEBUGGING
735
58eebef2
KW
736 if (DEBUG_L_TEST || debug_initialization) {
737 PerlIO_printf(Perl_debug_log,
b07929e4
KW
738 "%s:%d: ?UTF-8 locale=%d; x_len_shorter=%zu, "
739 "x_len_longer=%zu,"
740 " collate multipler=%zu, collate base=%zu\n",
58eebef2
KW
741 __FILE__, __LINE__,
742 PL_in_utf8_COLLATE_locale,
743 x_len_shorter, x_len_longer,
744 PL_collxfrm_mult, PL_collxfrm_base);
745 }
7d4bcc4a
KW
746# endif
747
98994639
HS
748 }
749 }
750
751#endif /* USE_LOCALE_COLLATE */
7d4bcc4a 752
98994639
HS
753}
754
d2b24094 755#ifdef WIN32
b8cc575c 756
a4f00dcc 757STATIC char *
b8cc575c 758S_win32_setlocale(pTHX_ int category, const char* locale)
b385bb4d
KW
759{
760 /* This, for Windows, emulates POSIX setlocale() behavior. There is no
7d4bcc4a
KW
761 * difference between the two unless the input locale is "", which normally
762 * means on Windows to get the machine default, which is set via the
763 * computer's "Regional and Language Options" (or its current equivalent).
764 * In POSIX, it instead means to find the locale from the user's
765 * environment. This routine changes the Windows behavior to first look in
766 * the environment, and, if anything is found, use that instead of going to
767 * the machine default. If there is no environment override, the machine
768 * default is used, by calling the real setlocale() with "".
769 *
770 * The POSIX behavior is to use the LC_ALL variable if set; otherwise to
771 * use the particular category's variable if set; otherwise to use the LANG
772 * variable. */
b385bb4d 773
175c4cf9 774 bool override_LC_ALL = FALSE;
89f7b9aa
KW
775 char * result;
776
b385bb4d 777 if (locale && strEQ(locale, "")) {
7d4bcc4a
KW
778
779# ifdef LC_ALL
780
b385bb4d
KW
781 locale = PerlEnv_getenv("LC_ALL");
782 if (! locale) {
7d4bcc4a
KW
783
784# endif
b385bb4d 785 switch (category) {
7d4bcc4a
KW
786
787# ifdef LC_ALL
b385bb4d 788 case LC_ALL:
481465ea 789 override_LC_ALL = TRUE;
b385bb4d 790 break; /* We already know its variable isn't set */
7d4bcc4a
KW
791
792# endif
793# ifdef USE_LOCALE_TIME
794
b385bb4d
KW
795 case LC_TIME:
796 locale = PerlEnv_getenv("LC_TIME");
797 break;
7d4bcc4a
KW
798
799# endif
800# ifdef USE_LOCALE_CTYPE
801
b385bb4d
KW
802 case LC_CTYPE:
803 locale = PerlEnv_getenv("LC_CTYPE");
804 break;
7d4bcc4a
KW
805
806# endif
807# ifdef USE_LOCALE_COLLATE
808
b385bb4d
KW
809 case LC_COLLATE:
810 locale = PerlEnv_getenv("LC_COLLATE");
811 break;
7d4bcc4a
KW
812
813# endif
814# ifdef USE_LOCALE_MONETARY
815
b385bb4d
KW
816 case LC_MONETARY:
817 locale = PerlEnv_getenv("LC_MONETARY");
818 break;
7d4bcc4a
KW
819
820# endif
821# ifdef USE_LOCALE_NUMERIC
822
b385bb4d
KW
823 case LC_NUMERIC:
824 locale = PerlEnv_getenv("LC_NUMERIC");
825 break;
7d4bcc4a
KW
826
827# endif
828# ifdef USE_LOCALE_MESSAGES
829
b385bb4d
KW
830 case LC_MESSAGES:
831 locale = PerlEnv_getenv("LC_MESSAGES");
832 break;
7d4bcc4a
KW
833
834# endif
835
b385bb4d
KW
836 default:
837 /* This is a category, like PAPER_SIZE that we don't
838 * know about; and so can't provide a wrapper. */
839 break;
840 }
841 if (! locale) {
842 locale = PerlEnv_getenv("LANG");
481465ea 843 if (! locale) {
b385bb4d
KW
844 locale = "";
845 }
846 }
7d4bcc4a
KW
847
848# ifdef LC_ALL
849
b385bb4d 850 }
7d4bcc4a
KW
851
852# endif
853
b385bb4d
KW
854 }
855
89f7b9aa 856 result = setlocale(category, locale);
bbc98134 857 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n", __FILE__, __LINE__,
a4f00dcc 858 setlocale_debug_string(category, locale, result)));
89f7b9aa 859
481465ea 860 if (! override_LC_ALL) {
89f7b9aa
KW
861 return result;
862 }
863
dfd77d7a 864 /* Here the input category was LC_ALL, and we have set it to what is in the
481465ea
KW
865 * LANG variable or the system default if there is no LANG. But these have
866 * lower priority than the other LC_foo variables, so override it for each
867 * one that is set. (If they are set to "", it means to use the same thing
868 * we just set LC_ALL to, so can skip) */
7d4bcc4a
KW
869
870# ifdef USE_LOCALE_TIME
871
89f7b9aa 872 result = PerlEnv_getenv("LC_TIME");
730252b2 873 if (result && strNE(result, "")) {
89f7b9aa 874 setlocale(LC_TIME, result);
bbc98134
KW
875 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
876 __FILE__, __LINE__,
a4f00dcc 877 setlocale_debug_string(LC_TIME, result, "not captured")));
89f7b9aa 878 }
7d4bcc4a
KW
879
880# endif
881# ifdef USE_LOCALE_CTYPE
882
89f7b9aa 883 result = PerlEnv_getenv("LC_CTYPE");
730252b2 884 if (result && strNE(result, "")) {
89f7b9aa 885 setlocale(LC_CTYPE, result);
bbc98134
KW
886 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
887 __FILE__, __LINE__,
a4f00dcc 888 setlocale_debug_string(LC_CTYPE, result, "not captured")));
89f7b9aa 889 }
7d4bcc4a
KW
890
891# endif
892# ifdef USE_LOCALE_COLLATE
893
89f7b9aa 894 result = PerlEnv_getenv("LC_COLLATE");
730252b2 895 if (result && strNE(result, "")) {
89f7b9aa 896 setlocale(LC_COLLATE, result);
bbc98134
KW
897 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
898 __FILE__, __LINE__,
a4f00dcc 899 setlocale_debug_string(LC_COLLATE, result, "not captured")));
89f7b9aa 900 }
7d4bcc4a
KW
901
902# endif
903# ifdef USE_LOCALE_MONETARY
904
89f7b9aa 905 result = PerlEnv_getenv("LC_MONETARY");
730252b2 906 if (result && strNE(result, "")) {
89f7b9aa 907 setlocale(LC_MONETARY, result);
bbc98134
KW
908 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
909 __FILE__, __LINE__,
a4f00dcc 910 setlocale_debug_string(LC_MONETARY, result, "not captured")));
89f7b9aa 911 }
7d4bcc4a
KW
912
913# endif
914# ifdef USE_LOCALE_NUMERIC
915
89f7b9aa 916 result = PerlEnv_getenv("LC_NUMERIC");
730252b2 917 if (result && strNE(result, "")) {
89f7b9aa 918 setlocale(LC_NUMERIC, result);
bbc98134
KW
919 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
920 __FILE__, __LINE__,
a4f00dcc 921 setlocale_debug_string(LC_NUMERIC, result, "not captured")));
89f7b9aa 922 }
7d4bcc4a
KW
923
924# endif
925# ifdef USE_LOCALE_MESSAGES
926
89f7b9aa 927 result = PerlEnv_getenv("LC_MESSAGES");
730252b2 928 if (result && strNE(result, "")) {
89f7b9aa 929 setlocale(LC_MESSAGES, result);
bbc98134
KW
930 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
931 __FILE__, __LINE__,
a4f00dcc 932 setlocale_debug_string(LC_MESSAGES, result, "not captured")));
89f7b9aa 933 }
7d4bcc4a
KW
934
935# endif
89f7b9aa 936
bbc98134
KW
937 result = setlocale(LC_ALL, NULL);
938 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
939 __FILE__, __LINE__,
a4f00dcc 940 setlocale_debug_string(LC_ALL, NULL, result)));
89f7b9aa 941
bbc98134 942 return result;
b385bb4d
KW
943}
944
945#endif
946
a4f00dcc
KW
947char *
948Perl_setlocale(int category, const char * locale)
949{
950 /* This wraps POSIX::setlocale() */
951
952 char * retval;
1159483a 953 char * newlocale;
a4f00dcc
KW
954 dTHX;
955
a4f00dcc
KW
956#ifdef USE_LOCALE_NUMERIC
957
958 /* A NULL locale means only query what the current one is. We
959 * have the LC_NUMERIC name saved, because we are normally switched
960 * into the C locale for it. Switch back so an LC_ALL query will yield
961 * the correct results; all other categories don't require special
962 * handling */
963 if (locale == NULL) {
964 if (category == LC_NUMERIC) {
965 return savepv(PL_numeric_name);
966 }
967
7d4bcc4a 968# ifdef LC_ALL
a4f00dcc
KW
969
970 else if (category == LC_ALL) {
971 SET_NUMERIC_UNDERLYING();
972 }
973
7d4bcc4a 974# endif
a4f00dcc
KW
975
976 }
977
978#endif
979
d2b24094 980 retval = do_setlocale_r(category, locale);
a4f00dcc
KW
981
982 DEBUG_L(PerlIO_printf(Perl_debug_log,
983 "%s:%d: %s\n", __FILE__, __LINE__,
984 setlocale_debug_string(category, locale, retval)));
985 if (! retval) {
986 /* Should never happen that a query would return an error, but be
987 * sure and reset to C locale */
988 if (locale == 0) {
989 SET_NUMERIC_STANDARD();
990 }
7d4bcc4a 991
a4f00dcc
KW
992 return NULL;
993 }
994
995 /* Save retval since subsequent setlocale() calls may overwrite it. */
996 retval = savepv(retval);
997
998 /* If locale == NULL, we are just querying the state, but may have switched
999 * to NUMERIC_UNDERLYING. Switch back before returning. */
1000 if (locale == NULL) {
1001 SET_NUMERIC_STANDARD();
1002 return retval;
1003 }
a4f00dcc 1004
1159483a
KW
1005 /* Now that have switched locales, we have to update our records to
1006 * correspond. */
a4f00dcc 1007
1159483a 1008 switch (category) {
a4f00dcc 1009
1159483a 1010#ifdef USE_LOCALE_CTYPE
a4f00dcc 1011
1159483a
KW
1012 case LC_CTYPE:
1013 new_ctype(retval);
1014 break;
a4f00dcc 1015
1159483a 1016#endif
a4f00dcc
KW
1017#ifdef USE_LOCALE_COLLATE
1018
1159483a
KW
1019 case LC_COLLATE:
1020 new_collate(retval);
1021 break;
a4f00dcc 1022
1159483a 1023#endif
a4f00dcc
KW
1024#ifdef USE_LOCALE_NUMERIC
1025
1159483a
KW
1026 case LC_NUMERIC:
1027 new_numeric(retval);
1028 break;
a4f00dcc 1029
1159483a
KW
1030#endif
1031#ifdef LC_ALL
a4f00dcc 1032
1159483a 1033 case LC_ALL:
a4f00dcc 1034
1159483a
KW
1035 /* LC_ALL updates all the things we care about. The values may not
1036 * be the same as 'retval', as the locale "" may have set things
1037 * individually */
a4f00dcc 1038
1159483a 1039# ifdef USE_LOCALE_CTYPE
a4f00dcc 1040
1159483a
KW
1041 newlocale = do_setlocale_c(LC_CTYPE, NULL);
1042 new_ctype(newlocale);
a4f00dcc 1043
1159483a
KW
1044# endif /* USE_LOCALE_CTYPE */
1045# ifdef USE_LOCALE_COLLATE
1046
1047 newlocale = do_setlocale_c(LC_COLLATE, NULL);
1048 new_collate(newlocale);
a4f00dcc 1049
7d4bcc4a 1050# endif
1159483a 1051# ifdef USE_LOCALE_NUMERIC
a4f00dcc 1052
1159483a
KW
1053 newlocale = do_setlocale_c(LC_NUMERIC, NULL);
1054 new_numeric(newlocale);
a4f00dcc 1055
1159483a
KW
1056# endif /* USE_LOCALE_NUMERIC */
1057#endif /* LC_ALL */
a4f00dcc 1058
1159483a
KW
1059 default:
1060 break;
a4f00dcc
KW
1061 }
1062
1063 return retval;
1064
f7416781
KW
1065
1066}
1067
1068PERL_STATIC_INLINE const char *
1069S_save_to_buffer(const char * string, char **buf, Size_t *buf_size, const Size_t offset)
1070{
1071 /* Copy the NUL-terminated 'string' to 'buf' + 'offset'. 'buf' has size 'buf_size',
1072 * growing it if necessary */
1073
1074 const Size_t string_size = strlen(string) + offset + 1;
1075
1076 PERL_ARGS_ASSERT_SAVE_TO_BUFFER;
1077
1078 if (*buf_size == 0) {
1079 Newx(*buf, string_size, char);
1080 *buf_size = string_size;
1081 }
1082 else if (string_size > *buf_size) {
1083 Renew(*buf, string_size, char);
1084 *buf_size = string_size;
1085 }
1086
1087 Copy(string, *buf + offset, string_size - offset, char);
1088 return *buf;
1089}
1090
1091/*
1092
1093=head1 Locale-related functions and macros
1094
1095=for apidoc Perl_langinfo
1096
7d4bcc4a 1097This is an (almost ª) drop-in replacement for the system C<L<nl_langinfo(3)>>,
f7416781
KW
1098taking the same C<item> parameter values, and returning the same information.
1099But it is more thread-safe than regular C<nl_langinfo()>, and hides the quirks
1100of Perl's locale handling from your code, and can be used on systems that lack
1101a native C<nl_langinfo>.
1102
1103Expanding on these:
1104
1105=over
1106
1107=item *
1108
1109It delivers the correct results for the C<RADIXCHAR> and C<THOUSESEP> items,
1110without you having to write extra code. The reason for the extra code would be
1111because these are from the C<LC_NUMERIC> locale category, which is normally
1112kept set to the C locale by Perl, no matter what the underlying locale is
1113supposed to be, and so to get the expected results, you have to temporarily
1114toggle into the underlying locale, and later toggle back. (You could use
1115plain C<nl_langinfo> and C<L</STORE_LC_NUMERIC_FORCE_TO_UNDERLYING>> for this
1116but then you wouldn't get the other advantages of C<Perl_langinfo()>; not
1117keeping C<LC_NUMERIC> in the C locale would break a lot of CPAN, which is
1118expecting the radix (decimal point) character to be a dot.)
1119
1120=item *
1121
1122Depending on C<item>, it works on systems that don't have C<nl_langinfo>, hence
1123makes your code more portable. Of the fifty-some possible items specified by
1124the POSIX 2008 standard,
1125L<http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/langinfo.h.html>,
1126only two are completely unimplemented. It uses various techniques to recover
1127the other items, including calling C<L<localeconv(3)>>, and C<L<strftime(3)>>,
1128both of which are specified in C89, so should be always be available. Later
1129C<strftime()> versions have additional capabilities; C<""> is returned for
1130those not available on your system.
1131
1132The details for those items which may differ from what this emulation returns
1133and what a native C<nl_langinfo()> would return are:
1134
1135=over
1136
1137=item C<CODESET>
1138
1139=item C<ERA>
1140
1141Unimplemented, so returns C<"">.
1142
1143=item C<YESEXPR>
1144
1145=item C<NOEXPR>
1146
1147Only the values for English are returned. Earlier POSIX standards also
1148specified C<YESSTR> and C<NOSTR>, but these have been removed from POSIX 2008,
1149and aren't supported by C<Perl_langinfo>.
1150
1151=item C<D_FMT>
1152
1153Always evaluates to C<%x>, the locale's appropriate date representation.
1154
1155=item C<T_FMT>
1156
1157Always evaluates to C<%X>, the locale's appropriate time representation.
1158
1159=item C<D_T_FMT>
1160
1161Always evaluates to C<%c>, the locale's appropriate date and time
1162representation.
1163
1164=item C<CRNCYSTR>
1165
1166The return may be incorrect for those rare locales where the currency symbol
1167replaces the radix character.
1168Send email to L<mailto:perlbug@perl.org> if you have examples of it needing
1169to work differently.
1170
1171=item C<ALT_DIGITS>
1172
1173Currently this gives the same results as Linux does.
1174Send email to L<mailto:perlbug@perl.org> if you have examples of it needing
1175to work differently.
1176
1177=item C<ERA_D_FMT>
1178
1179=item C<ERA_T_FMT>
1180
1181=item C<ERA_D_T_FMT>
1182
1183=item C<T_FMT_AMPM>
1184
1185These are derived by using C<strftime()>, and not all versions of that function
1186know about them. C<""> is returned for these on such systems.
1187
1188=back
1189
1190When using C<Perl_langinfo> on systems that don't have a native
1191C<nl_langinfo()>, you must
1192
1193 #include "perl_langinfo.h"
1194
1195before the C<perl.h> C<#include>. You can replace your C<langinfo.h>
1196C<#include> with this one. (Doing it this way keeps out the symbols that plain
1197C<langinfo.h> imports into the namespace for code that doesn't need it.)
1198
1199You also should not use the bare C<langinfo.h> item names, but should preface
1200them with C<PERL_>, so use C<PERL_RADIXCHAR> instead of plain C<RADIXCHAR>.
1201The C<PERL_I<foo>> versions will also work for this function on systems that do
1202have a native C<nl_langinfo>.
1203
1204=item *
1205
1206It is thread-friendly, returning its result in a buffer that won't be
1207overwritten by another thread, so you don't have to code for that possibility.
1208The buffer can be overwritten by the next call to C<nl_langinfo> or
1209C<Perl_langinfo> in the same thread.
1210
1211=item *
1212
7d4bcc4a 1213ª It returns S<C<const char *>>, whereas plain C<nl_langinfo()> returns S<C<char
f7416781
KW
1214*>>, but you are (only by documentation) forbidden to write into the buffer.
1215By declaring this C<const>, the compiler enforces this restriction. The extra
1216C<const> is why this isn't an unequivocal drop-in replacement for
1217C<nl_langinfo>.
1218
1219=back
1220
1221The original impetus for C<Perl_langinfo()> was so that code that needs to
1222find out the current currency symbol, floating point radix character, or digit
1223grouping separator can use, on all systems, the simpler and more
1224thread-friendly C<nl_langinfo> API instead of C<L<localeconv(3)>> which is a
1225pain to make thread-friendly. For other fields returned by C<localeconv>, it
1226is better to use the methods given in L<perlcall> to call
1227L<C<POSIX::localeconv()>|POSIX/localeconv>, which is thread-friendly.
1228
1229=cut
1230
1231*/
1232
1233const char *
1234#ifdef HAS_NL_LANGINFO
1235Perl_langinfo(const nl_item item)
1236#else
1237Perl_langinfo(const int item)
1238#endif
1239{
f61748ac
KW
1240 return my_nl_langinfo(item, TRUE);
1241}
1242
1243const char *
1244#ifdef HAS_NL_LANGINFO
1245S_my_nl_langinfo(const nl_item item, bool toggle)
1246#else
1247S_my_nl_langinfo(const int item, bool toggle)
1248#endif
1249{
ae74815b 1250 dTHX;
f7416781 1251
ab340fff
KW
1252#if defined(HAS_NL_LANGINFO) /* nl_langinfo() is available. */
1253#if ! defined(HAS_POSIX_2008_LOCALE)
f7416781 1254
ab340fff 1255 /* Here, use plain nl_langinfo(), switching to the underlying LC_NUMERIC
ae74815b
KW
1256 * for those items dependent on it. This must be copied to a buffer before
1257 * switching back, as some systems destroy the buffer when setlocale() is
1258 * called */
f7416781
KW
1259
1260 LOCALE_LOCK;
1261
1262 if (toggle) {
1263 if (item == PERL_RADIXCHAR || item == PERL_THOUSEP) {
837ce802 1264 do_setlocale_c(LC_NUMERIC, PL_numeric_name);
f7416781
KW
1265 }
1266 else {
1267 toggle = FALSE;
1268 }
1269 }
1270
1271 save_to_buffer(nl_langinfo(item), &PL_langinfo_buf, &PL_langinfo_bufsize, 0);
1272
1273 if (toggle) {
837ce802 1274 do_setlocale_c(LC_NUMERIC, "C");
f7416781
KW
1275 }
1276
1277 LOCALE_UNLOCK;
1278
1279 return PL_langinfo_buf;
1280
ab340fff
KW
1281# else /* Use nl_langinfo_l(), avoiding both a mutex and changing the locale */
1282
1283 bool do_free = FALSE;
1284 locale_t cur = uselocale((locale_t) 0);
1285
1286 if (cur == LC_GLOBAL_LOCALE) {
1287 cur = duplocale(LC_GLOBAL_LOCALE);
1288 do_free = TRUE;
1289 }
1290
1291 if ( toggle
1292 && (item == PERL_RADIXCHAR || item == PERL_THOUSEP))
1293 {
1294 cur = newlocale(LC_NUMERIC_MASK, PL_numeric_name, cur);
1295 do_free = TRUE;
1296 }
1297
1298 save_to_buffer(nl_langinfo_l(item, cur),
1299 &PL_langinfo_buf, &PL_langinfo_bufsize, 0);
1300 if (do_free) {
1301 freelocale(cur);
1302 }
1303
1304 return PL_langinfo_buf;
1305
1306# endif
f7416781 1307#else /* Below, emulate nl_langinfo as best we can */
f7416781
KW
1308# ifdef HAS_LOCALECONV
1309
1310 const struct lconv* lc;
1311
1312# endif
1313# ifdef HAS_STRFTIME
1314
1315 struct tm tm;
1316 bool return_format = FALSE; /* Return the %format, not the value */
1317 const char * format;
1318
1319# endif
1320
1321 /* We copy the results to a per-thread buffer, even if not multi-threaded.
1322 * This is in part to simplify this code, and partly because we need a
1323 * buffer anyway for strftime(), and partly because a call of localeconv()
1324 * could otherwise wipe out the buffer, and the programmer would not be
1325 * expecting this, as this is a nl_langinfo() substitute after all, so s/he
1326 * might be thinking their localeconv() is safe until another localeconv()
1327 * call. */
1328
1329 switch (item) {
1330 Size_t len;
1331 const char * retval;
1332
1333 /* These 2 are unimplemented */
1334 case PERL_CODESET:
1335 case PERL_ERA: /* For use with strftime() %E modifier */
1336
1337 default:
1338 return "";
1339
1340 /* We use only an English set, since we don't know any more */
1341 case PERL_YESEXPR: return "^[+1yY]";
1342 case PERL_NOEXPR: return "^[-0nN]";
1343
1344# ifdef HAS_LOCALECONV
1345
1346 case PERL_CRNCYSTR:
1347
1348 LOCALE_LOCK;
1349
1350 lc = localeconv();
1351 if (! lc || ! lc->currency_symbol || strEQ("", lc->currency_symbol))
1352 {
1353 LOCALE_UNLOCK;
1354 return "";
1355 }
1356
1357 /* Leave the first spot empty to be filled in below */
1358 save_to_buffer(lc->currency_symbol, &PL_langinfo_buf,
1359 &PL_langinfo_bufsize, 1);
1360 if (lc->mon_decimal_point && strEQ(lc->mon_decimal_point, ""))
1361 { /* khw couldn't figure out how the localedef specifications
1362 would show that the $ should replace the radix; this is
1363 just a guess as to how it might work.*/
1364 *PL_langinfo_buf = '.';
1365 }
1366 else if (lc->p_cs_precedes) {
1367 *PL_langinfo_buf = '-';
1368 }
1369 else {
1370 *PL_langinfo_buf = '+';
1371 }
1372
1373 LOCALE_UNLOCK;
1374 break;
1375
1376 case PERL_RADIXCHAR:
1377 case PERL_THOUSEP:
1378
1379 LOCALE_LOCK;
1380
1381 if (toggle) {
837ce802 1382 do_setlocale_c(LC_NUMERIC, PL_numeric_name);
f7416781
KW
1383 }
1384
1385 lc = localeconv();
1386 if (! lc) {
1387 retval = "";
1388 }
1389 else switch (item) {
1390 case PERL_RADIXCHAR:
1391 if (! lc->decimal_point) {
1392 retval = "";
1393 }
1394 else {
1395 retval = lc->decimal_point;
1396 }
1397 break;
1398
1399 case PERL_THOUSEP:
1400 if (! lc->thousands_sep || strEQ("", lc->thousands_sep)) {
1401 retval = "";
1402 }
1403 else {
1404 retval = lc->thousands_sep;
1405 }
1406 break;
1407
1408 default:
1409 LOCALE_UNLOCK;
1410 Perl_croak(aTHX_ "panic: %s: %d: switch case: %d problem",
1411 __FILE__, __LINE__, item);
1412 }
1413
1414 save_to_buffer(retval, &PL_langinfo_buf, &PL_langinfo_bufsize, 0);
1415
1416 if (toggle) {
837ce802 1417 do_setlocale_c(LC_NUMERIC, "C");
f7416781
KW
1418 }
1419
1420 LOCALE_UNLOCK;
1421
1422 break;
1423
1424# endif
1425# ifdef HAS_STRFTIME
1426
1427 /* These are defined by C89, so we assume that strftime supports them,
1428 * and so are returned unconditionally; they may not be what the locale
1429 * actually says, but should give good enough results for someone using
1430 * them as formats (as opposed to trying to parse them to figure out
7d4bcc4a 1431 * what the locale says). The other format items are actually tested to
f7416781
KW
1432 * verify they work on the platform */
1433 case PERL_D_FMT: return "%x";
1434 case PERL_T_FMT: return "%X";
1435 case PERL_D_T_FMT: return "%c";
1436
1437 /* These formats are only available in later strfmtime's */
1438 case PERL_ERA_D_FMT: case PERL_ERA_T_FMT: case PERL_ERA_D_T_FMT:
1439 case PERL_T_FMT_AMPM:
1440
1441 /* The rest can be gotten from most versions of strftime(). */
1442 case PERL_ABDAY_1: case PERL_ABDAY_2: case PERL_ABDAY_3:
1443 case PERL_ABDAY_4: case PERL_ABDAY_5: case PERL_ABDAY_6:
1444 case PERL_ABDAY_7:
1445 case PERL_ALT_DIGITS:
1446 case PERL_AM_STR: case PERL_PM_STR:
1447 case PERL_ABMON_1: case PERL_ABMON_2: case PERL_ABMON_3:
1448 case PERL_ABMON_4: case PERL_ABMON_5: case PERL_ABMON_6:
1449 case PERL_ABMON_7: case PERL_ABMON_8: case PERL_ABMON_9:
1450 case PERL_ABMON_10: case PERL_ABMON_11: case PERL_ABMON_12:
1451 case PERL_DAY_1: case PERL_DAY_2: case PERL_DAY_3: case PERL_DAY_4:
1452 case PERL_DAY_5: case PERL_DAY_6: case PERL_DAY_7:
1453 case PERL_MON_1: case PERL_MON_2: case PERL_MON_3: case PERL_MON_4:
1454 case PERL_MON_5: case PERL_MON_6: case PERL_MON_7: case PERL_MON_8:
1455 case PERL_MON_9: case PERL_MON_10: case PERL_MON_11: case PERL_MON_12:
1456
1457 LOCALE_LOCK;
1458
1459 init_tm(&tm); /* Precaution against core dumps */
1460 tm.tm_sec = 30;
1461 tm.tm_min = 30;
1462 tm.tm_hour = 6;
1463 tm.tm_year = 2017 - 1900;
1464 tm.tm_wday = 0;
1465 tm.tm_mon = 0;
1466 switch (item) {
1467 default:
1468 LOCALE_UNLOCK;
1469 Perl_croak(aTHX_ "panic: %s: %d: switch case: %d problem",
1470 __FILE__, __LINE__, item);
1471 NOT_REACHED; /* NOTREACHED */
1472
1473 case PERL_PM_STR: tm.tm_hour = 18;
1474 case PERL_AM_STR:
1475 format = "%p";
1476 break;
1477
1478 case PERL_ABDAY_7: tm.tm_wday++;
1479 case PERL_ABDAY_6: tm.tm_wday++;
1480 case PERL_ABDAY_5: tm.tm_wday++;
1481 case PERL_ABDAY_4: tm.tm_wday++;
1482 case PERL_ABDAY_3: tm.tm_wday++;
1483 case PERL_ABDAY_2: tm.tm_wday++;
1484 case PERL_ABDAY_1:
1485 format = "%a";
1486 break;
1487
1488 case PERL_DAY_7: tm.tm_wday++;
1489 case PERL_DAY_6: tm.tm_wday++;
1490 case PERL_DAY_5: tm.tm_wday++;
1491 case PERL_DAY_4: tm.tm_wday++;
1492 case PERL_DAY_3: tm.tm_wday++;
1493 case PERL_DAY_2: tm.tm_wday++;
1494 case PERL_DAY_1:
1495 format = "%A";
1496 break;
1497
1498 case PERL_ABMON_12: tm.tm_mon++;
1499 case PERL_ABMON_11: tm.tm_mon++;
1500 case PERL_ABMON_10: tm.tm_mon++;
1501 case PERL_ABMON_9: tm.tm_mon++;
1502 case PERL_ABMON_8: tm.tm_mon++;
1503 case PERL_ABMON_7: tm.tm_mon++;
1504 case PERL_ABMON_6: tm.tm_mon++;
1505 case PERL_ABMON_5: tm.tm_mon++;
1506 case PERL_ABMON_4: tm.tm_mon++;
1507 case PERL_ABMON_3: tm.tm_mon++;
1508 case PERL_ABMON_2: tm.tm_mon++;
1509 case PERL_ABMON_1:
1510 format = "%b";
1511 break;
1512
1513 case PERL_MON_12: tm.tm_mon++;
1514 case PERL_MON_11: tm.tm_mon++;
1515 case PERL_MON_10: tm.tm_mon++;
1516 case PERL_MON_9: tm.tm_mon++;
1517 case PERL_MON_8: tm.tm_mon++;
1518 case PERL_MON_7: tm.tm_mon++;
1519 case PERL_MON_6: tm.tm_mon++;
1520 case PERL_MON_5: tm.tm_mon++;
1521 case PERL_MON_4: tm.tm_mon++;
1522 case PERL_MON_3: tm.tm_mon++;
1523 case PERL_MON_2: tm.tm_mon++;
1524 case PERL_MON_1:
1525 format = "%B";
1526 break;
1527
1528 case PERL_T_FMT_AMPM:
1529 format = "%r";
1530 return_format = TRUE;
1531 break;
1532
1533 case PERL_ERA_D_FMT:
1534 format = "%Ex";
1535 return_format = TRUE;
1536 break;
1537
1538 case PERL_ERA_T_FMT:
1539 format = "%EX";
1540 return_format = TRUE;
1541 break;
1542
1543 case PERL_ERA_D_T_FMT:
1544 format = "%Ec";
1545 return_format = TRUE;
1546 break;
1547
1548 case PERL_ALT_DIGITS:
1549 tm.tm_wday = 0;
1550 format = "%Ow"; /* Find the alternate digit for 0 */
1551 break;
1552 }
1553
1554 /* We can't use my_strftime() because it doesn't look at tm_wday */
1555 while (0 == strftime(PL_langinfo_buf, PL_langinfo_bufsize,
1556 format, &tm))
1557 {
1558 /* A zero return means one of:
1559 * a) there wasn't enough space in PL_langinfo_buf
1560 * b) the format, like a plain %p, returns empty
1561 * c) it was an illegal format, though some implementations of
1562 * strftime will just return the illegal format as a plain
1563 * character sequence.
1564 *
1565 * To quickly test for case 'b)', try again but precede the
1566 * format with a plain character. If that result is still
1567 * empty, the problem is either 'a)' or 'c)' */
1568
1569 Size_t format_size = strlen(format) + 1;
1570 Size_t mod_size = format_size + 1;
1571 char * mod_format;
1572 char * temp_result;
1573
1574 Newx(mod_format, mod_size, char);
1575 Newx(temp_result, PL_langinfo_bufsize, char);
1576 *mod_format = '\a';
1577 my_strlcpy(mod_format + 1, format, mod_size);
1578 len = strftime(temp_result,
1579 PL_langinfo_bufsize,
1580 mod_format, &tm);
1581 Safefree(mod_format);
1582 Safefree(temp_result);
1583
1584 /* If 'len' is non-zero, it means that we had a case like %p
1585 * which means the current locale doesn't use a.m. or p.m., and
1586 * that is valid */
1587 if (len == 0) {
1588
1589 /* Here, still didn't work. If we get well beyond a
1590 * reasonable size, bail out to prevent an infinite loop. */
1591
1592 if (PL_langinfo_bufsize > 100 * format_size) {
1593 *PL_langinfo_buf = '\0';
1594 }
1595 else { /* Double the buffer size to retry; Add 1 in case
1596 original was 0, so we aren't stuck at 0. */
1597 PL_langinfo_bufsize *= 2;
1598 PL_langinfo_bufsize++;
1599 Renew(PL_langinfo_buf, PL_langinfo_bufsize, char);
1600 continue;
1601 }
1602 }
1603
1604 break;
1605 }
1606
1607 /* Here, we got a result.
1608 *
1609 * If the item is 'ALT_DIGITS', PL_langinfo_buf contains the
1610 * alternate format for wday 0. If the value is the same as the
1611 * normal 0, there isn't an alternate, so clear the buffer. */
1612 if ( item == PERL_ALT_DIGITS
1613 && strEQ(PL_langinfo_buf, "0"))
1614 {
1615 *PL_langinfo_buf = '\0';
1616 }
1617
1618 /* ALT_DIGITS is problematic. Experiments on it showed that
1619 * strftime() did not always work properly when going from alt-9 to
1620 * alt-10. Only a few locales have this item defined, and in all
1621 * of them on Linux that khw was able to find, nl_langinfo() merely
1622 * returned the alt-0 character, possibly doubled. Most Unicode
1623 * digits are in blocks of 10 consecutive code points, so that is
1624 * sufficient information for those scripts, as we can infer alt-1,
1625 * alt-2, .... But for a Japanese locale, a CJK ideographic 0 is
1626 * returned, and the CJK digits are not in code point order, so you
1627 * can't really infer anything. The localedef for this locale did
1628 * specify the succeeding digits, so that strftime() works properly
1629 * on them, without needing to infer anything. But the
1630 * nl_langinfo() return did not give sufficient information for the
1631 * caller to understand what's going on. So until there is
1632 * evidence that it should work differently, this returns the alt-0
1633 * string for ALT_DIGITS.
1634 *
1635 * wday was chosen because its range is all a single digit. Things
1636 * like tm_sec have two digits as the minimum: '00' */
1637
1638 LOCALE_UNLOCK;
1639
1640 /* If to return the format, not the value, overwrite the buffer
1641 * with it. But some strftime()s will keep the original format if
1642 * illegal, so change those to "" */
1643 if (return_format) {
1644 if (strEQ(PL_langinfo_buf, format)) {
1645 *PL_langinfo_buf = '\0';
1646 }
1647 else {
1648 save_to_buffer(format, &PL_langinfo_buf,
1649 &PL_langinfo_bufsize, 0);
1650 }
1651 }
1652
1653 break;
1654
1655# endif
1656
1657 }
1658
1659 return PL_langinfo_buf;
1660
1661#endif
1662
a4f00dcc 1663}
b385bb4d 1664
98994639
HS
1665/*
1666 * Initialize locale awareness.
1667 */
1668int
1669Perl_init_i18nl10n(pTHX_ int printwarn)
1670{
0e92a118
KW
1671 /* printwarn is
1672 *
1673 * 0 if not to output warning when setup locale is bad
1674 * 1 if to output warning based on value of PERL_BADLANG
1675 * >1 if to output regardless of PERL_BADLANG
1676 *
1677 * returns
98994639 1678 * 1 = set ok or not applicable,
0e92a118
KW
1679 * 0 = fallback to a locale of lower priority
1680 * -1 = fallback to all locales failed, not even to the C locale
6b058d42
KW
1681 *
1682 * Under -DDEBUGGING, if the environment variable PERL_DEBUG_LOCALE_INIT is
1683 * set, debugging information is output.
1684 *
1685 * This looks more complicated than it is, mainly due to the #ifdefs.
1686 *
1687 * We try to set LC_ALL to the value determined by the environment. If
1688 * there is no LC_ALL on this platform, we try the individual categories we
1689 * know about. If this works, we are done.
1690 *
1691 * But if it doesn't work, we have to do something else. We search the
1692 * environment variables ourselves instead of relying on the system to do
1693 * it. We look at, in order, LC_ALL, LANG, a system default locale (if we
1694 * think there is one), and the ultimate fallback "C". This is all done in
1695 * the same loop as above to avoid duplicating code, but it makes things
7d4bcc4a
KW
1696 * more complex. The 'trial_locales' array is initialized with just one
1697 * element; it causes the behavior described in the paragraph above this to
1698 * happen. If that fails, we add elements to 'trial_locales', and do extra
1699 * loop iterations to cause the behavior described in this paragraph.
6b058d42
KW
1700 *
1701 * On Ultrix, the locale MUST come from the environment, so there is
1702 * preliminary code to set it. I (khw) am not sure that it is necessary,
1703 * and that this couldn't be folded into the loop, but barring any real
1704 * platforms to test on, it's staying as-is
1705 *
1706 * A slight complication is that in embedded Perls, the locale may already
1707 * be set-up, and we don't want to get it from the normal environment
1708 * variables. This is handled by having a special environment variable
1709 * indicate we're in this situation. We simply set setlocale's 2nd
1710 * parameter to be a NULL instead of "". That indicates to setlocale that
1711 * it is not to change anything, but to return the current value,
1712 * effectively initializing perl's db to what the locale already is.
1713 *
1714 * We play the same trick with NULL if a LC_ALL succeeds. We call
1715 * setlocale() on the individual categores with NULL to get their existing
1716 * values for our db, instead of trying to change them.
1717 * */
98994639 1718
0e92a118
KW
1719 int ok = 1;
1720
7d4bcc4a
KW
1721#ifndef USE_LOCALE
1722
1723 PERL_UNUSED_ARG(printwarn);
1724
1725#else /* USE_LOCALE */
1726# ifdef USE_LOCALE_CTYPE
1727
98994639 1728 char *curctype = NULL;
7d4bcc4a
KW
1729
1730# endif /* USE_LOCALE_CTYPE */
1731# ifdef USE_LOCALE_COLLATE
1732
98994639 1733 char *curcoll = NULL;
7d4bcc4a
KW
1734
1735# endif /* USE_LOCALE_COLLATE */
1736# ifdef USE_LOCALE_NUMERIC
1737
98994639 1738 char *curnum = NULL;
7d4bcc4a
KW
1739
1740# endif /* USE_LOCALE_NUMERIC */
1741# ifdef __GLIBC__
1742
175c4cf9 1743 const char * const language = savepv(PerlEnv_getenv("LANGUAGE"));
7d4bcc4a
KW
1744
1745# endif
65ebb059 1746
ccd65d51
KW
1747 /* NULL uses the existing already set up locale */
1748 const char * const setlocale_init = (PerlEnv_getenv("PERL_SKIP_LOCALE_INIT"))
1749 ? NULL
1750 : "";
c3fcd832
KW
1751 const char* trial_locales[5]; /* 5 = 1 each for "", LC_ALL, LANG, "", C */
1752 unsigned int trial_locales_count;
175c4cf9
KW
1753 const char * const lc_all = savepv(PerlEnv_getenv("LC_ALL"));
1754 const char * const lang = savepv(PerlEnv_getenv("LANG"));
98994639 1755 bool setlocale_failure = FALSE;
65ebb059 1756 unsigned int i;
175c4cf9
KW
1757
1758 /* A later getenv() could zap this, so only use here */
1759 const char * const bad_lang_use_once = PerlEnv_getenv("PERL_BADLANG");
1760
1761 const bool locwarn = (printwarn > 1
1762 || (printwarn
1763 && (! bad_lang_use_once
22ff3130
HS
1764 || (
1765 /* disallow with "" or "0" */
1766 *bad_lang_use_once
1767 && strNE("0", bad_lang_use_once)))));
0e92a118 1768 bool done = FALSE;
5d1187d1
KW
1769 char * sl_result; /* return from setlocale() */
1770 char * locale_param;
7d4bcc4a
KW
1771
1772# ifdef WIN32
1773
6bce99ee
JH
1774 /* In some systems you can find out the system default locale
1775 * and use that as the fallback locale. */
7d4bcc4a
KW
1776# define SYSTEM_DEFAULT_LOCALE
1777# endif
1778# ifdef SYSTEM_DEFAULT_LOCALE
1779
65ebb059 1780 const char *system_default_locale = NULL;
98994639 1781
7d4bcc4a
KW
1782# endif
1783# ifdef DEBUGGING
1784
8298454c 1785 DEBUG_INITIALIZATION_set(cBOOL(PerlEnv_getenv("PERL_DEBUG_LOCALE_INIT")));
7d4bcc4a
KW
1786
1787# define DEBUG_LOCALE_INIT(category, locale, result) \
2fcc0ca9
KW
1788 STMT_START { \
1789 if (debug_initialization) { \
1790 PerlIO_printf(Perl_debug_log, \
1791 "%s:%d: %s\n", \
1792 __FILE__, __LINE__, \
a4f00dcc 1793 setlocale_debug_string(category, \
2fcc0ca9
KW
1794 locale, \
1795 result)); \
1796 } \
1797 } STMT_END
2fcc0ca9 1798
7d4bcc4a
KW
1799# else
1800# define DEBUG_LOCALE_INIT(a,b,c)
1801# endif
1802
1803# ifndef LOCALE_ENVIRON_REQUIRED
1804
0e92a118 1805 PERL_UNUSED_VAR(done);
5d1187d1 1806 PERL_UNUSED_VAR(locale_param);
7d4bcc4a
KW
1807
1808# else
98994639
HS
1809
1810 /*
1811 * Ultrix setlocale(..., "") fails if there are no environment
1812 * variables from which to get a locale name.
1813 */
1814
7d4bcc4a
KW
1815# ifdef LC_ALL
1816
98994639 1817 if (lang) {
d2b24094 1818 sl_result = do_setlocale_c(LC_ALL, setlocale_init);
5d1187d1
KW
1819 DEBUG_LOCALE_INIT(LC_ALL, setlocale_init, sl_result);
1820 if (sl_result)
98994639
HS
1821 done = TRUE;
1822 else
1823 setlocale_failure = TRUE;
1824 }
5d1187d1 1825 if (! setlocale_failure) {
7d4bcc4a
KW
1826
1827# ifdef USE_LOCALE_CTYPE
1828
5d1187d1
KW
1829 locale_param = (! done && (lang || PerlEnv_getenv("LC_CTYPE")))
1830 ? setlocale_init
1831 : NULL;
d2b24094 1832 curctype = do_setlocale_c(LC_CTYPE, locale_param);
5d1187d1
KW
1833 DEBUG_LOCALE_INIT(LC_CTYPE, locale_param, sl_result);
1834 if (! curctype)
98994639
HS
1835 setlocale_failure = TRUE;
1836 else
1837 curctype = savepv(curctype);
7d4bcc4a
KW
1838
1839# endif /* USE_LOCALE_CTYPE */
1840# ifdef USE_LOCALE_COLLATE
1841
5d1187d1
KW
1842 locale_param = (! done && (lang || PerlEnv_getenv("LC_COLLATE")))
1843 ? setlocale_init
1844 : NULL;
d2b24094 1845 curcoll = do_setlocale_c(LC_COLLATE, locale_param);
5d1187d1
KW
1846 DEBUG_LOCALE_INIT(LC_COLLATE, locale_param, sl_result);
1847 if (! curcoll)
98994639
HS
1848 setlocale_failure = TRUE;
1849 else
1850 curcoll = savepv(curcoll);
7d4bcc4a
KW
1851
1852# endif /* USE_LOCALE_COLLATE */
1853# ifdef USE_LOCALE_NUMERIC
1854
5d1187d1
KW
1855 locale_param = (! done && (lang || PerlEnv_getenv("LC_NUMERIC")))
1856 ? setlocale_init
1857 : NULL;
d2b24094 1858 curnum = do_setlocale_c(LC_NUMERIC, locale_param);
5d1187d1
KW
1859 DEBUG_LOCALE_INIT(LC_NUMERIC, locale_param, sl_result);
1860 if (! curnum)
98994639
HS
1861 setlocale_failure = TRUE;
1862 else
1863 curnum = savepv(curnum);
7d4bcc4a
KW
1864
1865# endif /* USE_LOCALE_NUMERIC */
1866# ifdef USE_LOCALE_MESSAGES
1867
5d1187d1
KW
1868 locale_param = (! done && (lang || PerlEnv_getenv("LC_MESSAGES")))
1869 ? setlocale_init
1870 : NULL;
d2b24094 1871 sl_result = do_setlocale_c(LC_MESSAGES, locale_param);
5d1187d1 1872 DEBUG_LOCALE_INIT(LC_MESSAGES, locale_param, sl_result);
9f42613c 1873 if (! sl_result) {
a782673d
KW
1874 setlocale_failure = TRUE;
1875 }
7d4bcc4a
KW
1876
1877# endif /* USE_LOCALE_MESSAGES */
1878# ifdef USE_LOCALE_MONETARY
1879
5d1187d1
KW
1880 locale_param = (! done && (lang || PerlEnv_getenv("LC_MONETARY")))
1881 ? setlocale_init
1882 : NULL;
d2b24094 1883 sl_result = do_setlocale_c(LC_MONETARY, locale_param);
5d1187d1
KW
1884 DEBUG_LOCALE_INIT(LC_MONETARY, locale_param, sl_result);
1885 if (! sl_result) {
c835d6be
KW
1886 setlocale_failure = TRUE;
1887 }
98994639 1888
7d4bcc4a 1889# endif /* USE_LOCALE_MONETARY */
98994639 1890
7d4bcc4a
KW
1891 }
1892
1893# endif /* LC_ALL */
1894# endif /* !LOCALE_ENVIRON_REQUIRED */
98994639 1895
65ebb059 1896 /* We try each locale in the list until we get one that works, or exhaust
20a240df
KW
1897 * the list. Normally the loop is executed just once. But if setting the
1898 * locale fails, inside the loop we add fallback trials to the array and so
1899 * will execute the loop multiple times */
c3fcd832
KW
1900 trial_locales[0] = setlocale_init;
1901 trial_locales_count = 1;
7d4bcc4a 1902
65ebb059
KW
1903 for (i= 0; i < trial_locales_count; i++) {
1904 const char * trial_locale = trial_locales[i];
1905
1906 if (i > 0) {
1907
1908 /* XXX This is to preserve old behavior for LOCALE_ENVIRON_REQUIRED
1909 * when i==0, but I (khw) don't think that behavior makes much
1910 * sense */
1911 setlocale_failure = FALSE;
1912
7d4bcc4a
KW
1913# ifdef SYSTEM_DEFAULT_LOCALE
1914# ifdef WIN32
1915
65ebb059
KW
1916 /* On Windows machines, an entry of "" after the 0th means to use
1917 * the system default locale, which we now proceed to get. */
1918 if (strEQ(trial_locale, "")) {
1919 unsigned int j;
1920
1921 /* Note that this may change the locale, but we are going to do
1922 * that anyway just below */
837ce802 1923 system_default_locale = do_setlocale_c(LC_ALL, "");
5d1187d1 1924 DEBUG_LOCALE_INIT(LC_ALL, "", system_default_locale);
65ebb059 1925
7d4bcc4a 1926 /* Skip if invalid or if it's already on the list of locales to
65ebb059
KW
1927 * try */
1928 if (! system_default_locale) {
1929 goto next_iteration;
1930 }
1931 for (j = 0; j < trial_locales_count; j++) {
1932 if (strEQ(system_default_locale, trial_locales[j])) {
1933 goto next_iteration;
1934 }
1935 }
1936
1937 trial_locale = system_default_locale;
1938 }
7d4bcc4a
KW
1939# endif /* WIN32 */
1940# endif /* SYSTEM_DEFAULT_LOCALE */
65ebb059
KW
1941 }
1942
7d4bcc4a
KW
1943# ifdef LC_ALL
1944
d2b24094 1945 sl_result = do_setlocale_c(LC_ALL, trial_locale);
5d1187d1
KW
1946 DEBUG_LOCALE_INIT(LC_ALL, trial_locale, sl_result);
1947 if (! sl_result) {
49c85077 1948 setlocale_failure = TRUE;
7cd8b568
KW
1949 }
1950 else {
1951 /* Since LC_ALL succeeded, it should have changed all the other
1952 * categories it can to its value; so we massage things so that the
1953 * setlocales below just return their category's current values.
1954 * This adequately handles the case in NetBSD where LC_COLLATE may
1955 * not be defined for a locale, and setting it individually will
7d4bcc4a 1956 * fail, whereas setting LC_ALL succeeds, leaving LC_COLLATE set to
7cd8b568
KW
1957 * the POSIX locale. */
1958 trial_locale = NULL;
1959 }
7d4bcc4a
KW
1960
1961# endif /* LC_ALL */
98994639 1962
49c85077 1963 if (!setlocale_failure) {
7d4bcc4a
KW
1964
1965# ifdef USE_LOCALE_CTYPE
1966
49c85077 1967 Safefree(curctype);
d2b24094 1968 curctype = do_setlocale_c(LC_CTYPE, trial_locale);
5d1187d1
KW
1969 DEBUG_LOCALE_INIT(LC_CTYPE, trial_locale, curctype);
1970 if (! curctype)
49c85077
KW
1971 setlocale_failure = TRUE;
1972 else
1973 curctype = savepv(curctype);
7d4bcc4a
KW
1974
1975# endif /* USE_LOCALE_CTYPE */
1976# ifdef USE_LOCALE_COLLATE
1977
49c85077 1978 Safefree(curcoll);
d2b24094 1979 curcoll = do_setlocale_c(LC_COLLATE, trial_locale);
5d1187d1
KW
1980 DEBUG_LOCALE_INIT(LC_COLLATE, trial_locale, curcoll);
1981 if (! curcoll)
49c85077
KW
1982 setlocale_failure = TRUE;
1983 else
1984 curcoll = savepv(curcoll);
7d4bcc4a
KW
1985
1986# endif /* USE_LOCALE_COLLATE */
1987# ifdef USE_LOCALE_NUMERIC
1988
49c85077 1989 Safefree(curnum);
d2b24094 1990 curnum = do_setlocale_c(LC_NUMERIC, trial_locale);
5d1187d1
KW
1991 DEBUG_LOCALE_INIT(LC_NUMERIC, trial_locale, curnum);
1992 if (! curnum)
49c85077
KW
1993 setlocale_failure = TRUE;
1994 else
1995 curnum = savepv(curnum);
7d4bcc4a
KW
1996
1997# endif /* USE_LOCALE_NUMERIC */
1998# ifdef USE_LOCALE_MESSAGES
1999
d2b24094 2000 sl_result = do_setlocale_c(LC_MESSAGES, trial_locale);
5d1187d1
KW
2001 DEBUG_LOCALE_INIT(LC_MESSAGES, trial_locale, sl_result);
2002 if (! (sl_result))
a782673d 2003 setlocale_failure = TRUE;
7d4bcc4a
KW
2004
2005# endif /* USE_LOCALE_MESSAGES */
2006# ifdef USE_LOCALE_MONETARY
2007
d2b24094 2008 sl_result = do_setlocale_c(LC_MONETARY, trial_locale);
5d1187d1
KW
2009 DEBUG_LOCALE_INIT(LC_MONETARY, trial_locale, sl_result);
2010 if (! (sl_result))
c835d6be 2011 setlocale_failure = TRUE;
7d4bcc4a
KW
2012
2013# endif /* USE_LOCALE_MONETARY */
c835d6be 2014
49c85077
KW
2015 if (! setlocale_failure) { /* Success */
2016 break;
2017 }
65ebb059 2018 }
98994639 2019
49c85077
KW
2020 /* Here, something failed; will need to try a fallback. */
2021 ok = 0;
65ebb059 2022
49c85077
KW
2023 if (i == 0) {
2024 unsigned int j;
98994639 2025
65ebb059 2026 if (locwarn) { /* Output failure info only on the first one */
7d4bcc4a
KW
2027
2028# ifdef LC_ALL
98994639 2029
49c85077
KW
2030 PerlIO_printf(Perl_error_log,
2031 "perl: warning: Setting locale failed.\n");
98994639 2032
7d4bcc4a 2033# else /* !LC_ALL */
98994639 2034
49c85077
KW
2035 PerlIO_printf(Perl_error_log,
2036 "perl: warning: Setting locale failed for the categories:\n\t");
7d4bcc4a
KW
2037
2038# ifdef USE_LOCALE_CTYPE
2039
49c85077
KW
2040 if (! curctype)
2041 PerlIO_printf(Perl_error_log, "LC_CTYPE ");
7d4bcc4a
KW
2042
2043# endif /* USE_LOCALE_CTYPE */
2044# ifdef USE_LOCALE_COLLATE
49c85077
KW
2045 if (! curcoll)
2046 PerlIO_printf(Perl_error_log, "LC_COLLATE ");
7d4bcc4a
KW
2047
2048# endif /* USE_LOCALE_COLLATE */
2049# ifdef USE_LOCALE_NUMERIC
2050
49c85077
KW
2051 if (! curnum)
2052 PerlIO_printf(Perl_error_log, "LC_NUMERIC ");
7d4bcc4a
KW
2053
2054# endif /* USE_LOCALE_NUMERIC */
2055
a782673d 2056 PerlIO_printf(Perl_error_log, "and possibly others\n");
98994639 2057
7d4bcc4a 2058# endif /* LC_ALL */
98994639 2059
49c85077
KW
2060 PerlIO_printf(Perl_error_log,
2061 "perl: warning: Please check that your locale settings:\n");
98994639 2062
7d4bcc4a
KW
2063# ifdef __GLIBC__
2064
49c85077
KW
2065 PerlIO_printf(Perl_error_log,
2066 "\tLANGUAGE = %c%s%c,\n",
2067 language ? '"' : '(',
2068 language ? language : "unset",
2069 language ? '"' : ')');
7d4bcc4a 2070# endif
98994639 2071
49c85077
KW
2072 PerlIO_printf(Perl_error_log,
2073 "\tLC_ALL = %c%s%c,\n",
2074 lc_all ? '"' : '(',
2075 lc_all ? lc_all : "unset",
2076 lc_all ? '"' : ')');
98994639 2077
7d4bcc4a
KW
2078# if defined(USE_ENVIRON_ARRAY)
2079
49c85077 2080 {
cd999af9 2081 char **e;
d5e32b93
KW
2082
2083 /* Look through the environment for any variables of the
2084 * form qr/ ^ LC_ [A-Z]+ = /x, except LC_ALL which was
2085 * already handled above. These are assumed to be locale
2086 * settings. Output them and their values. */
cd999af9 2087 for (e = environ; *e; e++) {
d5e32b93
KW
2088 const STRLEN prefix_len = sizeof("LC_") - 1;
2089 STRLEN uppers_len;
2090
cd999af9 2091 if ( strBEGINs(*e, "LC_")
c8b388b0 2092 && ! strBEGINs(*e, "LC_ALL=")
d5e32b93
KW
2093 && (uppers_len = strspn(*e + prefix_len,
2094 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
2095 && ((*e)[prefix_len + uppers_len] == '='))
cd999af9
KW
2096 {
2097 PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
d5e32b93
KW
2098 (int) (prefix_len + uppers_len), *e,
2099 *e + prefix_len + uppers_len + 1);
cd999af9
KW
2100 }
2101 }
49c85077 2102 }
7d4bcc4a
KW
2103
2104# else
2105
49c85077
KW
2106 PerlIO_printf(Perl_error_log,
2107 "\t(possibly more locale environment variables)\n");
7d4bcc4a
KW
2108
2109# endif
98994639 2110
49c85077
KW
2111 PerlIO_printf(Perl_error_log,
2112 "\tLANG = %c%s%c\n",
2113 lang ? '"' : '(',
2114 lang ? lang : "unset",
2115 lang ? '"' : ')');
98994639 2116
49c85077
KW
2117 PerlIO_printf(Perl_error_log,
2118 " are supported and installed on your system.\n");
2119 }
98994639 2120
65ebb059 2121 /* Calculate what fallback locales to try. We have avoided this
f6bab5f6 2122 * until we have to, because failure is quite unlikely. This will
65ebb059
KW
2123 * usually change the upper bound of the loop we are in.
2124 *
2125 * Since the system's default way of setting the locale has not
2126 * found one that works, We use Perl's defined ordering: LC_ALL,
2127 * LANG, and the C locale. We don't try the same locale twice, so
2128 * don't add to the list if already there. (On POSIX systems, the
2129 * LC_ALL element will likely be a repeat of the 0th element "",
6b058d42
KW
2130 * but there's no harm done by doing it explicitly.
2131 *
2132 * Note that this tries the LC_ALL environment variable even on
2133 * systems which have no LC_ALL locale setting. This may or may
2134 * not have been originally intentional, but there's no real need
2135 * to change the behavior. */
65ebb059
KW
2136 if (lc_all) {
2137 for (j = 0; j < trial_locales_count; j++) {
2138 if (strEQ(lc_all, trial_locales[j])) {
2139 goto done_lc_all;
2140 }
2141 }
2142 trial_locales[trial_locales_count++] = lc_all;
2143 }
2144 done_lc_all:
98994639 2145
65ebb059
KW
2146 if (lang) {
2147 for (j = 0; j < trial_locales_count; j++) {
2148 if (strEQ(lang, trial_locales[j])) {
2149 goto done_lang;
2150 }
2151 }
2152 trial_locales[trial_locales_count++] = lang;
2153 }
2154 done_lang:
2155
7d4bcc4a
KW
2156# if defined(WIN32) && defined(LC_ALL)
2157
65ebb059
KW
2158 /* For Windows, we also try the system default locale before "C".
2159 * (If there exists a Windows without LC_ALL we skip this because
2160 * it gets too complicated. For those, the "C" is the next
2161 * fallback possibility). The "" is the same as the 0th element of
2162 * the array, but the code at the loop above knows to treat it
2163 * differently when not the 0th */
2164 trial_locales[trial_locales_count++] = "";
7d4bcc4a
KW
2165
2166# endif
65ebb059
KW
2167
2168 for (j = 0; j < trial_locales_count; j++) {
2169 if (strEQ("C", trial_locales[j])) {
2170 goto done_C;
2171 }
2172 }
2173 trial_locales[trial_locales_count++] = "C";
98994639 2174
65ebb059
KW
2175 done_C: ;
2176 } /* end of first time through the loop */
98994639 2177
7d4bcc4a
KW
2178# ifdef WIN32
2179
65ebb059 2180 next_iteration: ;
7d4bcc4a
KW
2181
2182# endif
65ebb059
KW
2183
2184 } /* end of looping through the trial locales */
2185
2186 if (ok < 1) { /* If we tried to fallback */
2187 const char* msg;
2188 if (! setlocale_failure) { /* fallback succeeded */
2189 msg = "Falling back to";
2190 }
2191 else { /* fallback failed */
98994639 2192
65ebb059
KW
2193 /* We dropped off the end of the loop, so have to decrement i to
2194 * get back to the value the last time through */
2195 i--;
98994639 2196
65ebb059
KW
2197 ok = -1;
2198 msg = "Failed to fall back to";
2199
2200 /* To continue, we should use whatever values we've got */
7d4bcc4a
KW
2201
2202# ifdef USE_LOCALE_CTYPE
2203
49c85077 2204 Safefree(curctype);
837ce802 2205 curctype = savepv(do_setlocale_c(LC_CTYPE, NULL));
5d1187d1 2206 DEBUG_LOCALE_INIT(LC_CTYPE, NULL, curctype);
7d4bcc4a
KW
2207
2208# endif /* USE_LOCALE_CTYPE */
2209# ifdef USE_LOCALE_COLLATE
2210
49c85077 2211 Safefree(curcoll);
837ce802 2212 curcoll = savepv(do_setlocale_c(LC_COLLATE, NULL));
5d1187d1 2213 DEBUG_LOCALE_INIT(LC_COLLATE, NULL, curcoll);
7d4bcc4a
KW
2214
2215# endif /* USE_LOCALE_COLLATE */
2216# ifdef USE_LOCALE_NUMERIC
2217
49c85077 2218 Safefree(curnum);
837ce802 2219 curnum = savepv(do_setlocale_c(LC_NUMERIC, NULL));
5d1187d1 2220 DEBUG_LOCALE_INIT(LC_NUMERIC, NULL, curnum);
7d4bcc4a
KW
2221
2222# endif /* USE_LOCALE_NUMERIC */
2223
65ebb059
KW
2224 }
2225
2226 if (locwarn) {
2227 const char * description;
2228 const char * name = "";
2229 if (strEQ(trial_locales[i], "C")) {
2230 description = "the standard locale";
2231 name = "C";
2232 }
7d4bcc4a
KW
2233
2234# ifdef SYSTEM_DEFAULT_LOCALE
2235
65ebb059
KW
2236 else if (strEQ(trial_locales[i], "")) {
2237 description = "the system default locale";
2238 if (system_default_locale) {
2239 name = system_default_locale;
2240 }
2241 }
7d4bcc4a
KW
2242
2243# endif /* SYSTEM_DEFAULT_LOCALE */
2244
65ebb059
KW
2245 else {
2246 description = "a fallback locale";
2247 name = trial_locales[i];
2248 }
2249 if (name && strNE(name, "")) {
2250 PerlIO_printf(Perl_error_log,
2251 "perl: warning: %s %s (\"%s\").\n", msg, description, name);
2252 }
2253 else {
2254 PerlIO_printf(Perl_error_log,
2255 "perl: warning: %s %s.\n", msg, description);
2256 }
2257 }
2258 } /* End of tried to fallback */
98994639 2259
7d4bcc4a
KW
2260# ifdef USE_LOCALE_CTYPE
2261
98994639 2262 new_ctype(curctype);
98994639 2263
7d4bcc4a
KW
2264# endif /* USE_LOCALE_CTYPE */
2265# ifdef USE_LOCALE_COLLATE
2266
98994639 2267 new_collate(curcoll);
98994639 2268
7d4bcc4a
KW
2269# endif /* USE_LOCALE_COLLATE */
2270# ifdef USE_LOCALE_NUMERIC
2271
98994639 2272 new_numeric(curnum);
b310b053 2273
7d4bcc4a
KW
2274# endif /* USE_LOCALE_NUMERIC */
2275# if defined(USE_PERLIO) && defined(USE_LOCALE_CTYPE)
2276
49c85077
KW
2277 /* Set PL_utf8locale to TRUE if using PerlIO _and_ the current LC_CTYPE
2278 * locale is UTF-8. If PL_utf8locale and PL_unicode (set by -C or by
2279 * $ENV{PERL_UNICODE}) are true, perl.c:S_parse_body() will turn on the
2280 * PerlIO :utf8 layer on STDIN, STDOUT, STDERR, _and_ the default open
2281 * discipline. */
c1284011 2282 PL_utf8locale = _is_cur_LC_category_utf8(LC_CTYPE);
49c85077 2283
a05d7ebb 2284 /* Set PL_unicode to $ENV{PERL_UNICODE} if using PerlIO.
fde18df1
JH
2285 This is an alternative to using the -C command line switch
2286 (the -C if present will override this). */
2287 {
dd374669 2288 const char *p = PerlEnv_getenv("PERL_UNICODE");
a05d7ebb 2289 PL_unicode = p ? parse_unicode_opts(&p) : 0;
5a22a2bb
NC
2290 if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
2291 PL_utf8cache = -1;
b310b053
JH
2292 }
2293
7d4bcc4a
KW
2294# endif
2295# ifdef USE_LOCALE_CTYPE
2296
43c5f42d 2297 Safefree(curctype);
7d4bcc4a
KW
2298
2299# endif /* USE_LOCALE_CTYPE */
2300# ifdef USE_LOCALE_COLLATE
2301
43c5f42d 2302 Safefree(curcoll);
7d4bcc4a
KW
2303
2304# endif /* USE_LOCALE_COLLATE */
2305# ifdef USE_LOCALE_NUMERIC
2306
43c5f42d 2307 Safefree(curnum);
8ef6e574 2308
7d4bcc4a
KW
2309# endif /* USE_LOCALE_NUMERIC */
2310
2311# ifdef __GLIBC__
2312
175c4cf9 2313 Safefree(language);
7d4bcc4a
KW
2314
2315# endif
175c4cf9
KW
2316
2317 Safefree(lc_all);
2318 Safefree(lang);
2319
e3305790 2320#endif /* USE_LOCALE */
2fcc0ca9 2321#ifdef DEBUGGING
7d4bcc4a 2322
2fcc0ca9 2323 /* So won't continue to output stuff */
27cdc72e 2324 DEBUG_INITIALIZATION_set(FALSE);
7d4bcc4a 2325
2fcc0ca9
KW
2326#endif
2327
98994639
HS
2328 return ok;
2329}
2330
98994639
HS
2331#ifdef USE_LOCALE_COLLATE
2332
a4a439fb 2333char *
a4a439fb
KW
2334Perl__mem_collxfrm(pTHX_ const char *input_string,
2335 STRLEN len, /* Length of 'input_string' */
2336 STRLEN *xlen, /* Set to length of returned string
2337 (not including the collation index
2338 prefix) */
2339 bool utf8 /* Is the input in UTF-8? */
6696cfa7 2340 )
98994639 2341{
a4a439fb
KW
2342
2343 /* _mem_collxfrm() is a bit like strxfrm() but with two important
2344 * differences. First, it handles embedded NULs. Second, it allocates a bit
2345 * more memory than needed for the transformed data itself. The real
55e5378d 2346 * transformed data begins at offset COLLXFRM_HDR_LEN. *xlen is set to
a4a439fb
KW
2347 * the length of that, and doesn't include the collation index size.
2348 * Please see sv_collxfrm() to see how this is used. */
2349
55e5378d
KW
2350#define COLLXFRM_HDR_LEN sizeof(PL_collation_ix)
2351
6696cfa7
KW
2352 char * s = (char *) input_string;
2353 STRLEN s_strlen = strlen(input_string);
79f120c8 2354 char *xbuf = NULL;
55e5378d 2355 STRLEN xAlloc; /* xalloc is a reserved word in VC */
17f41037 2356 STRLEN length_in_chars;
c664130f 2357 bool first_time = TRUE; /* Cleared after first loop iteration */
98994639 2358
a4a439fb
KW
2359 PERL_ARGS_ASSERT__MEM_COLLXFRM;
2360
2361 /* Must be NUL-terminated */
2362 assert(*(input_string + len) == '\0');
7918f24d 2363
79f120c8
KW
2364 /* If this locale has defective collation, skip */
2365 if (PL_collxfrm_base == 0 && PL_collxfrm_mult == 0) {
c7202dee
KW
2366 DEBUG_L(PerlIO_printf(Perl_debug_log,
2367 "_mem_collxfrm: locale's collation is defective\n"));
79f120c8
KW
2368 goto bad;
2369 }
2370
6696cfa7
KW
2371 /* Replace any embedded NULs with the control that sorts before any others.
2372 * This will give as good as possible results on strings that don't
2373 * otherwise contain that character, but otherwise there may be
2374 * less-than-perfect results with that character and NUL. This is
fdc080f3 2375 * unavoidable unless we replace strxfrm with our own implementation. */
fd43f63c
KW
2376 if (UNLIKELY(s_strlen < len)) { /* Only execute if there is an embedded
2377 NUL */
6696cfa7
KW
2378 char * e = s + len;
2379 char * sans_nuls;
fdc080f3 2380 STRLEN sans_nuls_len;
94762aa0 2381 int try_non_controls;
afc4976f
KW
2382 char this_replacement_char[] = "?\0"; /* Room for a two-byte string,
2383 making sure 2nd byte is NUL.
2384 */
2385 STRLEN this_replacement_len;
2386
1e4c9676
KW
2387 /* If we don't know what non-NUL control character sorts lowest for
2388 * this locale, find it */
f28f4d2a 2389 if (PL_strxfrm_NUL_replacement == '\0') {
6696cfa7 2390 int j;
afc4976f 2391 char * cur_min_x = NULL; /* The min_char's xfrm, (except it also
6696cfa7
KW
2392 includes the collation index
2393 prefixed. */
2394
91c0e2e0 2395 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "Looking to replace NUL\n"));
94762aa0
KW
2396
2397 /* Unlikely, but it may be that no control will work to replace
1e4c9676
KW
2398 * NUL, in which case we instead look for any character. Controls
2399 * are preferred because collation order is, in general, context
2400 * sensitive, with adjoining characters affecting the order, and
2401 * controls are less likely to have such interactions, allowing the
2402 * NUL-replacement to stand on its own. (Another way to look at it
2403 * is to imagine what would happen if the NUL were replaced by a
2404 * combining character; it wouldn't work out all that well.) */
94762aa0
KW
2405 for (try_non_controls = 0;
2406 try_non_controls < 2;
2407 try_non_controls++)
2408 {
d4ff9586
KW
2409 /* Look through all legal code points (NUL isn't) */
2410 for (j = 1; j < 256; j++) {
2411 char * x; /* j's xfrm plus collation index */
2412 STRLEN x_len; /* length of 'x' */
2413 STRLEN trial_len = 1;
736a4fed 2414 char cur_source[] = { '\0', '\0' };
d4ff9586 2415
736a4fed
KW
2416 /* Skip non-controls the first time through the loop. The
2417 * controls in a UTF-8 locale are the L1 ones */
afc4976f
KW
2418 if (! try_non_controls && (PL_in_utf8_COLLATE_locale)
2419 ? ! isCNTRL_L1(j)
2420 : ! isCNTRL_LC(j))
2421 {
d4ff9586 2422 continue;
6696cfa7 2423 }
6696cfa7 2424
736a4fed
KW
2425 /* Create a 1-char string of the current code point */
2426 cur_source[0] = (char) j;
2427
d4ff9586
KW
2428 /* Then transform it */
2429 x = _mem_collxfrm(cur_source, trial_len, &x_len,
afc4976f 2430 0 /* The string is not in UTF-8 */);
6696cfa7 2431
1e4c9676 2432 /* Ignore any character that didn't successfully transform.
d4ff9586
KW
2433 * */
2434 if (! x) {
2435 continue;
2436 }
6696cfa7 2437
d4ff9586
KW
2438 /* If this character's transformation is lower than
2439 * the current lowest, this one becomes the lowest */
2440 if ( cur_min_x == NULL
2441 || strLT(x + COLLXFRM_HDR_LEN,
2442 cur_min_x + COLLXFRM_HDR_LEN))
2443 {
f28f4d2a 2444 PL_strxfrm_NUL_replacement = j;
d4ff9586 2445 cur_min_x = x;
d4ff9586
KW
2446 }
2447 else {
2448 Safefree(x);
2449 }
1e4c9676 2450 } /* end of loop through all 255 characters */
6696cfa7 2451
1e4c9676 2452 /* Stop looking if found */
94762aa0
KW
2453 if (cur_min_x) {
2454 break;
2455 }
2456
2457 /* Unlikely, but possible, if there aren't any controls that
2458 * work in the locale, repeat the loop, looking for any
2459 * character that works */
2460 DEBUG_L(PerlIO_printf(Perl_debug_log,
2461 "_mem_collxfrm: No control worked. Trying non-controls\n"));
1e4c9676 2462 } /* End of loop to try first the controls, then any char */
6696cfa7 2463
94762aa0
KW
2464 if (! cur_min_x) {
2465 DEBUG_L(PerlIO_printf(Perl_debug_log,
2466 "_mem_collxfrm: Couldn't find any character to replace"
2467 " embedded NULs in locale %s with", PL_collation_name));
2468 goto bad;
58eebef2
KW
2469 }
2470
94762aa0
KW
2471 DEBUG_L(PerlIO_printf(Perl_debug_log,
2472 "_mem_collxfrm: Replacing embedded NULs in locale %s with "
f28f4d2a 2473 "0x%02X\n", PL_collation_name, PL_strxfrm_NUL_replacement));
94762aa0 2474
6696cfa7 2475 Safefree(cur_min_x);
1e4c9676 2476 } /* End of determining the character that is to replace NULs */
afc4976f
KW
2477
2478 /* If the replacement is variant under UTF-8, it must match the
2479 * UTF8-ness as the original */
f28f4d2a
KW
2480 if ( ! UVCHR_IS_INVARIANT(PL_strxfrm_NUL_replacement) && utf8) {
2481 this_replacement_char[0] =
2482 UTF8_EIGHT_BIT_HI(PL_strxfrm_NUL_replacement);
2483 this_replacement_char[1] =
2484 UTF8_EIGHT_BIT_LO(PL_strxfrm_NUL_replacement);
afc4976f
KW
2485 this_replacement_len = 2;
2486 }
2487 else {
f28f4d2a 2488 this_replacement_char[0] = PL_strxfrm_NUL_replacement;
afc4976f
KW
2489 /* this_replacement_char[1] = '\0' was done at initialization */
2490 this_replacement_len = 1;
6696cfa7
KW
2491 }
2492
2493 /* The worst case length for the replaced string would be if every
2494 * character in it is NUL. Multiply that by the length of each
2495 * replacement, and allow for a trailing NUL */
afc4976f 2496 sans_nuls_len = (len * this_replacement_len) + 1;
fdc080f3 2497 Newx(sans_nuls, sans_nuls_len, char);
6696cfa7
KW
2498 *sans_nuls = '\0';
2499
6696cfa7
KW
2500 /* Replace each NUL with the lowest collating control. Loop until have
2501 * exhausted all the NULs */
2502 while (s + s_strlen < e) {
6069d6c5 2503 my_strlcat(sans_nuls, s, sans_nuls_len);
6696cfa7
KW
2504
2505 /* Do the actual replacement */
6069d6c5 2506 my_strlcat(sans_nuls, this_replacement_char, sans_nuls_len);
6696cfa7
KW
2507
2508 /* Move past the input NUL */
2509 s += s_strlen + 1;
2510 s_strlen = strlen(s);
2511 }
2512
2513 /* And add anything that trails the final NUL */
6069d6c5 2514 my_strlcat(sans_nuls, s, sans_nuls_len);
6696cfa7
KW
2515
2516 /* Switch so below we transform this modified string */
2517 s = sans_nuls;
2518 len = strlen(s);
1e4c9676 2519 } /* End of replacing NULs */
6696cfa7 2520
a4a439fb
KW
2521 /* Make sure the UTF8ness of the string and locale match */
2522 if (utf8 != PL_in_utf8_COLLATE_locale) {
2523 const char * const t = s; /* Temporary so we can later find where the
2524 input was */
2525
2526 /* Here they don't match. Change the string's to be what the locale is
2527 * expecting */
2528
2529 if (! utf8) { /* locale is UTF-8, but input isn't; upgrade the input */
2530 s = (char *) bytes_to_utf8((const U8 *) s, &len);
2531 utf8 = TRUE;
2532 }
2533 else { /* locale is not UTF-8; but input is; downgrade the input */
2534
2535 s = (char *) bytes_from_utf8((const U8 *) s, &len, &utf8);
2536
2537 /* If the downgrade was successful we are done, but if the input
2538 * contains things that require UTF-8 to represent, have to do
2539 * damage control ... */
2540 if (UNLIKELY(utf8)) {
2541
2542 /* What we do is construct a non-UTF-8 string with
2543 * 1) the characters representable by a single byte converted
2544 * to be so (if necessary);
2545 * 2) and the rest converted to collate the same as the
2546 * highest collating representable character. That makes
2547 * them collate at the end. This is similar to how we
2548 * handle embedded NULs, but we use the highest collating
2549 * code point instead of the smallest. Like the NUL case,
2550 * this isn't perfect, but is the best we can reasonably
2551 * do. Every above-255 code point will sort the same as
2552 * the highest-sorting 0-255 code point. If that code
2553 * point can combine in a sequence with some other code
2554 * points for weight calculations, us changing something to
2555 * be it can adversely affect the results. But in most
2556 * cases, it should work reasonably. And note that this is
2557 * really an illegal situation: using code points above 255
2558 * on a locale where only 0-255 are valid. If two strings
2559 * sort entirely equal, then the sort order for the
2560 * above-255 code points will be in code point order. */
2561
2562 utf8 = FALSE;
2563
2564 /* If we haven't calculated the code point with the maximum
2565 * collating order for this locale, do so now */
2566 if (! PL_strxfrm_max_cp) {
2567 int j;
2568
2569 /* The current transformed string that collates the
2570 * highest (except it also includes the prefixed collation
2571 * index. */
2572 char * cur_max_x = NULL;
2573
2574 /* Look through all legal code points (NUL isn't) */
2575 for (j = 1; j < 256; j++) {
2576 char * x;
2577 STRLEN x_len;
736a4fed 2578 char cur_source[] = { '\0', '\0' };
a4a439fb 2579
736a4fed
KW
2580 /* Create a 1-char string of the current code point */
2581 cur_source[0] = (char) j;
a4a439fb
KW
2582
2583 /* Then transform it */
2584 x = _mem_collxfrm(cur_source, 1, &x_len, FALSE);
2585
2586 /* If something went wrong (which it shouldn't), just
2587 * ignore this code point */
94762aa0 2588 if (! x) {
a4a439fb
KW
2589 continue;
2590 }
2591
2592 /* If this character's transformation is higher than
2593 * the current highest, this one becomes the highest */
2594 if ( cur_max_x == NULL
55e5378d
KW
2595 || strGT(x + COLLXFRM_HDR_LEN,
2596 cur_max_x + COLLXFRM_HDR_LEN))
a4a439fb
KW
2597 {
2598 PL_strxfrm_max_cp = j;
2599 cur_max_x = x;
2600 }
2601 else {
2602 Safefree(x);
2603 }
2604 }
2605
94762aa0
KW
2606 if (! cur_max_x) {
2607 DEBUG_L(PerlIO_printf(Perl_debug_log,
2608 "_mem_collxfrm: Couldn't find any character to"
2609 " replace above-Latin1 chars in locale %s with",
2610 PL_collation_name));
2611 goto bad;
2612 }
2613
58eebef2
KW
2614 DEBUG_L(PerlIO_printf(Perl_debug_log,
2615 "_mem_collxfrm: highest 1-byte collating character"
2616 " in locale %s is 0x%02X\n",
2617 PL_collation_name,
2618 PL_strxfrm_max_cp));
58eebef2 2619
a4a439fb
KW
2620 Safefree(cur_max_x);
2621 }
2622
2623 /* Here we know which legal code point collates the highest.
2624 * We are ready to construct the non-UTF-8 string. The length
2625 * will be at least 1 byte smaller than the input string
2626 * (because we changed at least one 2-byte character into a
2627 * single byte), but that is eaten up by the trailing NUL */
2628 Newx(s, len, char);
2629
2630 {
2631 STRLEN i;
2632 STRLEN d= 0;
042d9e50 2633 char * e = (char *) t + len;
a4a439fb
KW
2634
2635 for (i = 0; i < len; i+= UTF8SKIP(t + i)) {
2636 U8 cur_char = t[i];
2637 if (UTF8_IS_INVARIANT(cur_char)) {
2638 s[d++] = cur_char;
2639 }
042d9e50 2640 else if (UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(t + i, e)) {
a4a439fb
KW
2641 s[d++] = EIGHT_BIT_UTF8_TO_NATIVE(cur_char, t[i+1]);
2642 }
2643 else { /* Replace illegal cp with highest collating
2644 one */
2645 s[d++] = PL_strxfrm_max_cp;
2646 }
2647 }
2648 s[d++] = '\0';
2649 Renew(s, d, char); /* Free up unused space */
2650 }
2651 }
2652 }
2653
2654 /* Here, we have constructed a modified version of the input. It could
2655 * be that we already had a modified copy before we did this version.
2656 * If so, that copy is no longer needed */
2657 if (t != input_string) {
2658 Safefree(t);
2659 }
2660 }
2661
17f41037
KW
2662 length_in_chars = (utf8)
2663 ? utf8_length((U8 *) s, (U8 *) s + len)
2664 : len;
2665
59c018b9
KW
2666 /* The first element in the output is the collation id, used by
2667 * sv_collxfrm(); then comes the space for the transformed string. The
2668 * equation should give us a good estimate as to how much is needed */
55e5378d 2669 xAlloc = COLLXFRM_HDR_LEN
a4a439fb 2670 + PL_collxfrm_base
17f41037 2671 + (PL_collxfrm_mult * length_in_chars);
a02a5408 2672 Newx(xbuf, xAlloc, char);
c7202dee
KW
2673 if (UNLIKELY(! xbuf)) {
2674 DEBUG_L(PerlIO_printf(Perl_debug_log,
2675 "_mem_collxfrm: Couldn't malloc %zu bytes\n", xAlloc));
98994639 2676 goto bad;
c7202dee 2677 }
98994639 2678
d35fca5f 2679 /* Store the collation id */
98994639 2680 *(U32*)xbuf = PL_collation_ix;
d35fca5f
KW
2681
2682 /* Then the transformation of the input. We loop until successful, or we
2683 * give up */
4ebeff16 2684 for (;;) {
1adab0a7 2685
55e5378d 2686 *xlen = strxfrm(xbuf + COLLXFRM_HDR_LEN, s, xAlloc - COLLXFRM_HDR_LEN);
4ebeff16
KW
2687
2688 /* If the transformed string occupies less space than we told strxfrm()
2689 * was available, it means it successfully transformed the whole
2690 * string. */
55e5378d 2691 if (*xlen < xAlloc - COLLXFRM_HDR_LEN) {
17f41037 2692
1adab0a7
KW
2693 /* Some systems include a trailing NUL in the returned length.
2694 * Ignore it, using a loop in case multiple trailing NULs are
2695 * returned. */
2696 while ( (*xlen) > 0
2697 && *(xbuf + COLLXFRM_HDR_LEN + (*xlen) - 1) == '\0')
2698 {
2699 (*xlen)--;
2700 }
2701
17f41037
KW
2702 /* If the first try didn't get it, it means our prediction was low.
2703 * Modify the coefficients so that we predict a larger value in any
2704 * future transformations */
2705 if (! first_time) {
2706 STRLEN needed = *xlen + 1; /* +1 For trailing NUL */
2707 STRLEN computed_guess = PL_collxfrm_base
2708 + (PL_collxfrm_mult * length_in_chars);
e1c30f0c
KW
2709
2710 /* On zero-length input, just keep current slope instead of
2711 * dividing by 0 */
2712 const STRLEN new_m = (length_in_chars != 0)
2713 ? needed / length_in_chars
2714 : PL_collxfrm_mult;
17f41037
KW
2715
2716 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
b07929e4
KW
2717 "%s: %d: initial size of %zu bytes for a length "
2718 "%zu string was insufficient, %zu needed\n",
17f41037 2719 __FILE__, __LINE__,
b07929e4 2720 computed_guess, length_in_chars, needed));
17f41037
KW
2721
2722 /* If slope increased, use it, but discard this result for
2723 * length 1 strings, as we can't be sure that it's a real slope
2724 * change */
2725 if (length_in_chars > 1 && new_m > PL_collxfrm_mult) {
7d4bcc4a
KW
2726
2727# ifdef DEBUGGING
2728
17f41037
KW
2729 STRLEN old_m = PL_collxfrm_mult;
2730 STRLEN old_b = PL_collxfrm_base;
7d4bcc4a
KW
2731
2732# endif
2733
17f41037
KW
2734 PL_collxfrm_mult = new_m;
2735 PL_collxfrm_base = 1; /* +1 For trailing NUL */
2736 computed_guess = PL_collxfrm_base
2737 + (PL_collxfrm_mult * length_in_chars);
2738 if (computed_guess < needed) {
2739 PL_collxfrm_base += needed - computed_guess;
2740 }
2741
2742 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
b07929e4
KW
2743 "%s: %d: slope is now %zu; was %zu, base "
2744 "is now %zu; was %zu\n",
17f41037 2745 __FILE__, __LINE__,
b07929e4
KW
2746 PL_collxfrm_mult, old_m,
2747 PL_collxfrm_base, old_b));
17f41037
KW
2748 }
2749 else { /* Slope didn't change, but 'b' did */
2750 const STRLEN new_b = needed
2751 - computed_guess
2752 + PL_collxfrm_base;
2753 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
b07929e4 2754 "%s: %d: base is now %zu; was %zu\n",
17f41037 2755 __FILE__, __LINE__,
b07929e4 2756 new_b, PL_collxfrm_base));
17f41037
KW
2757 PL_collxfrm_base = new_b;
2758 }
2759 }
2760
4ebeff16
KW
2761 break;
2762 }
bb0f664e 2763
c7202dee
KW
2764 if (UNLIKELY(*xlen >= PERL_INT_MAX)) {
2765 DEBUG_L(PerlIO_printf(Perl_debug_log,
2766 "_mem_collxfrm: Needed %zu bytes, max permissible is %u\n",
2767 *xlen, PERL_INT_MAX));
4ebeff16 2768 goto bad;
c7202dee 2769 }
d35fca5f 2770
c664130f 2771 /* A well-behaved strxfrm() returns exactly how much space it needs
1adab0a7
KW
2772 * (usually not including the trailing NUL) when it fails due to not
2773 * enough space being provided. Assume that this is the case unless
2774 * it's been proven otherwise */
c664130f 2775 if (LIKELY(PL_strxfrm_is_behaved) && first_time) {
55e5378d 2776 xAlloc = *xlen + COLLXFRM_HDR_LEN + 1;
c664130f
KW
2777 }
2778 else { /* Here, either:
2779 * 1) The strxfrm() has previously shown bad behavior; or
2780 * 2) It isn't the first time through the loop, which means
2781 * that the strxfrm() is now showing bad behavior, because
2782 * we gave it what it said was needed in the previous
2783 * iteration, and it came back saying it needed still more.
2784 * (Many versions of cygwin fit this. When the buffer size
2785 * isn't sufficient, they return the input size instead of
2786 * how much is needed.)
d4ff9586
KW
2787 * Increase the buffer size by a fixed percentage and try again.
2788 * */
6ddd902c 2789 xAlloc += (xAlloc / 4) + 1;
c664130f 2790 PL_strxfrm_is_behaved = FALSE;
c664130f 2791
7d4bcc4a
KW
2792# ifdef DEBUGGING
2793
58eebef2
KW
2794 if (DEBUG_Lv_TEST || debug_initialization) {
2795 PerlIO_printf(Perl_debug_log,
2796 "_mem_collxfrm required more space than previously calculated"
b07929e4 2797 " for locale %s, trying again with new guess=%d+%zu\n",
58eebef2 2798 PL_collation_name, (int) COLLXFRM_HDR_LEN,
b07929e4 2799 xAlloc - COLLXFRM_HDR_LEN);
58eebef2 2800 }
7d4bcc4a
KW
2801
2802# endif
2803
58eebef2 2804 }
c664130f 2805
4ebeff16 2806 Renew(xbuf, xAlloc, char);
c7202dee
KW
2807 if (UNLIKELY(! xbuf)) {
2808 DEBUG_L(PerlIO_printf(Perl_debug_log,
2809 "_mem_collxfrm: Couldn't realloc %zu bytes\n", xAlloc));
4ebeff16 2810 goto bad;
c7202dee 2811 }
c664130f
KW
2812
2813 first_time = FALSE;
4ebeff16 2814 }
98994639 2815
6696cfa7 2816
7d4bcc4a
KW
2817# ifdef DEBUGGING
2818
58eebef2 2819 if (DEBUG_Lv_TEST || debug_initialization) {
c7202dee
KW
2820
2821 print_collxfrm_input_and_return(s, s + len, xlen, utf8);
2822 PerlIO_printf(Perl_debug_log, "Its xfrm is:");
7e2f38b2
KW
2823 PerlIO_printf(Perl_debug_log, "%s\n",
2824 _byte_dump_string((U8 *) xbuf + COLLXFRM_HDR_LEN,
2825 *xlen, 1));
58eebef2 2826 }
7d4bcc4a
KW
2827
2828# endif
58eebef2 2829
3c5f993e 2830 /* Free up unneeded space; retain ehough for trailing NUL */
55e5378d 2831 Renew(xbuf, COLLXFRM_HDR_LEN + *xlen + 1, char);
98994639 2832
6696cfa7
KW
2833 if (s != input_string) {
2834 Safefree(s);
98994639
HS
2835 }
2836
98994639
HS
2837 return xbuf;
2838
2839 bad:
2840 Safefree(xbuf);
6696cfa7
KW
2841 if (s != input_string) {
2842 Safefree(s);
2843 }
98994639 2844 *xlen = 0;
7d4bcc4a
KW
2845
2846# ifdef DEBUGGING
2847
58eebef2 2848 if (DEBUG_Lv_TEST || debug_initialization) {
c7202dee 2849 print_collxfrm_input_and_return(s, s + len, NULL, utf8);
58eebef2 2850 }
7d4bcc4a
KW
2851
2852# endif
2853
98994639
HS
2854 return NULL;
2855}
2856
7d4bcc4a 2857# ifdef DEBUGGING
c7202dee 2858
4cbaac56 2859STATIC void
c7202dee
KW
2860S_print_collxfrm_input_and_return(pTHX_
2861 const char * const s,
2862 const char * const e,
2863 const STRLEN * const xlen,
2864 const bool is_utf8)
2865{
c7202dee
KW
2866
2867 PERL_ARGS_ASSERT_PRINT_COLLXFRM_INPUT_AND_RETURN;
2868
511e4ff7
DM
2869 PerlIO_printf(Perl_debug_log, "_mem_collxfrm[%" UVuf "]: returning ",
2870 (UV)PL_collation_ix);
c7202dee 2871 if (xlen) {
08b6dc1d 2872 PerlIO_printf(Perl_debug_log, "%zu", *xlen);
c7202dee
KW
2873 }
2874 else {
2875 PerlIO_printf(Perl_debug_log, "NULL");
2876 }
2877 PerlIO_printf(Perl_debug_log, " for locale '%s', string='",
2878 PL_collation_name);
9c8a6dc2
KW
2879 print_bytes_for_locale(s, e, is_utf8);
2880
2881 PerlIO_printf(Perl_debug_log, "'\n");
2882}
2883
2884STATIC void
2885S_print_bytes_for_locale(pTHX_
2886 const char * const s,
2887 const char * const e,
2888 const bool is_utf8)
2889{
2890 const char * t = s;
2891 bool prev_was_printable = TRUE;
2892 bool first_time = TRUE;
2893
2894 PERL_ARGS_ASSERT_PRINT_BYTES_FOR_LOCALE;
c7202dee
KW
2895
2896 while (t < e) {
2897 UV cp = (is_utf8)
2898 ? utf8_to_uvchr_buf((U8 *) t, e, NULL)
2899 : * (U8 *) t;
2900 if (isPRINT(cp)) {
2901 if (! prev_was_printable) {
2902 PerlIO_printf(Perl_debug_log, " ");
2903 }
2904 PerlIO_printf(Perl_debug_log, "%c", (U8) cp);
2905 prev_was_printable = TRUE;
2906 }
2907 else {
2908 if (! first_time) {
2909 PerlIO_printf(Perl_debug_log, " ");
2910 }
147e3846 2911 PerlIO_printf(Perl_debug_log, "%02" UVXf, cp);
c7202dee
KW
2912 prev_was_printable = FALSE;
2913 }
2914 t += (is_utf8) ? UTF8SKIP(t) : 1;
2915 first_time = FALSE;
2916 }
c7202dee
KW
2917}
2918
7d4bcc4a 2919# endif /* #ifdef DEBUGGING */
98994639 2920#endif /* USE_LOCALE_COLLATE */
58eebef2 2921
8ef6e574
KW
2922#ifdef USE_LOCALE
2923
c1284011
KW
2924bool
2925Perl__is_cur_LC_category_utf8(pTHX_ int category)
7d74bb61
KW
2926{
2927 /* Returns TRUE if the current locale for 'category' is UTF-8; FALSE
2928 * otherwise. 'category' may not be LC_ALL. If the platform doesn't have
119ee68b 2929 * nl_langinfo(), nor MB_CUR_MAX, this employs a heuristic, which hence
609548d2
KW
2930 * could give the wrong result. The result will very likely be correct for
2931 * languages that have commonly used non-ASCII characters, but for notably
2932 * English, it comes down to if the locale's name ends in something like
2933 * "UTF-8". It errs on the side of not being a UTF-8 locale. */
7d74bb61
KW
2934
2935 char *save_input_locale = NULL;
7d74bb61
KW
2936 STRLEN final_pos;
2937
7d4bcc4a
KW
2938# ifdef LC_ALL
2939
7d74bb61 2940 assert(category != LC_ALL);
7d4bcc4a
KW
2941
2942# endif
7d74bb61
KW
2943
2944 /* First dispose of the trivial cases */
837ce802 2945 save_input_locale = do_setlocale_r(category, NULL);
7d74bb61 2946 if (! save_input_locale) {
69014004
KW
2947 DEBUG_L(PerlIO_printf(Perl_debug_log,
2948 "Could not find current locale for category %d\n",
2949 category));
7d74bb61
KW
2950 return FALSE; /* XXX maybe should croak */
2951 }
b07fffd1 2952 save_input_locale = stdize_locale(savepv(save_input_locale));
a39edc4c 2953 if (isNAME_C_OR_POSIX(save_input_locale)) {
69014004
KW
2954 DEBUG_L(PerlIO_printf(Perl_debug_log,
2955 "Current locale for category %d is %s\n",
2956 category, save_input_locale));
b07fffd1 2957 Safefree(save_input_locale);
7d74bb61
KW
2958 return FALSE;
2959 }
2960
7d4bcc4a 2961# if defined(USE_LOCALE_CTYPE) \
1d958db2 2962 && (defined(MB_CUR_MAX) || (defined(HAS_NL_LANGINFO) && defined(CODESET)))
7d74bb61 2963
1d958db2 2964 { /* Next try nl_langinfo or MB_CUR_MAX if available */
7d74bb61
KW
2965
2966 char *save_ctype_locale = NULL;
119ee68b 2967 bool is_utf8;
7d74bb61 2968
119ee68b 2969 if (category != LC_CTYPE) { /* These work only on LC_CTYPE */
7d74bb61
KW
2970
2971 /* Get the current LC_CTYPE locale */
837ce802 2972 save_ctype_locale = do_setlocale_c(LC_CTYPE, NULL);
7d74bb61 2973 if (! save_ctype_locale) {
69014004
KW
2974 DEBUG_L(PerlIO_printf(Perl_debug_log,
2975 "Could not find current locale for LC_CTYPE\n"));
7d74bb61
KW
2976 goto cant_use_nllanginfo;
2977 }
4f72bb37 2978 save_ctype_locale = stdize_locale(savepv(save_ctype_locale));
7d74bb61
KW
2979
2980 /* If LC_CTYPE and the desired category use the same locale, this
2981 * means that finding the value for LC_CTYPE is the same as finding
2982 * the value for the desired category. Otherwise, switch LC_CTYPE
2983 * to the desired category's locale */
2984 if (strEQ(save_ctype_locale, save_input_locale)) {
2985 Safefree(save_ctype_locale);
2986 save_ctype_locale = NULL;
2987 }
837ce802 2988 else if (! do_setlocale_c(LC_CTYPE, save_input_locale)) {
69014004
KW
2989 DEBUG_L(PerlIO_printf(Perl_debug_log,
2990 "Could not change LC_CTYPE locale to %s\n",
2991 save_input_locale));
7d74bb61
KW
2992 Safefree(save_ctype_locale);
2993 goto cant_use_nllanginfo;
2994 }
2995 }
2996
69014004
KW
2997 DEBUG_L(PerlIO_printf(Perl_debug_log, "Current LC_CTYPE locale=%s\n",
2998 save_input_locale));
2999
7d74bb61 3000 /* Here the current LC_CTYPE is set to the locale of the category whose
1d958db2
KW
3001 * information is desired. This means that nl_langinfo() and MB_CUR_MAX
3002 * should give the correct results */
119ee68b 3003
7d4bcc4a 3004# if defined(HAS_NL_LANGINFO) && defined(CODESET)
c70a3e68 3005 /* The task is easiest if has this POSIX 2001 function */
7d4bcc4a 3006
1d958db2 3007 {
c70a3e68
KW
3008 const char *codeset = my_nl_langinfo(PERL_CODESET, FALSE);
3009 /* FALSE => already in dest locale */
119ee68b 3010
c70a3e68
KW
3011 DEBUG_L(PerlIO_printf(Perl_debug_log,
3012 "\tnllanginfo returned CODESET '%s'\n", codeset));
3013
3014 if (codeset && strNE(codeset, "")) {
1d958db2
KW
3015 /* If we switched LC_CTYPE, switch back */
3016 if (save_ctype_locale) {
837ce802 3017 do_setlocale_c(LC_CTYPE, save_ctype_locale);
1d958db2
KW
3018 Safefree(save_ctype_locale);
3019 }
3020
abc1d81d
KW
3021 is_utf8 = ( ( strlen(codeset) == STRLENs("UTF-8")
3022 && foldEQ(codeset, STR_WITH_LEN("UTF-8")))
3023 || ( strlen(codeset) == STRLENs("UTF8")
3024 && foldEQ(codeset, STR_WITH_LEN("UTF8"))));
1d958db2 3025
69014004
KW
3026 DEBUG_L(PerlIO_printf(Perl_debug_log,
3027 "\tnllanginfo returned CODESET '%s'; ?UTF8 locale=%d\n",
3028 codeset, is_utf8));
1d958db2
KW
3029 Safefree(save_input_locale);
3030 return is_utf8;
3031 }
119ee68b
KW
3032 }
3033
7d4bcc4a
KW
3034# endif
3035# ifdef MB_CUR_MAX
1d958db2
KW
3036
3037 /* Here, either we don't have nl_langinfo, or it didn't return a
3038 * codeset. Try MB_CUR_MAX */
3039
119ee68b
KW
3040 /* Standard UTF-8 needs at least 4 bytes to represent the maximum
3041 * Unicode code point. Since UTF-8 is the only non-single byte
3042 * encoding we handle, we just say any such encoding is UTF-8, and if
3043 * turns out to be wrong, other things will fail */
3044 is_utf8 = MB_CUR_MAX >= 4;
3045
69014004
KW
3046 DEBUG_L(PerlIO_printf(Perl_debug_log,
3047 "\tMB_CUR_MAX=%d; ?UTF8 locale=%d\n",
3048 (int) MB_CUR_MAX, is_utf8));
3049
119ee68b
KW
3050 Safefree(save_input_locale);
3051
7d4bcc4a 3052# ifdef HAS_MBTOWC
119ee68b
KW
3053
3054 /* ... But, most system that have MB_CUR_MAX will also have mbtowc(),
3055 * since they are both in the C99 standard. We can feed a known byte
3056 * string to the latter function, and check that it gives the expected
3057 * result */
3058 if (is_utf8) {
3059 wchar_t wc;
51fc4b19
KW
3060 int len;
3061
856b881c 3062 PERL_UNUSED_RESULT(mbtowc(&wc, NULL, 0));/* Reset any shift state */
69014004 3063 errno = 0;
b1d4925c 3064 len = mbtowc(&wc, STR_WITH_LEN(REPLACEMENT_CHARACTER_UTF8));
51fc4b19 3065
b1d4925c
KW
3066
3067 if ( len != STRLENs(REPLACEMENT_CHARACTER_UTF8)
3068 || wc != (wchar_t) 0xFFFD)
119ee68b
KW
3069 {
3070 is_utf8 = FALSE;
b1d4925c
KW
3071 DEBUG_L(PerlIO_printf(Perl_debug_log, "\replacement=U+%x\n",
3072 (unsigned int)wc));
69014004
KW
3073 DEBUG_L(PerlIO_printf(Perl_debug_log,
3074 "\treturn from mbtowc=%d; errno=%d; ?UTF8 locale=0\n",
51fc4b19 3075 len, errno));
119ee68b
KW
3076 }
3077 }
7d4bcc4a
KW
3078
3079# endif
119ee68b 3080
1d958db2
KW
3081 /* If we switched LC_CTYPE, switch back */
3082 if (save_ctype_locale) {
837ce802 3083 do_setlocale_c(LC_CTYPE, save_ctype_locale);
1d958db2 3084 Safefree(save_ctype_locale);
119ee68b 3085 }
7d74bb61 3086
1d958db2 3087 return is_utf8;
7d4bcc4a
KW
3088
3089# endif
3090
7d74bb61 3091 }
119ee68b 3092
7d74bb61
KW
3093 cant_use_nllanginfo:
3094
7d4bcc4a 3095# else /* nl_langinfo should work if available, so don't bother compiling this
0080c90a
KW
3096 fallback code. The final fallback of looking at the name is
3097 compiled, and will be executed if nl_langinfo fails */
7d74bb61 3098
97f4de96
KW
3099 /* nl_langinfo not available or failed somehow. Next try looking at the
3100 * currency symbol to see if it disambiguates things. Often that will be
3101 * in the native script, and if the symbol isn't in UTF-8, we know that the
3102 * locale isn't. If it is non-ASCII UTF-8, we infer that the locale is
609548d2
KW
3103 * too, as the odds of a non-UTF8 string being valid UTF-8 are quite small
3104 * */
fa9b773e 3105
7d4bcc4a
KW
3106# ifdef HAS_LOCALECONV
3107# ifdef USE_LOCALE_MONETARY
3108
fa9b773e
KW
3109 {
3110 char *save_monetary_locale = NULL;
fa9b773e 3111 bool only_ascii = FALSE;
13542a67
KW
3112 bool is_utf8 = FALSE;
3113 struct lconv* lc;
fa9b773e 3114
97f4de96
KW
3115 /* Like above for LC_CTYPE, we first set LC_MONETARY to the locale of
3116 * the desired category, if it isn't that locale already */
3117
fa9b773e
KW
3118 if (category != LC_MONETARY) {
3119
837ce802 3120 save_monetary_locale = do_setlocale_c(LC_MONETARY, NULL);
fa9b773e 3121 if (! save_monetary_locale) {
69014004
KW
3122 DEBUG_L(PerlIO_printf(Perl_debug_log,
3123 "Could not find current locale for LC_MONETARY\n"));
fa9b773e
KW
3124 goto cant_use_monetary;
3125 }
4f72bb37 3126 save_monetary_locale = stdize_locale(savepv(save_monetary_locale));
fa9b773e 3127
13542a67
KW
3128 if (strEQ(save_monetary_locale, save_input_locale)) {
3129 Safefree(save_monetary_locale);
3130 save_monetary_locale = NULL;
3131 }
837ce802 3132 else if (! do_setlocale_c(LC_MONETARY, save_input_locale)) {
59c234b4
KW
3133 DEBUG_L(PerlIO_printf(Perl_debug_log,
3134 "Could not change LC_MONETARY locale to %s\n",
3135 save_input_locale));
3136 Safefree(save_monetary_locale);
3137 goto cant_use_monetary;
fa9b773e
KW
3138 }
3139 }
3140
3141 /* Here the current LC_MONETARY is set to the locale of the category
3142 * whose information is desired. */
3143
13542a67
KW
3144 lc = localeconv();
3145 if (! lc
3146 || ! lc->currency_symbol
c5f058df 3147 || is_utf8_invariant_string((U8 *) lc->currency_symbol, 0))
13542a67
KW
3148 {
3149 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));
3150 only_ascii = TRUE;
3151 }
3152 else {
3153 is_utf8 = is_utf8_string((U8 *) lc->currency_symbol, 0);
fa9b773e
KW
3154 }
3155
3156 /* If we changed it, restore LC_MONETARY to its original locale */
3157 if (save_monetary_locale) {
837ce802 3158 do_setlocale_c(LC_MONETARY, save_monetary_locale);
fa9b773e
KW
3159 Safefree(save_monetary_locale);
3160 }
3161
13542a67 3162 if (! only_ascii) {
fa9b773e 3163
59c234b4
KW
3164 /* It isn't a UTF-8 locale if the symbol is not legal UTF-8;
3165 * otherwise assume the locale is UTF-8 if and only if the symbol
3166 * is non-ascii UTF-8. */
3167 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?Currency symbol for %s is UTF-8=%d\n",
3168 save_input_locale, is_utf8));
3169 Safefree(save_input_locale);
3170 return is_utf8;
13542a67 3171 }
fa9b773e
KW
3172 }
3173 cant_use_monetary:
3174
7d4bcc4a
KW
3175# endif /* USE_LOCALE_MONETARY */
3176# endif /* HAS_LOCALECONV */
fa9b773e 3177
7d4bcc4a 3178# if defined(HAS_STRFTIME) && defined(USE_LOCALE_TIME)
15f7e74e
KW
3179
3180/* Still haven't found a non-ASCII string to disambiguate UTF-8 or not. Try
3181 * the names of the months and weekdays, timezone, and am/pm indicator */
3182 {
3183 char *save_time_locale = NULL;
3184 int hour = 10;
3185 bool is_dst = FALSE;
3186 int dom = 1;
3187 int month = 0;
3188 int i;
3189 char * formatted_time;
3190
3191
3192 /* Like above for LC_MONETARY, we set LC_TIME to the locale of the
3193 * desired category, if it isn't that locale already */
3194
3195 if (category != LC_TIME) {
3196
837ce802 3197 save_time_locale = do_setlocale_c(LC_TIME, NULL);
15f7e74e
KW
3198 if (! save_time_locale) {
3199 DEBUG_L(PerlIO_printf(Perl_debug_log,
3200 "Could not find current locale for LC_TIME\n"));
3201 goto cant_use_time;
3202 }
3203 save_time_locale = stdize_locale(savepv(save_time_locale));
3204
3205 if (strEQ(save_time_locale, save_input_locale)) {
3206 Safefree(save_time_locale);
3207 save_time_locale = NULL;
3208 }
837ce802 3209 else if (! do_setlocale_c(LC_TIME, save_input_locale)) {
15f7e74e
KW
3210 DEBUG_L(PerlIO_printf(Perl_debug_log,
3211 "Could not change LC_TIME locale to %s\n",
3212 save_input_locale));
3213 Safefree(save_time_locale);
3214 goto cant_use_time;
3215 }
3216 }
3217
3218 /* Here the current LC_TIME is set to the locale of the category
3219 * whose information is desired. Look at all the days of the week and
9f10db87 3220 * month names, and the timezone and am/pm indicator for UTF-8 variant
15f7e74e
KW
3221 * characters. The first such a one found will tell us if the locale
3222 * is UTF-8 or not */
3223
3224 for (i = 0; i < 7 + 12; i++) { /* 7 days; 12 months */
3225 formatted_time = my_strftime("%A %B %Z %p",
3ae5cd07 3226 0, 0, hour, dom, month, 2012 - 1900, 0, 0, is_dst);
c5f058df
KW
3227 if ( ! formatted_time
3228 || is_utf8_invariant_string((U8 *) formatted_time, 0))
3229 {
15f7e74e
KW
3230
3231 /* Here, we didn't find a non-ASCII. Try the next time through
3232 * with the complemented dst and am/pm, and try with the next
3233 * weekday. After we have gotten all weekdays, try the next
3234 * month */
3235 is_dst = ! is_dst;
3236 hour = (hour + 12) % 24;
3237 dom++;
3238 if (i > 6) {
3239 month++;
3240 }
3241 continue;
3242 }
3243
3244 /* Here, we have a non-ASCII. Return TRUE is it is valid UTF8;
3245 * false otherwise. But first, restore LC_TIME to its original
3246 * locale if we changed it */
3247 if (save_time_locale) {
837ce802 3248 do_setlocale_c(LC_TIME, save_time_locale);
15f7e74e
KW
3249 Safefree(save_time_locale);
3250 }
3251
3252 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?time-related strings for %s are UTF-8=%d\n",
3253 save_input_locale,
3254 is_utf8_string((U8 *) formatted_time, 0)));
3255 Safefree(save_input_locale);
3256 return is_utf8_string((U8 *) formatted_time, 0);
3257 }
3258
3259 /* Falling off the end of the loop indicates all the names were just
3260 * ASCII. Go on to the next test. If we changed it, restore LC_TIME
3261 * to its original locale */
3262 if (save_time_locale) {
837ce802 3263 do_setlocale_c(LC_TIME, save_time_locale);
15f7e74e
KW
3264 Safefree(save_time_locale);
3265 }
3266 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));
3267 }
3268 cant_use_time:
3269
7d4bcc4a 3270# endif
15f7e74e 3271
7d4bcc4a 3272# if 0 && defined(USE_LOCALE_MESSAGES) && defined(HAS_SYS_ERRLIST)
855aeb93
JH
3273
3274/* This code is ifdefd out because it was found to not be necessary in testing
5857e934
KW
3275 * on our dromedary test machine, which has over 700 locales. There, this
3276 * added no value to looking at the currency symbol and the time strings. I
3277 * left it in so as to avoid rewriting it if real-world experience indicates
3278 * that dromedary is an outlier. Essentially, instead of returning abpve if we
855aeb93
JH
3279 * haven't found illegal utf8, we continue on and examine all the strerror()
3280 * messages on the platform for utf8ness. If all are ASCII, we still don't
3281 * know the answer; but otherwise we have a pretty good indication of the
5857e934
KW
3282 * utf8ness. The reason this doesn't help much is that the messages may not
3283 * have been translated into the locale. The currency symbol and time strings
3284 * are much more likely to have been translated. */
3285 {
855aeb93 3286 int e;
5857e934
KW
3287 bool is_utf8 = FALSE;
3288 bool non_ascii = FALSE;
855aeb93 3289 char *save_messages_locale = NULL;
5857e934 3290 const char * errmsg = NULL;
855aeb93 3291
5857e934
KW
3292 /* Like above, we set LC_MESSAGES to the locale of the desired
3293 * category, if it isn't that locale already */
855aeb93
JH
3294
3295 if (category != LC_MESSAGES) {
3296
837ce802 3297 save_messages_locale = do_setlocale_c(LC_MESSAGES, NULL);
855aeb93 3298 if (! save_messages_locale) {
5857e934
KW
3299 DEBUG_L(PerlIO_printf(Perl_debug_log,
3300 "Could not find current locale for LC_MESSAGES\n"));
855aeb93
JH
3301 goto cant_use_messages;
3302 }
5857e934 3303 save_messages_locale = stdize_locale(savepv(save_messages_locale));
855aeb93
JH
3304
3305 if (strEQ(save_messages_locale, save_input_locale)) {
5857e934
KW
3306 Safefree(save_messages_locale);
3307 save_messages_locale = NULL;
855aeb93 3308 }
837ce802 3309 else if (! do_setlocale_c(LC_MESSAGES, save_input_locale)) {
5857e934
KW
3310 DEBUG_L(PerlIO_printf(Perl_debug_log,
3311 "Could not change LC_MESSAGES locale to %s\n",
3312 save_input_locale));
855aeb93
JH
3313 Safefree(save_messages_locale);
3314 goto cant_use_messages;
3315 }
3316 }
3317
3318 /* Here the current LC_MESSAGES is set to the locale of the category
5857e934
KW
3319 * whose information is desired. Look through all the messages. We
3320 * can't use Strerror() here because it may expand to code that
3321 * segfaults in miniperl */
855aeb93 3322
5857e934
KW
3323 for (e = 0; e <= sys_nerr; e++) {
3324 errno = 0;
3325 errmsg = sys_errlist[e];
3326 if (errno || !errmsg) {
855aeb93
JH
3327 break;
3328 }
5857e934 3329 errmsg = savepv(errmsg);
c5f058df 3330 if (! is_utf8_invariant_string((U8 *) errmsg, 0)) {
5857e934
KW
3331 non_ascii = TRUE;
3332 is_utf8 = is_utf8_string((U8 *) errmsg, 0);
3333 break;
855aeb93
JH
3334 }
3335 }
5857e934 3336 Safefree(errmsg);
855aeb93
JH
3337
3338 /* And, if we changed it, restore LC_MESSAGES to its original locale */
3339 if (save_messages_locale) {
837ce802 3340 do_setlocale_c(LC_MESSAGES, save_messages_locale);
855aeb93
JH
3341 Safefree(save_messages_locale);
3342 }
3343
5857e934
KW
3344 if (non_ascii) {
3345
3346 /* Any non-UTF-8 message means not a UTF-8 locale; if all are valid,
3347 * any non-ascii means it is one; otherwise we assume it isn't */
3348 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?error messages for %s are UTF-8=%d\n",
3349 save_input_locale,
3350 is_utf8));
3351 Safefree(save_input_locale);
3352 return is_utf8;
3353 }
855aeb93 3354
5857e934 3355 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));
855aeb93
JH
3356 }
3357 cant_use_messages:
3358
7d4bcc4a
KW
3359# endif
3360# endif /* the code that is compiled when no nl_langinfo */
0080c90a 3361
7d4bcc4a 3362# ifndef EBCDIC /* On os390, even if the name ends with "UTF-8', it isn't a
92c0a900 3363 UTF-8 locale */
7d4bcc4a 3364
97f4de96
KW
3365 /* As a last resort, look at the locale name to see if it matches
3366 * qr/UTF -? * 8 /ix, or some other common locale names. This "name", the
3367 * return of setlocale(), is actually defined to be opaque, so we can't
3368 * really rely on the absence of various substrings in the name to indicate
3369 * its UTF-8ness, but if it has UTF8 in the name, it is extremely likely to
3370 * be a UTF-8 locale. Similarly for the other common names */
3371
3372 final_pos = strlen(save_input_locale) - 1;
3373 if (final_pos >= 3) {
3374 char *name = save_input_locale;
3375
3376 /* Find next 'U' or 'u' and look from there */
3377 while ((name += strcspn(name, "Uu") + 1)
3378 <= save_input_locale + final_pos - 2)
3379 {
c72493e0 3380 if ( isALPHA_FOLD_NE(*name, 't')
305b8651 3381 || isALPHA_FOLD_NE(*(name + 1), 'f'))
97f4de96
KW
3382 {
3383 continue;
3384 }
3385 name += 2;
3386 if (*(name) == '-') {
3387 if ((name > save_input_locale + final_pos - 1)) {
3388 break;
3389 }
3390 name++;
3391 }
3392 if (*(name) == '8') {
97f4de96
KW
3393 DEBUG_L(PerlIO_printf(Perl_debug_log,
3394 "Locale %s ends with UTF-8 in name\n",
3395 save_input_locale));
00c54b9c 3396 Safefree(save_input_locale);
97f4de96
KW
3397 return TRUE;
3398 }
3399 }
3400 DEBUG_L(PerlIO_printf(Perl_debug_log,
3401 "Locale %s doesn't end with UTF-8 in name\n",
3402 save_input_locale));
3403 }
3404
7d4bcc4a
KW
3405# endif
3406# ifdef WIN32
3407
97f4de96 3408 /* http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756.aspx */
8a0832a1 3409 if (memENDs(save_input_locale, final_pos, "65001")) {
97f4de96 3410 DEBUG_L(PerlIO_printf(Perl_debug_log,
8a0832a1 3411 "Locale %s ends with 65001 in name, is UTF-8 locale\n",
97f4de96
KW
3412 save_input_locale));
3413 Safefree(save_input_locale);
3414 return TRUE;
3415 }
7d4bcc4a
KW
3416
3417# endif
97f4de96
KW
3418
3419 /* Other common encodings are the ISO 8859 series, which aren't UTF-8. But
3420 * since we are about to return FALSE anyway, there is no point in doing
3421 * this extra work */
7d4bcc4a
KW
3422
3423# if 0
97f4de96
KW
3424 if (instr(save_input_locale, "8859")) {
3425 DEBUG_L(PerlIO_printf(Perl_debug_log,
3426 "Locale %s has 8859 in name, not UTF-8 locale\n",
3427 save_input_locale));
3428 Safefree(save_input_locale);
3429 return FALSE;
3430 }
7d4bcc4a 3431# endif
97f4de96 3432
69014004
KW
3433 DEBUG_L(PerlIO_printf(Perl_debug_log,
3434 "Assuming locale %s is not a UTF-8 locale\n",
3435 save_input_locale));
fa9b773e 3436 Safefree(save_input_locale);
7d74bb61
KW
3437 return FALSE;
3438}
3439
8ef6e574 3440#endif
7d74bb61 3441
d6ded950
KW
3442
3443bool
3444Perl__is_in_locale_category(pTHX_ const bool compiling, const int category)
3445{
1a4f13e1 3446 dVAR;
d6ded950
KW
3447 /* Internal function which returns if we are in the scope of a pragma that
3448 * enables the locale category 'category'. 'compiling' should indicate if
3449 * this is during the compilation phase (TRUE) or not (FALSE). */
3450
3451 const COP * const cop = (compiling) ? &PL_compiling : PL_curcop;
3452
3453 SV *categories = cop_hints_fetch_pvs(cop, "locale", 0);
3454 if (! categories || categories == &PL_sv_placeholder) {
3455 return FALSE;
3456 }
3457
3458 /* The pseudo-category 'not_characters' is -1, so just add 1 to each to get
3459 * a valid unsigned */
3460 assert(category >= -1);
3461 return cBOOL(SvUV(categories) & (1U << (category + 1)));
3462}
3463
2c6ee1a7 3464char *
6ebbc862
KW
3465Perl_my_strerror(pTHX_ const int errnum)
3466{
3467 /* Returns a mortalized copy of the text of the error message associated
3468 * with 'errnum'. It uses the current locale's text unless the platform
3469 * doesn't have the LC_MESSAGES category or we are not being called from
3470 * within the scope of 'use locale'. In the former case, it uses whatever
3471 * strerror returns; in the latter case it uses the text from the C locale.
3472 *
3473 * The function just calls strerror(), but temporarily switches, if needed,
3474 * to the C locale */
3475
3476 char *errstr;
52770946 3477 dVAR;
6ebbc862 3478
52770946 3479#ifndef USE_LOCALE_MESSAGES
6ebbc862 3480
52770946
KW
3481 /* If platform doesn't have messages category, we don't do any switching to
3482 * the C locale; we just use whatever strerror() returns */
3483
3484 errstr = savepv(Strerror(errnum));
3485
3486#else /* Has locale messages */
3487
3488 const bool within_locale_scope = IN_LC(LC_MESSAGES);
2c6ee1a7 3489
7aaa36b1
KW
3490# if defined(HAS_POSIX_2008_LOCALE) && defined(HAS_STRERROR_L)
3491
3492 /* This function is trivial if we have strerror_l() */
3493
3494 if (within_locale_scope) {
4eb27fc5 3495 errstr = savepv(strerror(errnum));
7aaa36b1
KW
3496 }
3497 else {
4eb27fc5 3498 errstr = savepv(strerror_l(errnum, PL_C_locale_obj));
7aaa36b1
KW
3499 }
3500
7aaa36b1
KW
3501# else /* Doesn't have strerror_l(). */
3502
3503# ifdef USE_POSIX_2008_LOCALE
3504
fcd0e682 3505 locale_t save_locale = NULL;
7aaa36b1
KW
3506
3507# else
3508
fcd0e682 3509 char * save_locale = NULL;
c9dda6da 3510 bool locale_is_C = FALSE;
2c6ee1a7 3511
6ebbc862
KW
3512 /* We have a critical section to prevent another thread from changing the
3513 * locale out from under us (or zapping the buffer returned from
3514 * setlocale() ) */
3515 LOCALE_LOCK;
3516
7aaa36b1 3517# endif
6ebbc862 3518
9c8a6dc2
KW
3519 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3520 "my_strerror called with errnum %d\n", errnum));
6ebbc862 3521 if (! within_locale_scope) {
c9dda6da 3522 errno = 0;
a0b53297 3523
f1d2176b 3524# ifdef USE_POSIX_2008_LOCALE /* Use the thread-safe locale functions */
6ebbc862 3525
9c8a6dc2
KW
3526 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3527 "Not within locale scope, about to call"
3528 " uselocale(0x%p)\n", PL_C_locale_obj));
6ebbc862 3529 save_locale = uselocale(PL_C_locale_obj);
c9dda6da
KW
3530 if (! save_locale) {
3531 DEBUG_L(PerlIO_printf(Perl_debug_log,
9c8a6dc2
KW
3532 "uselocale failed, errno=%d\n", errno));
3533 }
3534 else {
3535 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3536 "uselocale returned 0x%p\n", save_locale));
c9dda6da 3537 }
6ebbc862 3538
7aaa36b1 3539# else /* Not thread-safe build */
a0b53297 3540
837ce802 3541 save_locale = do_setlocale_c(LC_MESSAGES, NULL);
c9dda6da
KW
3542 if (! save_locale) {
3543 DEBUG_L(PerlIO_printf(Perl_debug_log,
3544 "setlocale failed, errno=%d\n", errno));
3545 }
3546 else {
3547 locale_is_C = isNAME_C_OR_POSIX(save_locale);
2c6ee1a7 3548
c9dda6da
KW
3549 /* Switch to the C locale if not already in it */
3550 if (! locale_is_C) {
2c6ee1a7 3551
c9dda6da
KW
3552 /* The setlocale() just below likely will zap 'save_locale', so
3553 * create a copy. */
3554 save_locale = savepv(save_locale);
837ce802 3555 do_setlocale_c(LC_MESSAGES, "C");
c9dda6da 3556 }
6ebbc862 3557 }
2c6ee1a7 3558
7aaa36b1 3559# endif
2c6ee1a7 3560
6ebbc862 3561 } /* end of ! within_locale_scope */
9c8a6dc2
KW
3562 else {
3563 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s: %d: WITHIN locale scope\n",
3564 __FILE__, __LINE__));
3565 }
a0b53297 3566
9c8a6dc2
KW
3567 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3568 "Any locale change has been done; about to call Strerror\n"));
52770946 3569 errstr = savepv(Strerror(errnum));
6ebbc862
KW
3570
3571 if (! within_locale_scope) {
c9dda6da 3572 errno = 0;
a0b53297 3573
f1d2176b 3574# ifdef USE_POSIX_2008_LOCALE
6ebbc862 3575
9c8a6dc2
KW
3576 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3577 "%s: %d: not within locale scope, restoring the locale\n",
3578 __FILE__, __LINE__));
c9dda6da
KW
3579 if (save_locale && ! uselocale(save_locale)) {
3580 DEBUG_L(PerlIO_printf(Perl_debug_log,
3581 "uselocale restore failed, errno=%d\n", errno));
3582 }
2c6ee1a7 3583 }
6ebbc862 3584
7aaa36b1 3585# else
6ebbc862 3586
c9dda6da 3587 if (save_locale && ! locale_is_C) {
837ce802 3588 if (! do_setlocale_c(LC_MESSAGES, save_locale)) {
c9dda6da
KW
3589 DEBUG_L(PerlIO_printf(Perl_debug_log,
3590 "setlocale restore failed, errno=%d\n", errno));
3591 }
6ebbc862
KW
3592 Safefree(save_locale);
3593 }
3594 }
3595
3596 LOCALE_UNLOCK;
3597
7aaa36b1
KW
3598# endif
3599# endif /* End of doesn't have strerror_l */
52770946 3600#endif /* End of does have locale messages */
6affbbf0
KW
3601
3602#ifdef DEBUGGING
3603
3604 if (DEBUG_Lv_TEST) {
3605 PerlIO_printf(Perl_debug_log, "Strerror returned; saving a copy: '");
3606 print_bytes_for_locale(errstr, errstr + strlen(errstr), 0);
3607 PerlIO_printf(Perl_debug_log, "'\n");
3608 }
3609
2c6ee1a7
KW
3610#endif
3611
52770946 3612 SAVEFREEPV(errstr);
6ebbc862 3613 return errstr;
2c6ee1a7
KW
3614}
3615
66610fdd 3616/*
747c467a 3617
747c467a
KW
3618=for apidoc sync_locale
3619
3620Changing the program's locale should be avoided by XS code. Nevertheless,
3621certain non-Perl libraries called from XS, such as C<Gtk> do so. When this
3622happens, Perl needs to be told that the locale has changed. Use this function
3623to do so, before returning to Perl.
3624
3625=cut
3626*/
3627
3628void
3629Perl_sync_locale(pTHX)
3630{
9f82ea3e 3631 char * newlocale;
747c467a
KW
3632
3633#ifdef USE_LOCALE_CTYPE
7d4bcc4a 3634
9f82ea3e
KW
3635 newlocale = do_setlocale_c(LC_CTYPE, NULL);
3636 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3637 "%s:%d: %s\n", __FILE__, __LINE__,
3638 setlocale_debug_string(LC_CTYPE, NULL, newlocale)));
3639 new_ctype(newlocale);
747c467a 3640
7d4bcc4a 3641#endif /* USE_LOCALE_CTYPE */
747c467a 3642#ifdef USE_LOCALE_COLLATE
7d4bcc4a 3643
9f82ea3e
KW
3644 newlocale = do_setlocale_c(LC_COLLATE, NULL);
3645 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3646 "%s:%d: %s\n", __FILE__, __LINE__,
3647 setlocale_debug_string(LC_COLLATE, NULL, newlocale)));
3648 new_collate(newlocale);
747c467a 3649
7d4bcc4a 3650#endif
747c467a 3651#ifdef USE_LOCALE_NUMERIC
7d4bcc4a 3652
9f82ea3e
KW
3653 newlocale = do_setlocale_c(LC_NUMERIC, NULL);
3654 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3655 "%s:%d: %s\n", __FILE__, __LINE__,
3656 setlocale_debug_string(LC_NUMERIC, NULL, newlocale)));
3657 new_numeric(newlocale);
7d4bcc4a 3658
747c467a
KW
3659#endif /* USE_LOCALE_NUMERIC */
3660
3661}
3662
5d1187d1
KW
3663#if defined(DEBUGGING) && defined(USE_LOCALE)
3664
a4f00dcc
KW
3665STATIC char *
3666S_setlocale_debug_string(const int category, /* category number,
5d1187d1
KW
3667 like LC_ALL */
3668 const char* const locale, /* locale name */
3669
3670 /* return value from setlocale() when attempting to
3671 * set 'category' to 'locale' */
3672 const char* const retval)
3673{
3674 /* Returns a pointer to a NUL-terminated string in static storage with
3675 * added text about the info passed in. This is not thread safe and will
3676 * be overwritten by the next call, so this should be used just to
fa07b8e5 3677 * formulate a string to immediately print or savepv() on. */
5d1187d1 3678
398a990f
DM
3679 /* initialise to a non-null value to keep it out of BSS and so keep
3680 * -DPERL_GLOBAL_STRUCT_PRIVATE happy */
60b45a7d
KW
3681 static char ret[128] = "If you can read this, thank your buggy C"
3682 " library strlcpy(), and change your hints file"
3683 " to undef it";
fa07b8e5 3684 my_strlcpy(ret, "setlocale(", sizeof(ret));
5d1187d1
KW
3685
3686 switch (category) {
3687 default:
fa07b8e5 3688 my_snprintf(ret, sizeof(ret), "%s? %d", ret, category);
5d1187d1 3689 break;
7d4bcc4a
KW
3690
3691# ifdef LC_ALL
3692
5d1187d1 3693 case LC_ALL:
fa07b8e5 3694 my_strlcat(ret, "LC_ALL", sizeof(ret));
5d1187d1 3695 break;
7d4bcc4a
KW
3696
3697# endif
3698# ifdef LC_CTYPE
3699