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