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