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