This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perl.h: 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 }
ec0202b5
KW
1983# else
1984# error SYSTEM_DEFAULT_LOCALE only implemented for Win32
1985# endif
7d4bcc4a 1986# endif /* SYSTEM_DEFAULT_LOCALE */
291a84fb
KW
1987
1988 } /* For i > 0 */
65ebb059 1989
7d4bcc4a
KW
1990# ifdef LC_ALL
1991
948523db
KW
1992 sl_result[LC_ALL_INDEX] = do_setlocale_c(LC_ALL, trial_locale);
1993 DEBUG_LOCALE_INIT(LC_ALL, trial_locale, sl_result[LC_ALL_INDEX]);
1994 if (! sl_result[LC_ALL_INDEX]) {
49c85077 1995 setlocale_failure = TRUE;
7cd8b568
KW
1996 }
1997 else {
1998 /* Since LC_ALL succeeded, it should have changed all the other
1999 * categories it can to its value; so we massage things so that the
2000 * setlocales below just return their category's current values.
2001 * This adequately handles the case in NetBSD where LC_COLLATE may
2002 * not be defined for a locale, and setting it individually will
7d4bcc4a 2003 * fail, whereas setting LC_ALL succeeds, leaving LC_COLLATE set to
7cd8b568
KW
2004 * the POSIX locale. */
2005 trial_locale = NULL;
2006 }
7d4bcc4a
KW
2007
2008# endif /* LC_ALL */
98994639 2009
e5f10d49
KW
2010 if (! setlocale_failure) {
2011 unsigned int j;
2012 for (j = 0; j < NOMINAL_LC_ALL_INDEX; j++) {
2013 curlocales[j]
2014 = savepv(do_setlocale_r(categories[j], trial_locale));
2015 if (! curlocales[j]) {
2016 setlocale_failure = TRUE;
2017 }
2018 DEBUG_LOCALE_INIT(categories[j], trial_locale, curlocales[j]);
2019 }
c835d6be 2020
e5f10d49
KW
2021 if (! setlocale_failure) { /* All succeeded */
2022 break; /* Exit trial_locales loop */
49c85077 2023 }
65ebb059 2024 }
98994639 2025
49c85077
KW
2026 /* Here, something failed; will need to try a fallback. */
2027 ok = 0;
65ebb059 2028
49c85077
KW
2029 if (i == 0) {
2030 unsigned int j;
98994639 2031
65ebb059 2032 if (locwarn) { /* Output failure info only on the first one */
7d4bcc4a
KW
2033
2034# ifdef LC_ALL
98994639 2035
49c85077
KW
2036 PerlIO_printf(Perl_error_log,
2037 "perl: warning: Setting locale failed.\n");
98994639 2038
7d4bcc4a 2039# else /* !LC_ALL */
98994639 2040
49c85077
KW
2041 PerlIO_printf(Perl_error_log,
2042 "perl: warning: Setting locale failed for the categories:\n\t");
7d4bcc4a 2043
e5f10d49
KW
2044 for (j = 0; j < NOMINAL_LC_ALL_INDEX; j++) {
2045 if (! curlocales[j]) {
2046 PerlIO_printf(Perl_error_log, category_names[j]);
2047 }
2048 else {
2049 Safefree(curlocales[j]);
2050 }
2051 }
7d4bcc4a 2052
a782673d 2053 PerlIO_printf(Perl_error_log, "and possibly others\n");
98994639 2054
7d4bcc4a 2055# endif /* LC_ALL */
98994639 2056
49c85077
KW
2057 PerlIO_printf(Perl_error_log,
2058 "perl: warning: Please check that your locale settings:\n");
98994639 2059
7d4bcc4a
KW
2060# ifdef __GLIBC__
2061
49c85077
KW
2062 PerlIO_printf(Perl_error_log,
2063 "\tLANGUAGE = %c%s%c,\n",
2064 language ? '"' : '(',
2065 language ? language : "unset",
2066 language ? '"' : ')');
7d4bcc4a 2067# endif
98994639 2068
49c85077
KW
2069 PerlIO_printf(Perl_error_log,
2070 "\tLC_ALL = %c%s%c,\n",
2071 lc_all ? '"' : '(',
2072 lc_all ? lc_all : "unset",
2073 lc_all ? '"' : ')');
98994639 2074
7d4bcc4a
KW
2075# if defined(USE_ENVIRON_ARRAY)
2076
49c85077 2077 {
cd999af9 2078 char **e;
d5e32b93
KW
2079
2080 /* Look through the environment for any variables of the
2081 * form qr/ ^ LC_ [A-Z]+ = /x, except LC_ALL which was
2082 * already handled above. These are assumed to be locale
2083 * settings. Output them and their values. */
cd999af9 2084 for (e = environ; *e; e++) {
d5e32b93
KW
2085 const STRLEN prefix_len = sizeof("LC_") - 1;
2086 STRLEN uppers_len;
2087
cd999af9 2088 if ( strBEGINs(*e, "LC_")
c8b388b0 2089 && ! strBEGINs(*e, "LC_ALL=")
d5e32b93
KW
2090 && (uppers_len = strspn(*e + prefix_len,
2091 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
2092 && ((*e)[prefix_len + uppers_len] == '='))
cd999af9
KW
2093 {
2094 PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
d5e32b93
KW
2095 (int) (prefix_len + uppers_len), *e,
2096 *e + prefix_len + uppers_len + 1);
cd999af9
KW
2097 }
2098 }
49c85077 2099 }
7d4bcc4a
KW
2100
2101# else
2102
49c85077
KW
2103 PerlIO_printf(Perl_error_log,
2104 "\t(possibly more locale environment variables)\n");
7d4bcc4a
KW
2105
2106# endif
98994639 2107
49c85077
KW
2108 PerlIO_printf(Perl_error_log,
2109 "\tLANG = %c%s%c\n",
2110 lang ? '"' : '(',
2111 lang ? lang : "unset",
2112 lang ? '"' : ')');
98994639 2113
49c85077
KW
2114 PerlIO_printf(Perl_error_log,
2115 " are supported and installed on your system.\n");
2116 }
98994639 2117
65ebb059 2118 /* Calculate what fallback locales to try. We have avoided this
f6bab5f6 2119 * until we have to, because failure is quite unlikely. This will
65ebb059
KW
2120 * usually change the upper bound of the loop we are in.
2121 *
2122 * Since the system's default way of setting the locale has not
2123 * found one that works, We use Perl's defined ordering: LC_ALL,
2124 * LANG, and the C locale. We don't try the same locale twice, so
2125 * don't add to the list if already there. (On POSIX systems, the
2126 * LC_ALL element will likely be a repeat of the 0th element "",
6b058d42
KW
2127 * but there's no harm done by doing it explicitly.
2128 *
2129 * Note that this tries the LC_ALL environment variable even on
2130 * systems which have no LC_ALL locale setting. This may or may
2131 * not have been originally intentional, but there's no real need
2132 * to change the behavior. */
65ebb059
KW
2133 if (lc_all) {
2134 for (j = 0; j < trial_locales_count; j++) {
2135 if (strEQ(lc_all, trial_locales[j])) {
2136 goto done_lc_all;
2137 }
2138 }
2139 trial_locales[trial_locales_count++] = lc_all;
2140 }
2141 done_lc_all:
98994639 2142
65ebb059
KW
2143 if (lang) {
2144 for (j = 0; j < trial_locales_count; j++) {
2145 if (strEQ(lang, trial_locales[j])) {
2146 goto done_lang;
2147 }
2148 }
2149 trial_locales[trial_locales_count++] = lang;
2150 }
2151 done_lang:
2152
7d4bcc4a
KW
2153# if defined(WIN32) && defined(LC_ALL)
2154
65ebb059
KW
2155 /* For Windows, we also try the system default locale before "C".
2156 * (If there exists a Windows without LC_ALL we skip this because
2157 * it gets too complicated. For those, the "C" is the next
2158 * fallback possibility). The "" is the same as the 0th element of
2159 * the array, but the code at the loop above knows to treat it
2160 * differently when not the 0th */
2161 trial_locales[trial_locales_count++] = "";
7d4bcc4a
KW
2162
2163# endif
65ebb059
KW
2164
2165 for (j = 0; j < trial_locales_count; j++) {
2166 if (strEQ("C", trial_locales[j])) {
2167 goto done_C;
2168 }
2169 }
2170 trial_locales[trial_locales_count++] = "C";
98994639 2171
65ebb059
KW
2172 done_C: ;
2173 } /* end of first time through the loop */
98994639 2174
7d4bcc4a
KW
2175# ifdef WIN32
2176
65ebb059 2177 next_iteration: ;
7d4bcc4a
KW
2178
2179# endif
65ebb059
KW
2180
2181 } /* end of looping through the trial locales */
2182
2183 if (ok < 1) { /* If we tried to fallback */
2184 const char* msg;
2185 if (! setlocale_failure) { /* fallback succeeded */
2186 msg = "Falling back to";
2187 }
2188 else { /* fallback failed */
e5f10d49 2189 unsigned int j;
98994639 2190
65ebb059
KW
2191 /* We dropped off the end of the loop, so have to decrement i to
2192 * get back to the value the last time through */
2193 i--;
98994639 2194
65ebb059
KW
2195 ok = -1;
2196 msg = "Failed to fall back to";
2197
2198 /* To continue, we should use whatever values we've got */
7d4bcc4a 2199
e5f10d49
KW
2200 for (j = 0; j < NOMINAL_LC_ALL_INDEX; j++) {
2201 Safefree(curlocales[j]);
2202 curlocales[j] = savepv(do_setlocale_r(categories[j], NULL));
2203 DEBUG_LOCALE_INIT(categories[j], NULL, curlocales[j]);
2204 }
65ebb059
KW
2205 }
2206
2207 if (locwarn) {
2208 const char * description;
2209 const char * name = "";
2210 if (strEQ(trial_locales[i], "C")) {
2211 description = "the standard locale";
2212 name = "C";
2213 }
7d4bcc4a
KW
2214
2215# ifdef SYSTEM_DEFAULT_LOCALE
2216
65ebb059
KW
2217 else if (strEQ(trial_locales[i], "")) {
2218 description = "the system default locale";
2219 if (system_default_locale) {
2220 name = system_default_locale;
2221 }
2222 }
7d4bcc4a
KW
2223
2224# endif /* SYSTEM_DEFAULT_LOCALE */
2225
65ebb059
KW
2226 else {
2227 description = "a fallback locale";
2228 name = trial_locales[i];
2229 }
2230 if (name && strNE(name, "")) {
2231 PerlIO_printf(Perl_error_log,
2232 "perl: warning: %s %s (\"%s\").\n", msg, description, name);
2233 }
2234 else {
2235 PerlIO_printf(Perl_error_log,
2236 "perl: warning: %s %s.\n", msg, description);
2237 }
2238 }
2239 } /* End of tried to fallback */
98994639 2240
e5f10d49
KW
2241 /* Done with finding the locales; update our records */
2242
7d4bcc4a
KW
2243# ifdef USE_LOCALE_CTYPE
2244
948523db 2245 new_ctype(curlocales[LC_CTYPE_INDEX]);
98994639 2246
e5f10d49 2247# endif
7d4bcc4a
KW
2248# ifdef USE_LOCALE_COLLATE
2249
948523db 2250 new_collate(curlocales[LC_COLLATE_INDEX]);
98994639 2251
e5f10d49 2252# endif
7d4bcc4a
KW
2253# ifdef USE_LOCALE_NUMERIC
2254
948523db 2255 new_numeric(curlocales[LC_NUMERIC_INDEX]);
e5f10d49
KW
2256
2257# endif
2258
e5f10d49 2259
948523db 2260 for (i = 0; i < NOMINAL_LC_ALL_INDEX; i++) {
e5f10d49
KW
2261 Safefree(curlocales[i]);
2262 }
b310b053 2263
7d4bcc4a
KW
2264# if defined(USE_PERLIO) && defined(USE_LOCALE_CTYPE)
2265
49c85077
KW
2266 /* Set PL_utf8locale to TRUE if using PerlIO _and_ the current LC_CTYPE
2267 * locale is UTF-8. If PL_utf8locale and PL_unicode (set by -C or by
2268 * $ENV{PERL_UNICODE}) are true, perl.c:S_parse_body() will turn on the
2269 * PerlIO :utf8 layer on STDIN, STDOUT, STDERR, _and_ the default open
2270 * discipline. */
c1284011 2271 PL_utf8locale = _is_cur_LC_category_utf8(LC_CTYPE);
49c85077 2272
a05d7ebb 2273 /* Set PL_unicode to $ENV{PERL_UNICODE} if using PerlIO.
fde18df1
JH
2274 This is an alternative to using the -C command line switch
2275 (the -C if present will override this). */
2276 {
dd374669 2277 const char *p = PerlEnv_getenv("PERL_UNICODE");
a05d7ebb 2278 PL_unicode = p ? parse_unicode_opts(&p) : 0;
5a22a2bb
NC
2279 if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
2280 PL_utf8cache = -1;
b310b053
JH
2281 }
2282
7d4bcc4a 2283# endif
7d4bcc4a
KW
2284# ifdef __GLIBC__
2285
175c4cf9 2286 Safefree(language);
7d4bcc4a
KW
2287
2288# endif
175c4cf9
KW
2289
2290 Safefree(lc_all);
2291 Safefree(lang);
2292
e3305790 2293#endif /* USE_LOCALE */
2fcc0ca9 2294#ifdef DEBUGGING
7d4bcc4a 2295
2fcc0ca9 2296 /* So won't continue to output stuff */
27cdc72e 2297 DEBUG_INITIALIZATION_set(FALSE);
7d4bcc4a 2298
2fcc0ca9
KW
2299#endif
2300
98994639
HS
2301 return ok;
2302}
2303
98994639
HS
2304#ifdef USE_LOCALE_COLLATE
2305
a4a439fb 2306char *
a4a439fb
KW
2307Perl__mem_collxfrm(pTHX_ const char *input_string,
2308 STRLEN len, /* Length of 'input_string' */
2309 STRLEN *xlen, /* Set to length of returned string
2310 (not including the collation index
2311 prefix) */
2312 bool utf8 /* Is the input in UTF-8? */
6696cfa7 2313 )
98994639 2314{
a4a439fb
KW
2315
2316 /* _mem_collxfrm() is a bit like strxfrm() but with two important
2317 * differences. First, it handles embedded NULs. Second, it allocates a bit
2318 * more memory than needed for the transformed data itself. The real
55e5378d 2319 * transformed data begins at offset COLLXFRM_HDR_LEN. *xlen is set to
a4a439fb
KW
2320 * the length of that, and doesn't include the collation index size.
2321 * Please see sv_collxfrm() to see how this is used. */
2322
55e5378d
KW
2323#define COLLXFRM_HDR_LEN sizeof(PL_collation_ix)
2324
6696cfa7
KW
2325 char * s = (char *) input_string;
2326 STRLEN s_strlen = strlen(input_string);
79f120c8 2327 char *xbuf = NULL;
55e5378d 2328 STRLEN xAlloc; /* xalloc is a reserved word in VC */
17f41037 2329 STRLEN length_in_chars;
c664130f 2330 bool first_time = TRUE; /* Cleared after first loop iteration */
98994639 2331
a4a439fb
KW
2332 PERL_ARGS_ASSERT__MEM_COLLXFRM;
2333
2334 /* Must be NUL-terminated */
2335 assert(*(input_string + len) == '\0');
7918f24d 2336
79f120c8
KW
2337 /* If this locale has defective collation, skip */
2338 if (PL_collxfrm_base == 0 && PL_collxfrm_mult == 0) {
c7202dee
KW
2339 DEBUG_L(PerlIO_printf(Perl_debug_log,
2340 "_mem_collxfrm: locale's collation is defective\n"));
79f120c8
KW
2341 goto bad;
2342 }
2343
6696cfa7
KW
2344 /* Replace any embedded NULs with the control that sorts before any others.
2345 * This will give as good as possible results on strings that don't
2346 * otherwise contain that character, but otherwise there may be
2347 * less-than-perfect results with that character and NUL. This is
fdc080f3 2348 * unavoidable unless we replace strxfrm with our own implementation. */
fd43f63c
KW
2349 if (UNLIKELY(s_strlen < len)) { /* Only execute if there is an embedded
2350 NUL */
6696cfa7
KW
2351 char * e = s + len;
2352 char * sans_nuls;
fdc080f3 2353 STRLEN sans_nuls_len;
94762aa0 2354 int try_non_controls;
afc4976f
KW
2355 char this_replacement_char[] = "?\0"; /* Room for a two-byte string,
2356 making sure 2nd byte is NUL.
2357 */
2358 STRLEN this_replacement_len;
2359
1e4c9676
KW
2360 /* If we don't know what non-NUL control character sorts lowest for
2361 * this locale, find it */
f28f4d2a 2362 if (PL_strxfrm_NUL_replacement == '\0') {
6696cfa7 2363 int j;
afc4976f 2364 char * cur_min_x = NULL; /* The min_char's xfrm, (except it also
6696cfa7
KW
2365 includes the collation index
2366 prefixed. */
2367
91c0e2e0 2368 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "Looking to replace NUL\n"));
94762aa0
KW
2369
2370 /* Unlikely, but it may be that no control will work to replace
1e4c9676
KW
2371 * NUL, in which case we instead look for any character. Controls
2372 * are preferred because collation order is, in general, context
2373 * sensitive, with adjoining characters affecting the order, and
2374 * controls are less likely to have such interactions, allowing the
2375 * NUL-replacement to stand on its own. (Another way to look at it
2376 * is to imagine what would happen if the NUL were replaced by a
2377 * combining character; it wouldn't work out all that well.) */
94762aa0
KW
2378 for (try_non_controls = 0;
2379 try_non_controls < 2;
2380 try_non_controls++)
2381 {
d4ff9586
KW
2382 /* Look through all legal code points (NUL isn't) */
2383 for (j = 1; j < 256; j++) {
2384 char * x; /* j's xfrm plus collation index */
2385 STRLEN x_len; /* length of 'x' */
2386 STRLEN trial_len = 1;
736a4fed 2387 char cur_source[] = { '\0', '\0' };
d4ff9586 2388
736a4fed
KW
2389 /* Skip non-controls the first time through the loop. The
2390 * controls in a UTF-8 locale are the L1 ones */
afc4976f
KW
2391 if (! try_non_controls && (PL_in_utf8_COLLATE_locale)
2392 ? ! isCNTRL_L1(j)
2393 : ! isCNTRL_LC(j))
2394 {
d4ff9586 2395 continue;
6696cfa7 2396 }
6696cfa7 2397
736a4fed
KW
2398 /* Create a 1-char string of the current code point */
2399 cur_source[0] = (char) j;
2400
d4ff9586
KW
2401 /* Then transform it */
2402 x = _mem_collxfrm(cur_source, trial_len, &x_len,
afc4976f 2403 0 /* The string is not in UTF-8 */);
6696cfa7 2404
1e4c9676 2405 /* Ignore any character that didn't successfully transform.
d4ff9586
KW
2406 * */
2407 if (! x) {
2408 continue;
2409 }
6696cfa7 2410
d4ff9586
KW
2411 /* If this character's transformation is lower than
2412 * the current lowest, this one becomes the lowest */
2413 if ( cur_min_x == NULL
2414 || strLT(x + COLLXFRM_HDR_LEN,
2415 cur_min_x + COLLXFRM_HDR_LEN))
2416 {
f28f4d2a 2417 PL_strxfrm_NUL_replacement = j;
d4ff9586 2418 cur_min_x = x;
d4ff9586
KW
2419 }
2420 else {
2421 Safefree(x);
2422 }
1e4c9676 2423 } /* end of loop through all 255 characters */
6696cfa7 2424
1e4c9676 2425 /* Stop looking if found */
94762aa0
KW
2426 if (cur_min_x) {
2427 break;
2428 }
2429
2430 /* Unlikely, but possible, if there aren't any controls that
2431 * work in the locale, repeat the loop, looking for any
2432 * character that works */
2433 DEBUG_L(PerlIO_printf(Perl_debug_log,
2434 "_mem_collxfrm: No control worked. Trying non-controls\n"));
1e4c9676 2435 } /* End of loop to try first the controls, then any char */
6696cfa7 2436
94762aa0
KW
2437 if (! cur_min_x) {
2438 DEBUG_L(PerlIO_printf(Perl_debug_log,
2439 "_mem_collxfrm: Couldn't find any character to replace"
2440 " embedded NULs in locale %s with", PL_collation_name));
2441 goto bad;
58eebef2
KW
2442 }
2443
94762aa0
KW
2444 DEBUG_L(PerlIO_printf(Perl_debug_log,
2445 "_mem_collxfrm: Replacing embedded NULs in locale %s with "
f28f4d2a 2446 "0x%02X\n", PL_collation_name, PL_strxfrm_NUL_replacement));
94762aa0 2447
6696cfa7 2448 Safefree(cur_min_x);
1e4c9676 2449 } /* End of determining the character that is to replace NULs */
afc4976f
KW
2450
2451 /* If the replacement is variant under UTF-8, it must match the
291a84fb 2452 * UTF8-ness of the original */
f28f4d2a
KW
2453 if ( ! UVCHR_IS_INVARIANT(PL_strxfrm_NUL_replacement) && utf8) {
2454 this_replacement_char[0] =
2455 UTF8_EIGHT_BIT_HI(PL_strxfrm_NUL_replacement);
2456 this_replacement_char[1] =
2457 UTF8_EIGHT_BIT_LO(PL_strxfrm_NUL_replacement);
afc4976f
KW
2458 this_replacement_len = 2;
2459 }
2460 else {
f28f4d2a 2461 this_replacement_char[0] = PL_strxfrm_NUL_replacement;
afc4976f
KW
2462 /* this_replacement_char[1] = '\0' was done at initialization */
2463 this_replacement_len = 1;
6696cfa7
KW
2464 }
2465
2466 /* The worst case length for the replaced string would be if every
2467 * character in it is NUL. Multiply that by the length of each
2468 * replacement, and allow for a trailing NUL */
afc4976f 2469 sans_nuls_len = (len * this_replacement_len) + 1;
fdc080f3 2470 Newx(sans_nuls, sans_nuls_len, char);
6696cfa7
KW
2471 *sans_nuls = '\0';
2472
6696cfa7
KW
2473 /* Replace each NUL with the lowest collating control. Loop until have
2474 * exhausted all the NULs */
2475 while (s + s_strlen < e) {
6069d6c5 2476 my_strlcat(sans_nuls, s, sans_nuls_len);
6696cfa7
KW
2477
2478 /* Do the actual replacement */
6069d6c5 2479 my_strlcat(sans_nuls, this_replacement_char, sans_nuls_len);
6696cfa7
KW
2480
2481 /* Move past the input NUL */
2482 s += s_strlen + 1;
2483 s_strlen = strlen(s);
2484 }
2485
2486 /* And add anything that trails the final NUL */
6069d6c5 2487 my_strlcat(sans_nuls, s, sans_nuls_len);
6696cfa7
KW
2488
2489 /* Switch so below we transform this modified string */
2490 s = sans_nuls;
2491 len = strlen(s);
1e4c9676 2492 } /* End of replacing NULs */
6696cfa7 2493
a4a439fb
KW
2494 /* Make sure the UTF8ness of the string and locale match */
2495 if (utf8 != PL_in_utf8_COLLATE_locale) {
2496 const char * const t = s; /* Temporary so we can later find where the
2497 input was */
2498
2499 /* Here they don't match. Change the string's to be what the locale is
2500 * expecting */
2501
2502 if (! utf8) { /* locale is UTF-8, but input isn't; upgrade the input */
2503 s = (char *) bytes_to_utf8((const U8 *) s, &len);
2504 utf8 = TRUE;
2505 }
2506 else { /* locale is not UTF-8; but input is; downgrade the input */
2507
2508 s = (char *) bytes_from_utf8((const U8 *) s, &len, &utf8);
2509
2510 /* If the downgrade was successful we are done, but if the input
2511 * contains things that require UTF-8 to represent, have to do
2512 * damage control ... */
2513 if (UNLIKELY(utf8)) {
2514
2515 /* What we do is construct a non-UTF-8 string with
2516 * 1) the characters representable by a single byte converted
2517 * to be so (if necessary);
2518 * 2) and the rest converted to collate the same as the
2519 * highest collating representable character. That makes
2520 * them collate at the end. This is similar to how we
2521 * handle embedded NULs, but we use the highest collating
2522 * code point instead of the smallest. Like the NUL case,
2523 * this isn't perfect, but is the best we can reasonably
2524 * do. Every above-255 code point will sort the same as
2525 * the highest-sorting 0-255 code point. If that code
2526 * point can combine in a sequence with some other code
2527 * points for weight calculations, us changing something to
2528 * be it can adversely affect the results. But in most
2529 * cases, it should work reasonably. And note that this is
2530 * really an illegal situation: using code points above 255
2531 * on a locale where only 0-255 are valid. If two strings
2532 * sort entirely equal, then the sort order for the
2533 * above-255 code points will be in code point order. */
2534
2535 utf8 = FALSE;
2536
2537 /* If we haven't calculated the code point with the maximum
2538 * collating order for this locale, do so now */
2539 if (! PL_strxfrm_max_cp) {
2540 int j;
2541
2542 /* The current transformed string that collates the
2543 * highest (except it also includes the prefixed collation
2544 * index. */
2545 char * cur_max_x = NULL;
2546
2547 /* Look through all legal code points (NUL isn't) */
2548 for (j = 1; j < 256; j++) {
2549 char * x;
2550 STRLEN x_len;
736a4fed 2551 char cur_source[] = { '\0', '\0' };
a4a439fb 2552
736a4fed
KW
2553 /* Create a 1-char string of the current code point */
2554 cur_source[0] = (char) j;
a4a439fb
KW
2555
2556 /* Then transform it */
2557 x = _mem_collxfrm(cur_source, 1, &x_len, FALSE);
2558
2559 /* If something went wrong (which it shouldn't), just
2560 * ignore this code point */
94762aa0 2561 if (! x) {
a4a439fb
KW
2562 continue;
2563 }
2564
2565 /* If this character's transformation is higher than
2566 * the current highest, this one becomes the highest */
2567 if ( cur_max_x == NULL
55e5378d
KW
2568 || strGT(x + COLLXFRM_HDR_LEN,
2569 cur_max_x + COLLXFRM_HDR_LEN))
a4a439fb
KW
2570 {
2571 PL_strxfrm_max_cp = j;
2572 cur_max_x = x;
2573 }
2574 else {
2575 Safefree(x);
2576 }
2577 }
2578
94762aa0
KW
2579 if (! cur_max_x) {
2580 DEBUG_L(PerlIO_printf(Perl_debug_log,
2581 "_mem_collxfrm: Couldn't find any character to"
2582 " replace above-Latin1 chars in locale %s with",
2583 PL_collation_name));
2584 goto bad;
2585 }
2586
58eebef2
KW
2587 DEBUG_L(PerlIO_printf(Perl_debug_log,
2588 "_mem_collxfrm: highest 1-byte collating character"
2589 " in locale %s is 0x%02X\n",
2590 PL_collation_name,
2591 PL_strxfrm_max_cp));
58eebef2 2592
a4a439fb
KW
2593 Safefree(cur_max_x);
2594 }
2595
2596 /* Here we know which legal code point collates the highest.
2597 * We are ready to construct the non-UTF-8 string. The length
2598 * will be at least 1 byte smaller than the input string
2599 * (because we changed at least one 2-byte character into a
2600 * single byte), but that is eaten up by the trailing NUL */
2601 Newx(s, len, char);
2602
2603 {
2604 STRLEN i;
2605 STRLEN d= 0;
042d9e50 2606 char * e = (char *) t + len;
a4a439fb
KW
2607
2608 for (i = 0; i < len; i+= UTF8SKIP(t + i)) {
2609 U8 cur_char = t[i];
2610 if (UTF8_IS_INVARIANT(cur_char)) {
2611 s[d++] = cur_char;
2612 }
042d9e50 2613 else if (UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(t + i, e)) {
a4a439fb
KW
2614 s[d++] = EIGHT_BIT_UTF8_TO_NATIVE(cur_char, t[i+1]);
2615 }
2616 else { /* Replace illegal cp with highest collating
2617 one */
2618 s[d++] = PL_strxfrm_max_cp;
2619 }
2620 }
2621 s[d++] = '\0';
2622 Renew(s, d, char); /* Free up unused space */
2623 }
2624 }
2625 }
2626
2627 /* Here, we have constructed a modified version of the input. It could
2628 * be that we already had a modified copy before we did this version.
2629 * If so, that copy is no longer needed */
2630 if (t != input_string) {
2631 Safefree(t);
2632 }
2633 }
2634
17f41037
KW
2635 length_in_chars = (utf8)
2636 ? utf8_length((U8 *) s, (U8 *) s + len)
2637 : len;
2638
59c018b9
KW
2639 /* The first element in the output is the collation id, used by
2640 * sv_collxfrm(); then comes the space for the transformed string. The
2641 * equation should give us a good estimate as to how much is needed */
55e5378d 2642 xAlloc = COLLXFRM_HDR_LEN
a4a439fb 2643 + PL_collxfrm_base
17f41037 2644 + (PL_collxfrm_mult * length_in_chars);
a02a5408 2645 Newx(xbuf, xAlloc, char);
c7202dee
KW
2646 if (UNLIKELY(! xbuf)) {
2647 DEBUG_L(PerlIO_printf(Perl_debug_log,
2648 "_mem_collxfrm: Couldn't malloc %zu bytes\n", xAlloc));
98994639 2649 goto bad;
c7202dee 2650 }
98994639 2651
d35fca5f 2652 /* Store the collation id */
98994639 2653 *(U32*)xbuf = PL_collation_ix;
d35fca5f
KW
2654
2655 /* Then the transformation of the input. We loop until successful, or we
2656 * give up */
4ebeff16 2657 for (;;) {
1adab0a7 2658
55e5378d 2659 *xlen = strxfrm(xbuf + COLLXFRM_HDR_LEN, s, xAlloc - COLLXFRM_HDR_LEN);
4ebeff16
KW
2660
2661 /* If the transformed string occupies less space than we told strxfrm()
2662 * was available, it means it successfully transformed the whole
2663 * string. */
55e5378d 2664 if (*xlen < xAlloc - COLLXFRM_HDR_LEN) {
17f41037 2665
1adab0a7
KW
2666 /* Some systems include a trailing NUL in the returned length.
2667 * Ignore it, using a loop in case multiple trailing NULs are
2668 * returned. */
2669 while ( (*xlen) > 0
2670 && *(xbuf + COLLXFRM_HDR_LEN + (*xlen) - 1) == '\0')
2671 {
2672 (*xlen)--;
2673 }
2674
17f41037
KW
2675 /* If the first try didn't get it, it means our prediction was low.
2676 * Modify the coefficients so that we predict a larger value in any
2677 * future transformations */
2678 if (! first_time) {
2679 STRLEN needed = *xlen + 1; /* +1 For trailing NUL */
2680 STRLEN computed_guess = PL_collxfrm_base
2681 + (PL_collxfrm_mult * length_in_chars);
e1c30f0c
KW
2682
2683 /* On zero-length input, just keep current slope instead of
2684 * dividing by 0 */
2685 const STRLEN new_m = (length_in_chars != 0)
2686 ? needed / length_in_chars
2687 : PL_collxfrm_mult;
17f41037
KW
2688
2689 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
b07929e4
KW
2690 "%s: %d: initial size of %zu bytes for a length "
2691 "%zu string was insufficient, %zu needed\n",
17f41037 2692 __FILE__, __LINE__,
b07929e4 2693 computed_guess, length_in_chars, needed));
17f41037
KW
2694
2695 /* If slope increased, use it, but discard this result for
2696 * length 1 strings, as we can't be sure that it's a real slope
2697 * change */
2698 if (length_in_chars > 1 && new_m > PL_collxfrm_mult) {
7d4bcc4a
KW
2699
2700# ifdef DEBUGGING
2701
17f41037
KW
2702 STRLEN old_m = PL_collxfrm_mult;
2703 STRLEN old_b = PL_collxfrm_base;
7d4bcc4a
KW
2704
2705# endif
2706
17f41037
KW
2707 PL_collxfrm_mult = new_m;
2708 PL_collxfrm_base = 1; /* +1 For trailing NUL */
2709 computed_guess = PL_collxfrm_base
2710 + (PL_collxfrm_mult * length_in_chars);
2711 if (computed_guess < needed) {
2712 PL_collxfrm_base += needed - computed_guess;
2713 }
2714
2715 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
b07929e4
KW
2716 "%s: %d: slope is now %zu; was %zu, base "
2717 "is now %zu; was %zu\n",
17f41037 2718 __FILE__, __LINE__,
b07929e4
KW
2719 PL_collxfrm_mult, old_m,
2720 PL_collxfrm_base, old_b));
17f41037
KW
2721 }
2722 else { /* Slope didn't change, but 'b' did */
2723 const STRLEN new_b = needed
2724 - computed_guess
2725 + PL_collxfrm_base;
2726 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
b07929e4 2727 "%s: %d: base is now %zu; was %zu\n",
17f41037 2728 __FILE__, __LINE__,
b07929e4 2729 new_b, PL_collxfrm_base));
17f41037
KW
2730 PL_collxfrm_base = new_b;
2731 }
2732 }
2733
4ebeff16
KW
2734 break;
2735 }
bb0f664e 2736
c7202dee
KW
2737 if (UNLIKELY(*xlen >= PERL_INT_MAX)) {
2738 DEBUG_L(PerlIO_printf(Perl_debug_log,
2739 "_mem_collxfrm: Needed %zu bytes, max permissible is %u\n",
2740 *xlen, PERL_INT_MAX));
4ebeff16 2741 goto bad;
c7202dee 2742 }
d35fca5f 2743
c664130f 2744 /* A well-behaved strxfrm() returns exactly how much space it needs
1adab0a7
KW
2745 * (usually not including the trailing NUL) when it fails due to not
2746 * enough space being provided. Assume that this is the case unless
2747 * it's been proven otherwise */
c664130f 2748 if (LIKELY(PL_strxfrm_is_behaved) && first_time) {
55e5378d 2749 xAlloc = *xlen + COLLXFRM_HDR_LEN + 1;
c664130f
KW
2750 }
2751 else { /* Here, either:
2752 * 1) The strxfrm() has previously shown bad behavior; or
2753 * 2) It isn't the first time through the loop, which means
2754 * that the strxfrm() is now showing bad behavior, because
2755 * we gave it what it said was needed in the previous
2756 * iteration, and it came back saying it needed still more.
2757 * (Many versions of cygwin fit this. When the buffer size
2758 * isn't sufficient, they return the input size instead of
2759 * how much is needed.)
d4ff9586
KW
2760 * Increase the buffer size by a fixed percentage and try again.
2761 * */
6ddd902c 2762 xAlloc += (xAlloc / 4) + 1;
c664130f 2763 PL_strxfrm_is_behaved = FALSE;
c664130f 2764
7d4bcc4a
KW
2765# ifdef DEBUGGING
2766
58eebef2
KW
2767 if (DEBUG_Lv_TEST || debug_initialization) {
2768 PerlIO_printf(Perl_debug_log,
2769 "_mem_collxfrm required more space than previously calculated"
b07929e4 2770 " for locale %s, trying again with new guess=%d+%zu\n",
58eebef2 2771 PL_collation_name, (int) COLLXFRM_HDR_LEN,
b07929e4 2772 xAlloc - COLLXFRM_HDR_LEN);
58eebef2 2773 }
7d4bcc4a
KW
2774
2775# endif
2776
58eebef2 2777 }
c664130f 2778
4ebeff16 2779 Renew(xbuf, xAlloc, char);
c7202dee
KW
2780 if (UNLIKELY(! xbuf)) {
2781 DEBUG_L(PerlIO_printf(Perl_debug_log,
2782 "_mem_collxfrm: Couldn't realloc %zu bytes\n", xAlloc));
4ebeff16 2783 goto bad;
c7202dee 2784 }
c664130f
KW
2785
2786 first_time = FALSE;
4ebeff16 2787 }
98994639 2788
6696cfa7 2789
7d4bcc4a
KW
2790# ifdef DEBUGGING
2791
58eebef2 2792 if (DEBUG_Lv_TEST || debug_initialization) {
c7202dee
KW
2793
2794 print_collxfrm_input_and_return(s, s + len, xlen, utf8);
2795 PerlIO_printf(Perl_debug_log, "Its xfrm is:");
7e2f38b2
KW
2796 PerlIO_printf(Perl_debug_log, "%s\n",
2797 _byte_dump_string((U8 *) xbuf + COLLXFRM_HDR_LEN,
2798 *xlen, 1));
58eebef2 2799 }
7d4bcc4a
KW
2800
2801# endif
58eebef2 2802
3c5f993e 2803 /* Free up unneeded space; retain ehough for trailing NUL */
55e5378d 2804 Renew(xbuf, COLLXFRM_HDR_LEN + *xlen + 1, char);
98994639 2805
6696cfa7
KW
2806 if (s != input_string) {
2807 Safefree(s);
98994639
HS
2808 }
2809
98994639
HS
2810 return xbuf;
2811
2812 bad:
2813 Safefree(xbuf);
6696cfa7
KW
2814 if (s != input_string) {
2815 Safefree(s);
2816 }
98994639 2817 *xlen = 0;
7d4bcc4a
KW
2818
2819# ifdef DEBUGGING
2820
58eebef2 2821 if (DEBUG_Lv_TEST || debug_initialization) {
c7202dee 2822 print_collxfrm_input_and_return(s, s + len, NULL, utf8);
58eebef2 2823 }
7d4bcc4a
KW
2824
2825# endif
2826
98994639
HS
2827 return NULL;
2828}
2829
7d4bcc4a 2830# ifdef DEBUGGING
c7202dee 2831
4cbaac56 2832STATIC void
c7202dee
KW
2833S_print_collxfrm_input_and_return(pTHX_
2834 const char * const s,
2835 const char * const e,
2836 const STRLEN * const xlen,
2837 const bool is_utf8)
2838{
c7202dee
KW
2839
2840 PERL_ARGS_ASSERT_PRINT_COLLXFRM_INPUT_AND_RETURN;
2841
511e4ff7
DM
2842 PerlIO_printf(Perl_debug_log, "_mem_collxfrm[%" UVuf "]: returning ",
2843 (UV)PL_collation_ix);
c7202dee 2844 if (xlen) {
08b6dc1d 2845 PerlIO_printf(Perl_debug_log, "%zu", *xlen);
c7202dee
KW
2846 }
2847 else {
2848 PerlIO_printf(Perl_debug_log, "NULL");
2849 }
2850 PerlIO_printf(Perl_debug_log, " for locale '%s', string='",
2851 PL_collation_name);
9c8a6dc2
KW
2852 print_bytes_for_locale(s, e, is_utf8);
2853
2854 PerlIO_printf(Perl_debug_log, "'\n");
2855}
2856
2857STATIC void
2858S_print_bytes_for_locale(pTHX_
2859 const char * const s,
2860 const char * const e,
2861 const bool is_utf8)
2862{
2863 const char * t = s;
2864 bool prev_was_printable = TRUE;
2865 bool first_time = TRUE;
2866
2867 PERL_ARGS_ASSERT_PRINT_BYTES_FOR_LOCALE;
c7202dee
KW
2868
2869 while (t < e) {
2870 UV cp = (is_utf8)
2871 ? utf8_to_uvchr_buf((U8 *) t, e, NULL)
2872 : * (U8 *) t;
2873 if (isPRINT(cp)) {
2874 if (! prev_was_printable) {
2875 PerlIO_printf(Perl_debug_log, " ");
2876 }
2877 PerlIO_printf(Perl_debug_log, "%c", (U8) cp);
2878 prev_was_printable = TRUE;
2879 }
2880 else {
2881 if (! first_time) {
2882 PerlIO_printf(Perl_debug_log, " ");
2883 }
147e3846 2884 PerlIO_printf(Perl_debug_log, "%02" UVXf, cp);
c7202dee
KW
2885 prev_was_printable = FALSE;
2886 }
2887 t += (is_utf8) ? UTF8SKIP(t) : 1;
2888 first_time = FALSE;
2889 }
c7202dee
KW
2890}
2891
7d4bcc4a 2892# endif /* #ifdef DEBUGGING */
98994639 2893#endif /* USE_LOCALE_COLLATE */
58eebef2 2894
8ef6e574
KW
2895#ifdef USE_LOCALE
2896
c1284011
KW
2897bool
2898Perl__is_cur_LC_category_utf8(pTHX_ int category)
7d74bb61
KW
2899{
2900 /* Returns TRUE if the current locale for 'category' is UTF-8; FALSE
2901 * otherwise. 'category' may not be LC_ALL. If the platform doesn't have
119ee68b 2902 * nl_langinfo(), nor MB_CUR_MAX, this employs a heuristic, which hence
609548d2
KW
2903 * could give the wrong result. The result will very likely be correct for
2904 * languages that have commonly used non-ASCII characters, but for notably
2905 * English, it comes down to if the locale's name ends in something like
2906 * "UTF-8". It errs on the side of not being a UTF-8 locale. */
7d74bb61 2907
8de4332b 2908 const char *save_input_locale = NULL;
7d74bb61
KW
2909 STRLEN final_pos;
2910
7d4bcc4a
KW
2911# ifdef LC_ALL
2912
7d74bb61 2913 assert(category != LC_ALL);
7d4bcc4a
KW
2914
2915# endif
7d74bb61
KW
2916
2917 /* First dispose of the trivial cases */
837ce802 2918 save_input_locale = do_setlocale_r(category, NULL);
7d74bb61 2919 if (! save_input_locale) {
69014004
KW
2920 DEBUG_L(PerlIO_printf(Perl_debug_log,
2921 "Could not find current locale for category %d\n",
2922 category));
7d74bb61
KW
2923 return FALSE; /* XXX maybe should croak */
2924 }
b07fffd1 2925 save_input_locale = stdize_locale(savepv(save_input_locale));
a39edc4c 2926 if (isNAME_C_OR_POSIX(save_input_locale)) {
69014004
KW
2927 DEBUG_L(PerlIO_printf(Perl_debug_log,
2928 "Current locale for category %d is %s\n",
2929 category, save_input_locale));
b07fffd1 2930 Safefree(save_input_locale);
7d74bb61
KW
2931 return FALSE;
2932 }
2933
7d4bcc4a 2934# if defined(USE_LOCALE_CTYPE) \
1d958db2 2935 && (defined(MB_CUR_MAX) || (defined(HAS_NL_LANGINFO) && defined(CODESET)))
7d74bb61 2936
1d958db2 2937 { /* Next try nl_langinfo or MB_CUR_MAX if available */
7d74bb61
KW
2938
2939 char *save_ctype_locale = NULL;
119ee68b 2940 bool is_utf8;
7d74bb61 2941
119ee68b 2942 if (category != LC_CTYPE) { /* These work only on LC_CTYPE */
7d74bb61
KW
2943
2944 /* Get the current LC_CTYPE locale */
837ce802 2945 save_ctype_locale = do_setlocale_c(LC_CTYPE, NULL);
7d74bb61 2946 if (! save_ctype_locale) {
69014004
KW
2947 DEBUG_L(PerlIO_printf(Perl_debug_log,
2948 "Could not find current locale for LC_CTYPE\n"));
7d74bb61
KW
2949 goto cant_use_nllanginfo;
2950 }
4f72bb37 2951 save_ctype_locale = stdize_locale(savepv(save_ctype_locale));
7d74bb61
KW
2952
2953 /* If LC_CTYPE and the desired category use the same locale, this
2954 * means that finding the value for LC_CTYPE is the same as finding
2955 * the value for the desired category. Otherwise, switch LC_CTYPE
2956 * to the desired category's locale */
2957 if (strEQ(save_ctype_locale, save_input_locale)) {
2958 Safefree(save_ctype_locale);
2959 save_ctype_locale = NULL;
2960 }
837ce802 2961 else if (! do_setlocale_c(LC_CTYPE, save_input_locale)) {
69014004
KW
2962 DEBUG_L(PerlIO_printf(Perl_debug_log,
2963 "Could not change LC_CTYPE locale to %s\n",
2964 save_input_locale));
7d74bb61
KW
2965 Safefree(save_ctype_locale);
2966 goto cant_use_nllanginfo;
2967 }
2968 }
2969
69014004
KW
2970 DEBUG_L(PerlIO_printf(Perl_debug_log, "Current LC_CTYPE locale=%s\n",
2971 save_input_locale));
2972
7d74bb61 2973 /* Here the current LC_CTYPE is set to the locale of the category whose
1d958db2
KW
2974 * information is desired. This means that nl_langinfo() and MB_CUR_MAX
2975 * should give the correct results */
119ee68b 2976
7d4bcc4a
KW
2977# if defined(HAS_NL_LANGINFO) && defined(CODESET)
2978
291a84fb 2979 { /* The task is easiest if the platform has this POSIX 2001 function */
c70a3e68
KW
2980 const char *codeset = my_nl_langinfo(PERL_CODESET, FALSE);
2981 /* FALSE => already in dest locale */
119ee68b 2982
c70a3e68
KW
2983 DEBUG_L(PerlIO_printf(Perl_debug_log,
2984 "\tnllanginfo returned CODESET '%s'\n", codeset));
2985
2986 if (codeset && strNE(codeset, "")) {
1d958db2
KW
2987 /* If we switched LC_CTYPE, switch back */
2988 if (save_ctype_locale) {
837ce802 2989 do_setlocale_c(LC_CTYPE, save_ctype_locale);
1d958db2
KW
2990 Safefree(save_ctype_locale);
2991 }
2992
abc1d81d
KW
2993 is_utf8 = ( ( strlen(codeset) == STRLENs("UTF-8")
2994 && foldEQ(codeset, STR_WITH_LEN("UTF-8")))
2995 || ( strlen(codeset) == STRLENs("UTF8")
2996 && foldEQ(codeset, STR_WITH_LEN("UTF8"))));
1d958db2 2997
69014004
KW
2998 DEBUG_L(PerlIO_printf(Perl_debug_log,
2999 "\tnllanginfo returned CODESET '%s'; ?UTF8 locale=%d\n",
3000 codeset, is_utf8));
1d958db2
KW
3001 Safefree(save_input_locale);
3002 return is_utf8;
3003 }
119ee68b
KW
3004 }
3005
7d4bcc4a
KW
3006# endif
3007# ifdef MB_CUR_MAX
1d958db2
KW
3008
3009 /* Here, either we don't have nl_langinfo, or it didn't return a
3010 * codeset. Try MB_CUR_MAX */
3011
119ee68b
KW
3012 /* Standard UTF-8 needs at least 4 bytes to represent the maximum
3013 * Unicode code point. Since UTF-8 is the only non-single byte
3014 * encoding we handle, we just say any such encoding is UTF-8, and if
3015 * turns out to be wrong, other things will fail */
5f7616bd 3016 is_utf8 = (unsigned) MB_CUR_MAX >= STRLENs(MAX_UNICODE_UTF8);
119ee68b 3017
69014004
KW
3018 DEBUG_L(PerlIO_printf(Perl_debug_log,
3019 "\tMB_CUR_MAX=%d; ?UTF8 locale=%d\n",
3020 (int) MB_CUR_MAX, is_utf8));
3021
119ee68b
KW
3022 Safefree(save_input_locale);
3023
7d4bcc4a 3024# ifdef HAS_MBTOWC
119ee68b
KW
3025
3026 /* ... But, most system that have MB_CUR_MAX will also have mbtowc(),
3027 * since they are both in the C99 standard. We can feed a known byte
3028 * string to the latter function, and check that it gives the expected
3029 * result */
3030 if (is_utf8) {
3031 wchar_t wc;
51fc4b19
KW
3032 int len;
3033
856b881c 3034 PERL_UNUSED_RESULT(mbtowc(&wc, NULL, 0));/* Reset any shift state */
69014004 3035 errno = 0;
b1d4925c 3036 len = mbtowc(&wc, STR_WITH_LEN(REPLACEMENT_CHARACTER_UTF8));
51fc4b19 3037
b1d4925c
KW
3038
3039 if ( len != STRLENs(REPLACEMENT_CHARACTER_UTF8)
5579633c 3040 || wc != (wchar_t) UNICODE_REPLACEMENT)
119ee68b
KW
3041 {
3042 is_utf8 = FALSE;
b1d4925c
KW
3043 DEBUG_L(PerlIO_printf(Perl_debug_log, "\replacement=U+%x\n",
3044 (unsigned int)wc));
69014004
KW
3045 DEBUG_L(PerlIO_printf(Perl_debug_log,
3046 "\treturn from mbtowc=%d; errno=%d; ?UTF8 locale=0\n",
51fc4b19 3047 len, errno));
119ee68b
KW
3048 }
3049 }
7d4bcc4a
KW
3050
3051# endif
119ee68b 3052
1d958db2
KW
3053 /* If we switched LC_CTYPE, switch back */
3054 if (save_ctype_locale) {
837ce802 3055 do_setlocale_c(LC_CTYPE, save_ctype_locale);
1d958db2 3056 Safefree(save_ctype_locale);
119ee68b 3057 }
7d74bb61 3058
1d958db2 3059 return is_utf8;
7d4bcc4a
KW
3060
3061# endif
3062
7d74bb61 3063 }
119ee68b 3064
7d74bb61
KW
3065 cant_use_nllanginfo:
3066
7d4bcc4a 3067# else /* nl_langinfo should work if available, so don't bother compiling this
0080c90a
KW
3068 fallback code. The final fallback of looking at the name is
3069 compiled, and will be executed if nl_langinfo fails */
7d74bb61 3070
97f4de96
KW
3071 /* nl_langinfo not available or failed somehow. Next try looking at the
3072 * currency symbol to see if it disambiguates things. Often that will be
3073 * in the native script, and if the symbol isn't in UTF-8, we know that the
3074 * locale isn't. If it is non-ASCII UTF-8, we infer that the locale is
609548d2
KW
3075 * too, as the odds of a non-UTF8 string being valid UTF-8 are quite small
3076 * */
fa9b773e 3077
7d4bcc4a
KW
3078# ifdef HAS_LOCALECONV
3079# ifdef USE_LOCALE_MONETARY
3080
fa9b773e
KW
3081 {
3082 char *save_monetary_locale = NULL;
fa9b773e 3083 bool only_ascii = FALSE;
13542a67
KW
3084 bool is_utf8 = FALSE;
3085 struct lconv* lc;
fa9b773e 3086
97f4de96
KW
3087 /* Like above for LC_CTYPE, we first set LC_MONETARY to the locale of
3088 * the desired category, if it isn't that locale already */
3089
fa9b773e
KW
3090 if (category != LC_MONETARY) {
3091
837ce802 3092 save_monetary_locale = do_setlocale_c(LC_MONETARY, NULL);
fa9b773e 3093 if (! save_monetary_locale) {
69014004
KW
3094 DEBUG_L(PerlIO_printf(Perl_debug_log,
3095 "Could not find current locale for LC_MONETARY\n"));
fa9b773e
KW
3096 goto cant_use_monetary;
3097 }
4f72bb37 3098 save_monetary_locale = stdize_locale(savepv(save_monetary_locale));
fa9b773e 3099
13542a67
KW
3100 if (strEQ(save_monetary_locale, save_input_locale)) {
3101 Safefree(save_monetary_locale);
3102 save_monetary_locale = NULL;
3103 }
837ce802 3104 else if (! do_setlocale_c(LC_MONETARY, save_input_locale)) {
59c234b4
KW
3105 DEBUG_L(PerlIO_printf(Perl_debug_log,
3106 "Could not change LC_MONETARY locale to %s\n",
3107 save_input_locale));
3108 Safefree(save_monetary_locale);
3109 goto cant_use_monetary;
fa9b773e
KW
3110 }
3111 }
3112
3113 /* Here the current LC_MONETARY is set to the locale of the category
3114 * whose information is desired. */
3115
13542a67
KW
3116 lc = localeconv();
3117 if (! lc
3118 || ! lc->currency_symbol
c5f058df 3119 || is_utf8_invariant_string((U8 *) lc->currency_symbol, 0))
13542a67
KW
3120 {
3121 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));
3122 only_ascii = TRUE;
3123 }
3124 else {
3125 is_utf8 = is_utf8_string((U8 *) lc->currency_symbol, 0);
fa9b773e
KW
3126 }
3127
3128 /* If we changed it, restore LC_MONETARY to its original locale */
3129 if (save_monetary_locale) {
837ce802 3130 do_setlocale_c(LC_MONETARY, save_monetary_locale);
fa9b773e
KW
3131 Safefree(save_monetary_locale);
3132 }
3133
13542a67 3134 if (! only_ascii) {
fa9b773e 3135
59c234b4
KW
3136 /* It isn't a UTF-8 locale if the symbol is not legal UTF-8;
3137 * otherwise assume the locale is UTF-8 if and only if the symbol
3138 * is non-ascii UTF-8. */
3139 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?Currency symbol for %s is UTF-8=%d\n",
3140 save_input_locale, is_utf8));
3141 Safefree(save_input_locale);
3142 return is_utf8;
13542a67 3143 }
fa9b773e
KW
3144 }
3145 cant_use_monetary:
3146
7d4bcc4a
KW
3147# endif /* USE_LOCALE_MONETARY */
3148# endif /* HAS_LOCALECONV */
fa9b773e 3149
7d4bcc4a 3150# if defined(HAS_STRFTIME) && defined(USE_LOCALE_TIME)
15f7e74e
KW
3151
3152/* Still haven't found a non-ASCII string to disambiguate UTF-8 or not. Try
3153 * the names of the months and weekdays, timezone, and am/pm indicator */
3154 {
3155 char *save_time_locale = NULL;
3156 int hour = 10;
3157 bool is_dst = FALSE;
3158 int dom = 1;
3159 int month = 0;
3160 int i;
3161 char * formatted_time;
3162
3163
3164 /* Like above for LC_MONETARY, we set LC_TIME to the locale of the
3165 * desired category, if it isn't that locale already */
3166
3167 if (category != LC_TIME) {
3168
837ce802 3169 save_time_locale = do_setlocale_c(LC_TIME, NULL);
15f7e74e
KW
3170 if (! save_time_locale) {
3171 DEBUG_L(PerlIO_printf(Perl_debug_log,
3172 "Could not find current locale for LC_TIME\n"));
3173 goto cant_use_time;
3174 }
3175 save_time_locale = stdize_locale(savepv(save_time_locale));
3176
3177 if (strEQ(save_time_locale, save_input_locale)) {
3178 Safefree(save_time_locale);
3179 save_time_locale = NULL;
3180 }
837ce802 3181 else if (! do_setlocale_c(LC_TIME, save_input_locale)) {
15f7e74e
KW
3182 DEBUG_L(PerlIO_printf(Perl_debug_log,
3183 "Could not change LC_TIME locale to %s\n",
3184 save_input_locale));
3185 Safefree(save_time_locale);
3186 goto cant_use_time;
3187 }
3188 }
3189
3190 /* Here the current LC_TIME is set to the locale of the category
3191 * whose information is desired. Look at all the days of the week and
9f10db87 3192 * month names, and the timezone and am/pm indicator for UTF-8 variant
15f7e74e
KW
3193 * characters. The first such a one found will tell us if the locale
3194 * is UTF-8 or not */
3195
3196 for (i = 0; i < 7 + 12; i++) { /* 7 days; 12 months */
3197 formatted_time = my_strftime("%A %B %Z %p",
3ae5cd07 3198 0, 0, hour, dom, month, 2012 - 1900, 0, 0, is_dst);
c5f058df
KW
3199 if ( ! formatted_time
3200 || is_utf8_invariant_string((U8 *) formatted_time, 0))
3201 {
15f7e74e
KW
3202
3203 /* Here, we didn't find a non-ASCII. Try the next time through
3204 * with the complemented dst and am/pm, and try with the next
3205 * weekday. After we have gotten all weekdays, try the next
3206 * month */
3207 is_dst = ! is_dst;
3208 hour = (hour + 12) % 24;
3209 dom++;
3210 if (i > 6) {
3211 month++;
3212 }
3213 continue;
3214 }
3215
3216 /* Here, we have a non-ASCII. Return TRUE is it is valid UTF8;
3217 * false otherwise. But first, restore LC_TIME to its original
3218 * locale if we changed it */
3219 if (save_time_locale) {
837ce802 3220 do_setlocale_c(LC_TIME, save_time_locale);
15f7e74e
KW
3221 Safefree(save_time_locale);
3222 }
3223
3224 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?time-related strings for %s are UTF-8=%d\n",
3225 save_input_locale,
3226 is_utf8_string((U8 *) formatted_time, 0)));
3227 Safefree(save_input_locale);
3228 return is_utf8_string((U8 *) formatted_time, 0);
3229 }
3230
3231 /* Falling off the end of the loop indicates all the names were just
3232 * ASCII. Go on to the next test. If we changed it, restore LC_TIME
3233 * to its original locale */
3234 if (save_time_locale) {
837ce802 3235 do_setlocale_c(LC_TIME, save_time_locale);
15f7e74e
KW
3236 Safefree(save_time_locale);
3237 }
3238 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));
3239 }
3240 cant_use_time:
3241
7d4bcc4a 3242# endif
15f7e74e 3243
7d4bcc4a 3244# if 0 && defined(USE_LOCALE_MESSAGES) && defined(HAS_SYS_ERRLIST)
855aeb93
JH
3245
3246/* This code is ifdefd out because it was found to not be necessary in testing
5857e934
KW
3247 * on our dromedary test machine, which has over 700 locales. There, this
3248 * added no value to looking at the currency symbol and the time strings. I
3249 * left it in so as to avoid rewriting it if real-world experience indicates
3250 * that dromedary is an outlier. Essentially, instead of returning abpve if we
855aeb93
JH
3251 * haven't found illegal utf8, we continue on and examine all the strerror()
3252 * messages on the platform for utf8ness. If all are ASCII, we still don't
3253 * know the answer; but otherwise we have a pretty good indication of the
5857e934
KW
3254 * utf8ness. The reason this doesn't help much is that the messages may not
3255 * have been translated into the locale. The currency symbol and time strings
3256 * are much more likely to have been translated. */
3257 {
855aeb93 3258 int e;
5857e934
KW
3259 bool is_utf8 = FALSE;
3260 bool non_ascii = FALSE;
855aeb93 3261 char *save_messages_locale = NULL;
5857e934 3262 const char * errmsg = NULL;
855aeb93 3263
5857e934
KW
3264 /* Like above, we set LC_MESSAGES to the locale of the desired
3265 * category, if it isn't that locale already */
855aeb93
JH
3266
3267 if (category != LC_MESSAGES) {
3268
837ce802 3269 save_messages_locale = do_setlocale_c(LC_MESSAGES, NULL);
855aeb93 3270 if (! save_messages_locale) {
5857e934
KW
3271 DEBUG_L(PerlIO_printf(Perl_debug_log,
3272 "Could not find current locale for LC_MESSAGES\n"));
855aeb93
JH
3273 goto cant_use_messages;
3274 }
5857e934 3275 save_messages_locale = stdize_locale(savepv(save_messages_locale));
855aeb93
JH
3276
3277 if (strEQ(save_messages_locale, save_input_locale)) {
5857e934
KW
3278 Safefree(save_messages_locale);
3279 save_messages_locale = NULL;
855aeb93 3280 }
837ce802 3281 else if (! do_setlocale_c(LC_MESSAGES, save_input_locale)) {
5857e934
KW
3282 DEBUG_L(PerlIO_printf(Perl_debug_log,
3283 "Could not change LC_MESSAGES locale to %s\n",
3284 save_input_locale));
855aeb93
JH
3285 Safefree(save_messages_locale);
3286 goto cant_use_messages;
3287 }
3288 }
3289
3290 /* Here the current LC_MESSAGES is set to the locale of the category
5857e934
KW
3291 * whose information is desired. Look through all the messages. We
3292 * can't use Strerror() here because it may expand to code that
3293 * segfaults in miniperl */
855aeb93 3294
5857e934
KW
3295 for (e = 0; e <= sys_nerr; e++) {
3296 errno = 0;
3297 errmsg = sys_errlist[e];
3298 if (errno || !errmsg) {
855aeb93
JH
3299 break;
3300 }
5857e934 3301 errmsg = savepv(errmsg);
c5f058df 3302 if (! is_utf8_invariant_string((U8 *) errmsg, 0)) {
5857e934
KW
3303 non_ascii = TRUE;
3304 is_utf8 = is_utf8_string((U8 *) errmsg, 0);
3305 break;
855aeb93
JH
3306 }
3307 }
5857e934 3308 Safefree(errmsg);
855aeb93
JH
3309
3310 /* And, if we changed it, restore LC_MESSAGES to its original locale */
3311 if (save_messages_locale) {
837ce802 3312 do_setlocale_c(LC_MESSAGES, save_messages_locale);
855aeb93
JH
3313 Safefree(save_messages_locale);
3314 }
3315
5857e934
KW
3316 if (non_ascii) {
3317
3318 /* Any non-UTF-8 message means not a UTF-8 locale; if all are valid,
3319 * any non-ascii means it is one; otherwise we assume it isn't */
3320 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?error messages for %s are UTF-8=%d\n",
3321 save_input_locale,
3322 is_utf8));
3323 Safefree(save_input_locale);
3324 return is_utf8;
3325 }
855aeb93 3326
5857e934 3327 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
3328 }
3329 cant_use_messages:
3330
7d4bcc4a
KW
3331# endif
3332# endif /* the code that is compiled when no nl_langinfo */
0080c90a 3333
7d4bcc4a 3334# ifndef EBCDIC /* On os390, even if the name ends with "UTF-8', it isn't a
92c0a900 3335 UTF-8 locale */
7d4bcc4a 3336
97f4de96
KW
3337 /* As a last resort, look at the locale name to see if it matches
3338 * qr/UTF -? * 8 /ix, or some other common locale names. This "name", the
3339 * return of setlocale(), is actually defined to be opaque, so we can't
3340 * really rely on the absence of various substrings in the name to indicate
3341 * its UTF-8ness, but if it has UTF8 in the name, it is extremely likely to
3342 * be a UTF-8 locale. Similarly for the other common names */
3343
3344 final_pos = strlen(save_input_locale) - 1;
3345 if (final_pos >= 3) {
8de4332b 3346 const char *name = save_input_locale;
97f4de96
KW
3347
3348 /* Find next 'U' or 'u' and look from there */
3349 while ((name += strcspn(name, "Uu") + 1)
3350 <= save_input_locale + final_pos - 2)
3351 {
c72493e0 3352 if ( isALPHA_FOLD_NE(*name, 't')
305b8651 3353 || isALPHA_FOLD_NE(*(name + 1), 'f'))
97f4de96
KW
3354 {
3355 continue;
3356 }
3357 name += 2;
3358 if (*(name) == '-') {
3359 if ((name > save_input_locale + final_pos - 1)) {
3360 break;
3361 }
3362 name++;
3363 }
3364 if (*(name) == '8') {
97f4de96
KW
3365 DEBUG_L(PerlIO_printf(Perl_debug_log,
3366 "Locale %s ends with UTF-8 in name\n",
3367 save_input_locale));
00c54b9c 3368 Safefree(save_input_locale);
97f4de96
KW
3369 return TRUE;
3370 }
3371 }
3372 DEBUG_L(PerlIO_printf(Perl_debug_log,
3373 "Locale %s doesn't end with UTF-8 in name\n",
3374 save_input_locale));
3375 }
3376
7d4bcc4a
KW
3377# endif
3378# ifdef WIN32
3379
97f4de96 3380 /* http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756.aspx */
8a0832a1 3381 if (memENDs(save_input_locale, final_pos, "65001")) {
97f4de96 3382 DEBUG_L(PerlIO_printf(Perl_debug_log,
8a0832a1 3383 "Locale %s ends with 65001 in name, is UTF-8 locale\n",
97f4de96
KW
3384 save_input_locale));
3385 Safefree(save_input_locale);
3386 return TRUE;
3387 }
7d4bcc4a
KW
3388
3389# endif
97f4de96
KW
3390
3391 /* Other common encodings are the ISO 8859 series, which aren't UTF-8. But
3392 * since we are about to return FALSE anyway, there is no point in doing
3393 * this extra work */
7d4bcc4a
KW
3394
3395# if 0
97f4de96
KW
3396 if (instr(save_input_locale, "8859")) {
3397 DEBUG_L(PerlIO_printf(Perl_debug_log,
3398 "Locale %s has 8859 in name, not UTF-8 locale\n",
3399 save_input_locale));
3400 Safefree(save_input_locale);
3401 return FALSE;
3402 }
7d4bcc4a 3403# endif
97f4de96 3404
69014004
KW
3405 DEBUG_L(PerlIO_printf(Perl_debug_log,
3406 "Assuming locale %s is not a UTF-8 locale\n",
3407 save_input_locale));
fa9b773e 3408 Safefree(save_input_locale);
7d74bb61
KW
3409 return FALSE;
3410}
3411
8ef6e574 3412#endif
7d74bb61 3413
d6ded950
KW
3414
3415bool
3416Perl__is_in_locale_category(pTHX_ const bool compiling, const int category)
3417{
1a4f13e1 3418 dVAR;
d6ded950
KW
3419 /* Internal function which returns if we are in the scope of a pragma that
3420 * enables the locale category 'category'. 'compiling' should indicate if
3421 * this is during the compilation phase (TRUE) or not (FALSE). */
3422
3423 const COP * const cop = (compiling) ? &PL_compiling : PL_curcop;
3424
3425 SV *categories = cop_hints_fetch_pvs(cop, "locale", 0);
3426 if (! categories || categories == &PL_sv_placeholder) {
3427 return FALSE;
3428 }
3429
3430 /* The pseudo-category 'not_characters' is -1, so just add 1 to each to get
3431 * a valid unsigned */
3432 assert(category >= -1);
3433 return cBOOL(SvUV(categories) & (1U << (category + 1)));
3434}
3435
2c6ee1a7 3436char *
6ebbc862
KW
3437Perl_my_strerror(pTHX_ const int errnum)
3438{
3439 /* Returns a mortalized copy of the text of the error message associated
3440 * with 'errnum'. It uses the current locale's text unless the platform
3441 * doesn't have the LC_MESSAGES category or we are not being called from
3442 * within the scope of 'use locale'. In the former case, it uses whatever
3443 * strerror returns; in the latter case it uses the text from the C locale.
3444 *
3445 * The function just calls strerror(), but temporarily switches, if needed,
3446 * to the C locale */
3447
3448 char *errstr;
52770946 3449 dVAR;
6ebbc862 3450
52770946 3451#ifndef USE_LOCALE_MESSAGES
6ebbc862 3452
52770946
KW
3453 /* If platform doesn't have messages category, we don't do any switching to
3454 * the C locale; we just use whatever strerror() returns */
3455
3456 errstr = savepv(Strerror(errnum));
3457
3458#else /* Has locale messages */
3459
3460 const bool within_locale_scope = IN_LC(LC_MESSAGES);
2c6ee1a7 3461
7aaa36b1
KW
3462# if defined(HAS_POSIX_2008_LOCALE) && defined(HAS_STRERROR_L)
3463
43cb6651
KW
3464 /* This function is trivial if we don't have to worry about thread safety
3465 * and have strerror_l(), as it handles the switch of locales so we don't
3466 * have to deal with that. We don't have to worry about thread safety if
3467 * this is an unthreaded build, or if strerror_r() is also available. Both
3468 * it and strerror_l() are thread-safe. Plain strerror() isn't thread
3469 * safe. But on threaded builds when strerror_r() is available, the
3470 * apparent call to strerror() below is actually a macro that
3471 * behind-the-scenes calls strerror_r().
3472 */
3473
3474# if ! defined(USE_ITHREADS) || defined(HAS_STRERROR_R)
7aaa36b1
KW
3475
3476 if (within_locale_scope) {
4eb27fc5 3477 errstr = savepv(strerror(errnum));
7aaa36b1
KW
3478 }
3479 else {
4eb27fc5 3480 errstr = savepv(strerror_l(errnum, PL_C_locale_obj));
7aaa36b1
KW
3481 }
3482
43cb6651
KW
3483# else
3484
3485 /* Here we have strerror_l(), but not strerror_r() and we are on a
3486 * threaded-build. We use strerror_l() for everything, constructing a
3487 * locale to pass to it if necessary */
3488
3489 bool do_free = FALSE;
3490 locale_t locale_to_use;
3491
3492 if (within_locale_scope) {
3493 locale_to_use = uselocale((locale_t) 0);
3494 if (locale_to_use == LC_GLOBAL_LOCALE) {
3495 locale_to_use = duplocale(LC_GLOBAL_LOCALE);
3496 do_free = TRUE;
3497 }
3498 }
3499 else { /* Use C locale if not within 'use locale' scope */
3500 locale_to_use = PL_C_locale_obj;
3501 }
3502
3503 errstr = savepv(strerror_l(errnum, locale_to_use));
3504
3505 if (do_free) {
3506 freelocale(locale_to_use);
3507 }
3508
3509# endif
3510# else /* Doesn't have strerror_l() */
7aaa36b1
KW
3511
3512# ifdef USE_POSIX_2008_LOCALE
3513
fcd0e682 3514 locale_t save_locale = NULL;
7aaa36b1
KW
3515
3516# else
3517
8de4332b 3518 const char * save_locale = NULL;
c9dda6da 3519 bool locale_is_C = FALSE;
2c6ee1a7 3520
6ebbc862
KW
3521 /* We have a critical section to prevent another thread from changing the
3522 * locale out from under us (or zapping the buffer returned from
3523 * setlocale() ) */
3524 LOCALE_LOCK;
3525
7aaa36b1 3526# endif
6ebbc862 3527
9c8a6dc2
KW
3528 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3529 "my_strerror called with errnum %d\n", errnum));
6ebbc862 3530 if (! within_locale_scope) {
c9dda6da 3531 errno = 0;
a0b53297 3532
f1d2176b 3533# ifdef USE_POSIX_2008_LOCALE /* Use the thread-safe locale functions */
6ebbc862 3534
9c8a6dc2
KW
3535 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3536 "Not within locale scope, about to call"
3537 " uselocale(0x%p)\n", PL_C_locale_obj));
6ebbc862 3538 save_locale = uselocale(PL_C_locale_obj);
c9dda6da
KW
3539 if (! save_locale) {
3540 DEBUG_L(PerlIO_printf(Perl_debug_log,
9c8a6dc2
KW
3541 "uselocale failed, errno=%d\n", errno));
3542 }
3543 else {
3544 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3545 "uselocale returned 0x%p\n", save_locale));
c9dda6da 3546 }
6ebbc862 3547
7aaa36b1 3548# else /* Not thread-safe build */
a0b53297 3549
837ce802 3550 save_locale = do_setlocale_c(LC_MESSAGES, NULL);
c9dda6da
KW
3551 if (! save_locale) {
3552 DEBUG_L(PerlIO_printf(Perl_debug_log,
3553 "setlocale failed, errno=%d\n", errno));
3554 }
3555 else {
3556 locale_is_C = isNAME_C_OR_POSIX(save_locale);
2c6ee1a7 3557
c9dda6da
KW
3558 /* Switch to the C locale if not already in it */
3559 if (! locale_is_C) {
2c6ee1a7 3560
c9dda6da
KW
3561 /* The setlocale() just below likely will zap 'save_locale', so
3562 * create a copy. */
3563 save_locale = savepv(save_locale);
837ce802 3564 do_setlocale_c(LC_MESSAGES, "C");
c9dda6da 3565 }
6ebbc862 3566 }
2c6ee1a7 3567
7aaa36b1 3568# endif
2c6ee1a7 3569
6ebbc862 3570 } /* end of ! within_locale_scope */
9c8a6dc2
KW
3571 else {
3572 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s: %d: WITHIN locale scope\n",
3573 __FILE__, __LINE__));
3574 }
a0b53297 3575
9c8a6dc2
KW
3576 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3577 "Any locale change has been done; about to call Strerror\n"));
52770946 3578 errstr = savepv(Strerror(errnum));
6ebbc862
KW
3579
3580 if (! within_locale_scope) {
c9dda6da 3581 errno = 0;
a0b53297 3582
f1d2176b 3583# ifdef USE_POSIX_2008_LOCALE
6ebbc862 3584
9c8a6dc2
KW
3585 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3586 "%s: %d: not within locale scope, restoring the locale\n",
3587 __FILE__, __LINE__));
c9dda6da
KW
3588 if (save_locale && ! uselocale(save_locale)) {
3589 DEBUG_L(PerlIO_printf(Perl_debug_log,
3590 "uselocale restore failed, errno=%d\n", errno));
3591 }
2c6ee1a7 3592 }
6ebbc862 3593
7aaa36b1 3594# else
6ebbc862 3595
c9dda6da 3596 if (save_locale && ! locale_is_C) {
837ce802 3597 if (! do_setlocale_c(LC_MESSAGES, save_locale)) {
c9dda6da
KW
3598 DEBUG_L(PerlIO_printf(Perl_debug_log,
3599 "setlocale restore failed, errno=%d\n", errno));
3600 }
6ebbc862
KW
3601 Safefree(save_locale);
3602 }
3603 }
3604
3605 LOCALE_UNLOCK;
3606
7aaa36b1
KW
3607# endif
3608# endif /* End of doesn't have strerror_l */
52770946 3609#endif /* End of does have locale messages */
6affbbf0
KW
3610
3611#ifdef DEBUGGING
3612
3613 if (DEBUG_Lv_TEST) {
3614 PerlIO_printf(Perl_debug_log, "Strerror returned; saving a copy: '");
3615 print_bytes_for_locale(errstr, errstr + strlen(errstr), 0);
3616 PerlIO_printf(Perl_debug_log, "'\n");
3617 }
3618
2c6ee1a7
KW
3619#endif
3620
52770946 3621 SAVEFREEPV(errstr);
6ebbc862 3622 return errstr;
2c6ee1a7
KW
3623}
3624
66610fdd 3625/*
747c467a 3626
747c467a
KW
3627=for apidoc sync_locale
3628
3629Changing the program's locale should be avoided by XS code. Nevertheless,
3630certain non-Perl libraries called from XS, such as C<Gtk> do so. When this
3631happens, Perl needs to be told that the locale has changed. Use this function
3632to do so, before returning to Perl.
3633
3634=cut
3635*/
3636
3637void
3638Perl_sync_locale(pTHX)
3639{
9f82ea3e 3640 char * newlocale;
747c467a
KW
3641
3642#ifdef USE_LOCALE_CTYPE
7d4bcc4a 3643
9f82ea3e
KW
3644 newlocale = do_setlocale_c(LC_CTYPE, NULL);
3645 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3646 "%s:%d: %s\n", __FILE__, __LINE__,
3647 setlocale_debug_string(LC_CTYPE, NULL, newlocale)));
3648 new_ctype(newlocale);
747c467a 3649
7d4bcc4a 3650#endif /* USE_LOCALE_CTYPE */
747c467a 3651#ifdef USE_LOCALE_COLLATE
7d4bcc4a 3652
9f82ea3e
KW
3653 newlocale = do_setlocale_c(LC_COLLATE, NULL);
3654 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3655 "%s:%d: %s\n", __FILE__, __LINE__,
3656 setlocale_debug_string(LC_COLLATE, NULL, newlocale)));
3657 new_collate(newlocale);
747c467a 3658
7d4bcc4a 3659#endif
747c467a 3660#ifdef USE_LOCALE_NUMERIC
7d4bcc4a 3661
9f82ea3e
KW
3662 newlocale = do_setlocale_c(LC_NUMERIC, NULL);
3663 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3664 "%s:%d: %s\n", __FILE__, __LINE__,
3665 setlocale_debug_string(LC_NUMERIC, NULL, newlocale)));
3666 new_numeric(newlocale);
7d4bcc4a 3667
747c467a
KW
3668#endif /* USE_LOCALE_NUMERIC */
3669
3670}
3671
5d1187d1
KW
3672#if defined(DEBUGGING) && defined(USE_LOCALE)
3673
a4f00dcc
KW
3674STATIC char *
3675S_setlocale_debug_string(const int category, /* category number,
5d1187d1
KW
3676 like LC_ALL */
3677 const char* const locale, /* locale name */
3678
3679 /* return value from setlocale() when attempting to
3680 * set 'category' to 'locale' */
3681 const char* const retval)
3682{
3683 /* Returns a pointer to a NUL-terminated string in static storage with
3684 * added text about the info passed in. This is not thread safe and will
3685 * be overwritten by the next call, so this should be used just to
fa07b8e5 3686 * formulate a string to immediately print or savepv() on. */
5d1187d1 3687
398a990f
DM
3688 /* initialise to a non-null value to keep it out of BSS and so keep
3689 * -DPERL_GLOBAL_STRUCT_PRIVATE happy */
60b45a7d
KW
3690 static char ret[128] = "If you can read this, thank your buggy C"
3691 " library strlcpy(), and change your hints file"
3692 " to undef it";
7d4bcc4a 3693
e5f10d49 3694 my_strlcpy(ret, "setlocale(", sizeof(ret));
b09aaf40 3695 my_strlcat(ret, category_name(category), sizeof(ret));
fa07b8e5 3696 my_strlcat(ret, ", ", sizeof(ret));
5d1187d1
KW
3697
3698 if (locale) {
fa07b8e5
KW
3699 my_strlcat(ret, "\"", sizeof(ret));
3700 my_strlcat(ret, locale, sizeof(ret));
3701 my_strlcat(ret, "\"", sizeof(ret));
5d1187d1
KW
3702 }
3703 else {
fa07b8e5 3704 my_strlcat(ret, "NULL", sizeof(ret));
5d1187d1
KW
3705 }
3706
fa07b8e5 3707 my_strlcat(ret, ") returned ", sizeof(ret));
5d1187d1
KW
3708
3709 if (retval) {
fa07b8e5
KW
3710 my_strlcat(ret, "\"", sizeof(ret));
3711 my_strlcat(ret, retval, sizeof(ret));
3712 my_strlcat(ret, "\"", sizeof(ret));
5d1187d1
KW
3713 }
3714 else {
fa07b8e5 3715 my_strlcat(ret, "NULL", sizeof(ret));
5d1187d1
KW
3716 }
3717
3718 assert(strlen(ret) < sizeof(ret));
3719
3720 return ret;
3721}
3722
3723#endif
747c467a
KW
3724
3725
3726/*
14d04a33 3727 * ex: set ts=8 sts=4 sw=4 et:
37442d52 3728 */