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