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