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