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