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