This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
locale.c: Fix some debugging so will output during init
[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
KW
25 *
26 * All C programs have an underlying locale. Perl generally doesn't pay any
27 * attention to it except within the scope of a 'use locale'. For most
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
39#include "perl.h"
40
b310b053
JH
41#ifdef I_LANGINFO
42# include <langinfo.h>
43#endif
44
a4af207c
JH
45#include "reentr.h"
46
2fcc0ca9
KW
47/* If the environment says to, we can output debugging information during
48 * initialization. This is done before option parsing, and before any thread
49 * creation, so can be a file-level static */
50#ifdef DEBUGGING
51static bool debug_initialization = FALSE;
52#endif
53
8ef6e574
KW
54#ifdef USE_LOCALE
55
98994639 56/*
0d071d52
KW
57 * Standardize the locale name from a string returned by 'setlocale', possibly
58 * modifying that string.
98994639 59 *
0ef2a2b2 60 * The typical return value of setlocale() is either
98994639
HS
61 * (1) "xx_YY" if the first argument of setlocale() is not LC_ALL
62 * (2) "xa_YY xb_YY ..." if the first argument of setlocale() is LC_ALL
63 * (the space-separated values represent the various sublocales,
0ef2a2b2 64 * in some unspecified order). This is not handled by this function.
98994639
HS
65 *
66 * In some platforms it has a form like "LC_SOMETHING=Lang_Country.866\n",
0ef2a2b2
KW
67 * which is harmful for further use of the string in setlocale(). This
68 * function removes the trailing new line and everything up through the '='
98994639
HS
69 *
70 */
71STATIC char *
72S_stdize_locale(pTHX_ char *locs)
73{
7452cf6a 74 const char * const s = strchr(locs, '=');
98994639
HS
75 bool okay = TRUE;
76
7918f24d
NC
77 PERL_ARGS_ASSERT_STDIZE_LOCALE;
78
8772537c
AL
79 if (s) {
80 const char * const t = strchr(s, '.');
98994639 81 okay = FALSE;
8772537c
AL
82 if (t) {
83 const char * const u = strchr(t, '\n');
84 if (u && (u[1] == 0)) {
85 const STRLEN len = u - s;
86 Move(s + 1, locs, len, char);
87 locs[len] = 0;
88 okay = TRUE;
98994639
HS
89 }
90 }
91 }
92
93 if (!okay)
94 Perl_croak(aTHX_ "Can't fix broken locale name \"%s\"", locs);
95
96 return locs;
97}
98
8ef6e574
KW
99#endif
100
98994639
HS
101void
102Perl_set_numeric_radix(pTHX)
103{
104#ifdef USE_LOCALE_NUMERIC
105# ifdef HAS_LOCALECONV
7452cf6a 106 const struct lconv* const lc = localeconv();
98994639 107
98994639
HS
108 if (lc && lc->decimal_point) {
109 if (lc->decimal_point[0] == '.' && lc->decimal_point[1] == 0) {
110 SvREFCNT_dec(PL_numeric_radix_sv);
a0714e2c 111 PL_numeric_radix_sv = NULL;
98994639
HS
112 }
113 else {
114 if (PL_numeric_radix_sv)
115 sv_setpv(PL_numeric_radix_sv, lc->decimal_point);
116 else
117 PL_numeric_radix_sv = newSVpv(lc->decimal_point, 0);
9f10db87 118 if (! is_invariant_string((U8 *) lc->decimal_point, 0)
28acfe03 119 && is_utf8_string((U8 *) lc->decimal_point, 0)
c1284011 120 && _is_cur_LC_category_utf8(LC_NUMERIC))
28acfe03
KW
121 {
122 SvUTF8_on(PL_numeric_radix_sv);
123 }
98994639
HS
124 }
125 }
126 else
a0714e2c 127 PL_numeric_radix_sv = NULL;
69014004 128
2fcc0ca9
KW
129#ifdef DEBUGGING
130 if (DEBUG_L_TEST || debug_initialization) {
131 PerlIO_printf(Perl_debug_log, "Locale radix is '%s', ?UTF-8=%d\n",
69014004 132 (PL_numeric_radix_sv)
37b7e435
KW
133 ? SvPVX(PL_numeric_radix_sv)
134 : "NULL",
135 (PL_numeric_radix_sv)
39eb7305 136 ? cBOOL(SvUTF8(PL_numeric_radix_sv))
2fcc0ca9
KW
137 : 0);
138 }
139#endif
69014004 140
98994639
HS
141# endif /* HAS_LOCALECONV */
142#endif /* USE_LOCALE_NUMERIC */
143}
144
a39edc4c
KW
145/* Is the C string input 'name' "C" or "POSIX"? If so, and 'name' is the
146 * return of setlocale(), then this is extremely likely to be the C or POSIX
147 * locale. However, the output of setlocale() is documented to be opaque, but
148 * the odds are extremely small that it would return these two strings for some
149 * other locale. Note that VMS in these two locales includes many non-ASCII
150 * characters as controls and punctuation (below are hex bytes):
151 * cntrl: 00-1F 7F 84-97 9B-9F
152 * 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
153 * Oddly, none there are listed as alphas, though some represent alphabetics
154 * http://www.nntp.perl.org/group/perl.perl5.porters/2013/02/msg198753.html */
98b630b3
KW
155#define isNAME_C_OR_POSIX(name) ((name) != NULL \
156 && ((*(name) == 'C' && (*(name + 1)) == '\0') \
a39edc4c
KW
157 || strEQ((name), "POSIX")))
158
98994639 159void
8772537c 160Perl_new_numeric(pTHX_ const char *newnum)
98994639
HS
161{
162#ifdef USE_LOCALE_NUMERIC
0d071d52
KW
163
164 /* Called after all libc setlocale() calls affecting LC_NUMERIC, to tell
165 * core Perl this and that 'newnum' is the name of the new locale.
166 * It installs this locale as the current underlying default.
167 *
168 * The default locale and the C locale can be toggled between by use of the
169 * set_numeric_local() and set_numeric_standard() functions, which should
170 * probably not be called directly, but only via macros like
171 * SET_NUMERIC_STANDARD() in perl.h.
172 *
173 * The toggling is necessary mainly so that a non-dot radix decimal point
174 * character can be output, while allowing internal calculations to use a
175 * dot.
176 *
177 * This sets several interpreter-level variables:
bb304765 178 * PL_numeric_name The underlying locale's name: a copy of 'newnum'
0d071d52 179 * PL_numeric_local A boolean indicating if the toggled state is such
7738054c
KW
180 * that the current locale is the program's underlying
181 * locale
182 * PL_numeric_standard An int indicating if the toggled state is such
183 * that the current locale is the C locale. If non-zero,
184 * it is in C; if > 1, it means it may not be toggled away
185 * from C.
0d071d52
KW
186 * Note that both of the last two variables can be true at the same time,
187 * if the underlying locale is C. (Toggling is a no-op under these
188 * circumstances.)
189 *
190 * Any code changing the locale (outside this file) should use
191 * POSIX::setlocale, which calls this function. Therefore this function
192 * should be called directly only from this file and from
193 * POSIX::setlocale() */
194
b03f34cf 195 char *save_newnum;
98994639
HS
196
197 if (! newnum) {
43c5f42d
NC
198 Safefree(PL_numeric_name);
199 PL_numeric_name = NULL;
98994639
HS
200 PL_numeric_standard = TRUE;
201 PL_numeric_local = TRUE;
202 return;
203 }
204
b03f34cf 205 save_newnum = stdize_locale(savepv(newnum));
abe1abcf
KW
206
207 PL_numeric_standard = isNAME_C_OR_POSIX(save_newnum);
208 PL_numeric_local = TRUE;
209
b03f34cf 210 if (! PL_numeric_name || strNE(PL_numeric_name, save_newnum)) {
98994639 211 Safefree(PL_numeric_name);
b03f34cf 212 PL_numeric_name = save_newnum;
b03f34cf 213 }
abe1abcf
KW
214 else {
215 Safefree(save_newnum);
216 }
4c28b29c
KW
217
218 /* Keep LC_NUMERIC in the C locale. This is for XS modules, so they don't
219 * have to worry about the radix being a non-dot. (Core operations that
220 * need the underlying locale change to it temporarily). */
221 set_numeric_standard();
222
e19f01cb 223 set_numeric_radix();
6959d69d 224
f2ce9e1c
JH
225#else
226 PERL_UNUSED_ARG(newnum);
98994639
HS
227#endif /* USE_LOCALE_NUMERIC */
228}
229
230void
231Perl_set_numeric_standard(pTHX)
232{
233#ifdef USE_LOCALE_NUMERIC
28c1bf33
KW
234 /* Toggle the LC_NUMERIC locale to C. Most code should use the macros like
235 * SET_NUMERIC_STANDARD() in perl.h instead of calling this directly. The
236 * macro avoids calling this routine if toggling isn't necessary according
237 * to our records (which could be wrong if some XS code has changed the
238 * locale behind our back) */
0d071d52 239
a9b8c0d8
KW
240 setlocale(LC_NUMERIC, "C");
241 PL_numeric_standard = TRUE;
242 PL_numeric_local = isNAME_C_OR_POSIX(PL_numeric_name);
243 set_numeric_radix();
2fcc0ca9
KW
244#ifdef DEBUGGING
245 if (DEBUG_L_TEST || debug_initialization) {
246 PerlIO_printf(Perl_debug_log,
247 "Underlying LC_NUMERIC locale now is C\n");
248 }
249#endif
98994639
HS
250
251#endif /* USE_LOCALE_NUMERIC */
252}
253
254void
255Perl_set_numeric_local(pTHX)
256{
257#ifdef USE_LOCALE_NUMERIC
28c1bf33
KW
258 /* Toggle the LC_NUMERIC locale to the current underlying default. Most
259 * code should use the macros like SET_NUMERIC_LOCAL() in perl.h instead of
260 * calling this directly. The macro avoids calling this routine if
261 * toggling isn't necessary according to our records (which could be wrong
262 * if some XS code has changed the locale behind our back) */
a9b8c0d8
KW
263
264 setlocale(LC_NUMERIC, PL_numeric_name);
265 PL_numeric_standard = isNAME_C_OR_POSIX(PL_numeric_name);
266 PL_numeric_local = TRUE;
267 set_numeric_radix();
2fcc0ca9
KW
268#ifdef DEBUGGING
269 if (DEBUG_L_TEST || debug_initialization) {
270 PerlIO_printf(Perl_debug_log,
69014004 271 "Underlying LC_NUMERIC locale now is %s\n",
2fcc0ca9
KW
272 PL_numeric_name);
273 }
274#endif
98994639
HS
275
276#endif /* USE_LOCALE_NUMERIC */
277}
278
279/*
280 * Set up for a new ctype locale.
281 */
282void
8772537c 283Perl_new_ctype(pTHX_ const char *newctype)
98994639
HS
284{
285#ifdef USE_LOCALE_CTYPE
0d071d52
KW
286
287 /* Called after all libc setlocale() calls affecting LC_CTYPE, to tell
288 * core Perl this and that 'newctype' is the name of the new locale.
289 *
290 * This function sets up the folding arrays for all 256 bytes, assuming
291 * that tofold() is tolc() since fold case is not a concept in POSIX,
292 *
293 * Any code changing the locale (outside this file) should use
294 * POSIX::setlocale, which calls this function. Therefore this function
295 * should be called directly only from this file and from
296 * POSIX::setlocale() */
297
27da23d5 298 dVAR;
68067e4e 299 UV i;
98994639 300
7918f24d
NC
301 PERL_ARGS_ASSERT_NEW_CTYPE;
302
215c5139
KW
303 /* We will replace any bad locale warning with 1) nothing if the new one is
304 * ok; or 2) a new warning for the bad new locale */
305 if (PL_warn_locale) {
306 SvREFCNT_dec_NN(PL_warn_locale);
307 PL_warn_locale = NULL;
308 }
309
c1284011 310 PL_in_utf8_CTYPE_locale = _is_cur_LC_category_utf8(LC_CTYPE);
31f05a37
KW
311
312 /* A UTF-8 locale gets standard rules. But note that code still has to
313 * handle this specially because of the three problematic code points */
314 if (PL_in_utf8_CTYPE_locale) {
315 Copy(PL_fold_latin1, PL_fold_locale, 256, U8);
316 }
317 else {
8c6180a9
KW
318 /* Assume enough space for every character being bad. 4 spaces each
319 * for the 94 printable characters that are output like "'x' "; and 5
320 * spaces each for "'\\' ", "'\t' ", and "'\n' "; plus a terminating
321 * NUL */
322 char bad_chars_list[ (94 * 4) + (3 * 5) + 1 ];
323
324 bool check_for_problems = ckWARN_d(WARN_LOCALE); /* No warnings means
325 no check */
326 bool multi_byte_locale = FALSE; /* Assume is a single-byte locale
327 to start */
328 unsigned int bad_count = 0; /* Count of bad characters */
329
baa60164
KW
330 for (i = 0; i < 256; i++) {
331 if (isUPPER_LC((U8) i))
332 PL_fold_locale[i] = (U8) toLOWER_LC((U8) i);
333 else if (isLOWER_LC((U8) i))
334 PL_fold_locale[i] = (U8) toUPPER_LC((U8) i);
335 else
336 PL_fold_locale[i] = (U8) i;
8c6180a9
KW
337
338 /* If checking for locale problems, see if the native ASCII-range
339 * printables plus \n and \t are in their expected categories in
340 * the new locale. If not, this could mean big trouble, upending
341 * Perl's and most programs' assumptions, like having a
342 * metacharacter with special meaning become a \w. Fortunately,
343 * it's very rare to find locales that aren't supersets of ASCII
344 * nowadays. It isn't a problem for most controls to be changed
345 * into something else; we check only \n and \t, though perhaps \r
346 * could be an issue as well. */
347 if (check_for_problems
348 && (isGRAPH_A(i) || isBLANK_A(i) || i == '\n'))
349 {
350 if ((isALPHANUMERIC_A(i) && ! isALPHANUMERIC_LC(i))
351 || (isPUNCT_A(i) && ! isPUNCT_LC(i))
352 || (isBLANK_A(i) && ! isBLANK_LC(i))
353 || (i == '\n' && ! isCNTRL_LC(i)))
354 {
355 if (bad_count) { /* Separate multiple entries with a
356 blank */
357 bad_chars_list[bad_count++] = ' ';
358 }
359 bad_chars_list[bad_count++] = '\'';
360 if (isPRINT_A(i)) {
361 bad_chars_list[bad_count++] = (char) i;
362 }
363 else {
364 bad_chars_list[bad_count++] = '\\';
365 if (i == '\n') {
366 bad_chars_list[bad_count++] = 'n';
367 }
368 else {
369 assert(i == '\t');
370 bad_chars_list[bad_count++] = 't';
371 }
372 }
373 bad_chars_list[bad_count++] = '\'';
374 bad_chars_list[bad_count] = '\0';
375 }
376 }
377 }
378
379#ifdef MB_CUR_MAX
380 /* We only handle single-byte locales (outside of UTF-8 ones; so if
d35fca5f 381 * this locale requires more than one byte, there are going to be
8c6180a9 382 * problems. */
ba1a4362
KW
383 if (check_for_problems && MB_CUR_MAX > 1
384
385 /* Some platforms return MB_CUR_MAX > 1 for even the "C"
386 * locale. Just assume that the implementation for them (plus
387 * for POSIX) is correct and the > 1 value is spurious. (Since
388 * these are specially handled to never be considered UTF-8
389 * locales, as long as this is the only problem, everything
390 * should work fine */
391 && strNE(newctype, "C") && strNE(newctype, "POSIX"))
392 {
8c6180a9
KW
393 multi_byte_locale = TRUE;
394 }
395#endif
396
397 if (bad_count || multi_byte_locale) {
780fcc9f 398 PL_warn_locale = Perl_newSVpvf(aTHX_
8c6180a9 399 "Locale '%s' may not work well.%s%s%s\n",
780fcc9f 400 newctype,
8c6180a9
KW
401 (multi_byte_locale)
402 ? " Some characters in it are not recognized by"
403 " Perl."
404 : "",
405 (bad_count)
406 ? "\nThe following characters (and maybe others)"
407 " may not have the same meaning as the Perl"
408 " program expects:\n"
409 : "",
410 (bad_count)
411 ? bad_chars_list
412 : ""
413 );
780fcc9f
KW
414 /* If we are actually in the scope of the locale, output the
415 * message now. Otherwise we save it to be output at the first
416 * operation using this locale, if that actually happens. Most
417 * programs don't use locales, so they are immune to bad ones */
418 if (IN_LC(LC_CTYPE)) {
419
420 /* We have to save 'newctype' because the setlocale() just
421 * below may destroy it. The next setlocale() further down
422 * should restore it properly so that the intermediate change
423 * here is transparent to this function's caller */
424 const char * const badlocale = savepv(newctype);
425
426 setlocale(LC_CTYPE, "C");
427
428 /* The '0' below suppresses a bogus gcc compiler warning */
429 Perl_warner(aTHX_ packWARN(WARN_LOCALE), SvPVX(PL_warn_locale), 0);
430 setlocale(LC_CTYPE, badlocale);
c0f3a893 431 Safefree(badlocale);
780fcc9f
KW
432 SvREFCNT_dec_NN(PL_warn_locale);
433 PL_warn_locale = NULL;
434 }
baa60164 435 }
31f05a37 436 }
98994639
HS
437
438#endif /* USE_LOCALE_CTYPE */
7918f24d 439 PERL_ARGS_ASSERT_NEW_CTYPE;
8772537c 440 PERL_UNUSED_ARG(newctype);
96a5add6 441 PERL_UNUSED_CONTEXT;
98994639
HS
442}
443
98994639 444void
2726666d
KW
445Perl__warn_problematic_locale()
446{
2726666d
KW
447
448#ifdef USE_LOCALE_CTYPE
449
5f04a188
KW
450 dTHX;
451
452 /* Internal-to-core function that outputs the message in PL_warn_locale,
453 * and then NULLS it. Should be called only through the macro
454 * _CHECK_AND_WARN_PROBLEMATIC_LOCALE */
455
2726666d
KW
456 if (PL_warn_locale) {
457 /*GCC_DIAG_IGNORE(-Wformat-security); Didn't work */
458 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
459 SvPVX(PL_warn_locale),
460 0 /* dummy to avoid compiler warning */ );
461 /* GCC_DIAG_RESTORE; */
462 SvREFCNT_dec_NN(PL_warn_locale);
463 PL_warn_locale = NULL;
464 }
465
466#endif
467
468}
469
470void
8772537c 471Perl_new_collate(pTHX_ const char *newcoll)
98994639
HS
472{
473#ifdef USE_LOCALE_COLLATE
0d071d52
KW
474
475 /* Called after all libc setlocale() calls affecting LC_COLLATE, to tell
476 * core Perl this and that 'newcoll' is the name of the new locale.
477 *
478 * Any code changing the locale (outside this file) should use
479 * POSIX::setlocale, which calls this function. Therefore this function
480 * should be called directly only from this file and from
d35fca5f
KW
481 * POSIX::setlocale().
482 *
483 * The design of locale collation is that every locale change is given an
484 * index 'PL_collation_ix'. The first time a string particpates in an
485 * operation that requires collation while locale collation is active, it
486 * is given PERL_MAGIC_collxfrm magic (via sv_collxfrm_flags()). That
487 * magic includes the collation index, and the transformation of the string
488 * by strxfrm(), q.v. That transformation is used when doing comparisons,
489 * instead of the string itself. If a string changes, the magic is
490 * cleared. The next time the locale changes, the index is incremented,
491 * and so we know during a comparison that the transformation is not
492 * necessarily still valid, and so is recomputed. Note that if the locale
493 * changes enough times, the index could wrap (a U32), and it is possible
494 * that a transformation would improperly be considered valid, leading to
495 * an unlikely bug */
0d071d52 496
98994639
HS
497 if (! newcoll) {
498 if (PL_collation_name) {
499 ++PL_collation_ix;
500 Safefree(PL_collation_name);
501 PL_collation_name = NULL;
502 }
503 PL_collation_standard = TRUE;
00bf60ca 504 is_standard_collation:
98994639
HS
505 PL_collxfrm_base = 0;
506 PL_collxfrm_mult = 2;
165a1c52 507 PL_in_utf8_COLLATE_locale = FALSE;
6696cfa7 508 *PL_strxfrm_min_char = '\0';
a4a439fb 509 PL_strxfrm_max_cp = 0;
98994639
HS
510 return;
511 }
512
d35fca5f 513 /* If this is not the same locale as currently, set the new one up */
98994639
HS
514 if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
515 ++PL_collation_ix;
516 Safefree(PL_collation_name);
517 PL_collation_name = stdize_locale(savepv(newcoll));
a39edc4c 518 PL_collation_standard = isNAME_C_OR_POSIX(newcoll);
00bf60ca
KW
519 if (PL_collation_standard) {
520 goto is_standard_collation;
521 }
98994639 522
165a1c52 523 PL_in_utf8_COLLATE_locale = _is_cur_LC_category_utf8(LC_COLLATE);
6696cfa7 524 *PL_strxfrm_min_char = '\0';
a4a439fb 525 PL_strxfrm_max_cp = 0;
165a1c52 526
59c018b9
KW
527 /* A locale collation definition includes primary, secondary, tertiary,
528 * etc. weights for each character. To sort, the primary weights are
529 * used, and only if they compare equal, then the secondary weights are
530 * used, and only if they compare equal, then the tertiary, etc.
531 *
532 * strxfrm() works by taking the input string, say ABC, and creating an
533 * output transformed string consisting of first the primary weights,
534 * A¹B¹C¹ followed by the secondary ones, A²B²C²; and then the
535 * tertiary, etc, yielding A¹B¹C¹ A²B²C² A³B³C³ .... Some characters
536 * may not have weights at every level. In our example, let's say B
537 * doesn't have a tertiary weight, and A doesn't have a secondary
538 * weight. The constructed string is then going to be
539 * A¹B¹C¹ B²C² A³C³ ....
540 * This has the desired effect that strcmp() will look at the secondary
541 * or tertiary weights only if the strings compare equal at all higher
542 * priority weights. The spaces shown here, like in
543 * "A¹B¹C¹ * A²B²C² "
544 * are not just for readability. In the general case, these must
545 * actually be bytes, which we will call here 'separator weights'; and
546 * they must be smaller than any other weight value, but since these
547 * are C strings, only the terminating one can be a NUL (some
548 * implementations may include a non-NUL separator weight just before
549 * the NUL). Implementations tend to reserve 01 for the separator
550 * weights. They are needed so that a shorter string's secondary
551 * weights won't be misconstrued as primary weights of a longer string,
552 * etc. By making them smaller than any other weight, the shorter
553 * string will sort first. (Actually, if all secondary weights are
554 * smaller than all primary ones, there is no need for a separator
555 * weight between those two levels, etc.)
556 *
557 * The length of the transformed string is roughly a linear function of
558 * the input string. It's not exactly linear because some characters
559 * don't have weights at all levels. When we call strxfrm() we have to
560 * allocate some memory to hold the transformed string. The
561 * calculations below try to find coefficients 'm' and 'b' for this
562 * locale so that m*x + b equals how much space we need, given the size
563 * of the input string in 'x'. If we calculate too small, we increase
564 * the size as needed, and call strxfrm() again, but it is better to
565 * get it right the first time to avoid wasted expensive string
566 * transformations. */
567
98994639 568 {
79f120c8
KW
569 /* We use the string below to find how long the tranformation of it
570 * is. Almost all locales are supersets of ASCII, or at least the
571 * ASCII letters. We use all of them, half upper half lower,
572 * because if we used fewer, we might hit just the ones that are
573 * outliers in a particular locale. Most of the strings being
574 * collated will contain a preponderance of letters, and even if
575 * they are above-ASCII, they are likely to have the same number of
576 * weight levels as the ASCII ones. It turns out that digits tend
577 * to have fewer levels, and some punctuation has more, but those
578 * are relatively sparse in text, and khw believes this gives a
579 * reasonable result, but it could be changed if experience so
580 * dictates. */
581 const char longer[] = "ABCDEFGHIJKLMnopqrstuvwxyz";
582 char * x_longer; /* Transformed 'longer' */
583 Size_t x_len_longer; /* Length of 'x_longer' */
584
585 char * x_shorter; /* We also transform a substring of 'longer' */
586 Size_t x_len_shorter;
587
a4a439fb 588 /* _mem_collxfrm() is used get the transformation (though here we
79f120c8
KW
589 * are interested only in its length). It is used because it has
590 * the intelligence to handle all cases, but to work, it needs some
591 * values of 'm' and 'b' to get it started. For the purposes of
592 * this calculation we use a very conservative estimate of 'm' and
593 * 'b'. This assumes a weight can be multiple bytes, enough to
594 * hold any UV on the platform, and there are 5 levels, 4 weight
595 * bytes, and a trailing NUL. */
596 PL_collxfrm_base = 5;
597 PL_collxfrm_mult = 5 * sizeof(UV);
598
599 /* Find out how long the transformation really is */
a4a439fb
KW
600 x_longer = _mem_collxfrm(longer,
601 sizeof(longer) - 1,
602 &x_len_longer,
603
604 /* We avoid converting to UTF-8 in the
605 * called function by telling it the
606 * string is in UTF-8 if the locale is a
607 * UTF-8 one. Since the string passed
608 * here is invariant under UTF-8, we can
609 * claim it's UTF-8 even though it isn't.
610 * */
611 PL_in_utf8_COLLATE_locale);
79f120c8
KW
612 Safefree(x_longer);
613
614 /* Find out how long the transformation of a substring of 'longer'
615 * is. Together the lengths of these transformations are
616 * sufficient to calculate 'm' and 'b'. The substring is all of
617 * 'longer' except the first character. This minimizes the chances
618 * of being swayed by outliers */
a4a439fb 619 x_shorter = _mem_collxfrm(longer + 1,
79f120c8 620 sizeof(longer) - 2,
a4a439fb
KW
621 &x_len_shorter,
622 PL_in_utf8_COLLATE_locale);
79f120c8
KW
623 Safefree(x_shorter);
624
625 /* If the results are nonsensical for this simple test, the whole
626 * locale definition is suspect. Mark it so that locale collation
627 * is not active at all for it. XXX Should we warn? */
628 if ( x_len_shorter == 0
629 || x_len_longer == 0
630 || x_len_shorter >= x_len_longer)
631 {
632 PL_collxfrm_mult = 0;
633 PL_collxfrm_base = 0;
634 }
635 else {
636 SSize_t base; /* Temporary */
637
638 /* We have both: m * strlen(longer) + b = x_len_longer
639 * m * strlen(shorter) + b = x_len_shorter;
640 * subtracting yields:
641 * m * (strlen(longer) - strlen(shorter))
642 * = x_len_longer - x_len_shorter
643 * But we have set things up so that 'shorter' is 1 byte smaller
644 * than 'longer'. Hence:
645 * m = x_len_longer - x_len_shorter
646 *
647 * But if something went wrong, make sure the multiplier is at
648 * least 1.
649 */
650 if (x_len_longer > x_len_shorter) {
651 PL_collxfrm_mult = (STRLEN) x_len_longer - x_len_shorter;
652 }
653 else {
654 PL_collxfrm_mult = 1;
655 }
656
657 /* mx + b = len
658 * so: b = len - mx
659 * but in case something has gone wrong, make sure it is
660 * non-negative */
661 base = x_len_longer - PL_collxfrm_mult * (sizeof(longer) - 1);
662 if (base < 0) {
663 base = 0;
664 }
665
666 /* Add 1 for the trailing NUL */
667 PL_collxfrm_base = base + 1;
668 }
98994639
HS
669 }
670 }
671
f2ce9e1c
JH
672#else
673 PERL_UNUSED_ARG(newcoll);
98994639
HS
674#endif /* USE_LOCALE_COLLATE */
675}
676
b385bb4d
KW
677#ifdef WIN32
678
679char *
680Perl_my_setlocale(pTHX_ int category, const char* locale)
681{
682 /* This, for Windows, emulates POSIX setlocale() behavior. There is no
683 * difference unless the input locale is "", which means on Windows to get
684 * the machine default, which is set via the computer's "Regional and
685 * Language Options" (or its current equivalent). In POSIX, it instead
686 * means to find the locale from the user's environment. This routine
687 * looks in the environment, and, if anything is found, uses that instead
688 * of going to the machine default. If there is no environment override,
689 * the machine default is used, as normal, by calling the real setlocale()
690 * with "". The POSIX behavior is to use the LC_ALL variable if set;
691 * otherwise to use the particular category's variable if set; otherwise to
692 * use the LANG variable. */
693
175c4cf9 694 bool override_LC_ALL = FALSE;
89f7b9aa
KW
695 char * result;
696
b385bb4d
KW
697 if (locale && strEQ(locale, "")) {
698# ifdef LC_ALL
699 locale = PerlEnv_getenv("LC_ALL");
700 if (! locale) {
701#endif
702 switch (category) {
703# ifdef LC_ALL
704 case LC_ALL:
481465ea 705 override_LC_ALL = TRUE;
b385bb4d
KW
706 break; /* We already know its variable isn't set */
707# endif
708# ifdef USE_LOCALE_TIME
709 case LC_TIME:
710 locale = PerlEnv_getenv("LC_TIME");
711 break;
712# endif
713# ifdef USE_LOCALE_CTYPE
714 case LC_CTYPE:
715 locale = PerlEnv_getenv("LC_CTYPE");
716 break;
717# endif
718# ifdef USE_LOCALE_COLLATE
719 case LC_COLLATE:
720 locale = PerlEnv_getenv("LC_COLLATE");
721 break;
722# endif
723# ifdef USE_LOCALE_MONETARY
724 case LC_MONETARY:
725 locale = PerlEnv_getenv("LC_MONETARY");
726 break;
727# endif
728# ifdef USE_LOCALE_NUMERIC
729 case LC_NUMERIC:
730 locale = PerlEnv_getenv("LC_NUMERIC");
731 break;
732# endif
733# ifdef USE_LOCALE_MESSAGES
734 case LC_MESSAGES:
735 locale = PerlEnv_getenv("LC_MESSAGES");
736 break;
737# endif
738 default:
739 /* This is a category, like PAPER_SIZE that we don't
740 * know about; and so can't provide a wrapper. */
741 break;
742 }
743 if (! locale) {
744 locale = PerlEnv_getenv("LANG");
481465ea 745 if (! locale) {
b385bb4d
KW
746 locale = "";
747 }
748 }
749# ifdef LC_ALL
750 }
751# endif
752 }
753
89f7b9aa 754 result = setlocale(category, locale);
bbc98134
KW
755 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n", __FILE__, __LINE__,
756 _setlocale_debug_string(category, locale, result)));
89f7b9aa 757
481465ea 758 if (! override_LC_ALL) {
89f7b9aa
KW
759 return result;
760 }
761
dfd77d7a 762 /* Here the input category was LC_ALL, and we have set it to what is in the
481465ea
KW
763 * LANG variable or the system default if there is no LANG. But these have
764 * lower priority than the other LC_foo variables, so override it for each
765 * one that is set. (If they are set to "", it means to use the same thing
766 * we just set LC_ALL to, so can skip) */
89f7b9aa
KW
767# ifdef USE_LOCALE_TIME
768 result = PerlEnv_getenv("LC_TIME");
730252b2 769 if (result && strNE(result, "")) {
89f7b9aa 770 setlocale(LC_TIME, result);
bbc98134
KW
771 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
772 __FILE__, __LINE__,
773 _setlocale_debug_string(LC_TIME, result, "not captured")));
89f7b9aa
KW
774 }
775# endif
776# ifdef USE_LOCALE_CTYPE
777 result = PerlEnv_getenv("LC_CTYPE");
730252b2 778 if (result && strNE(result, "")) {
89f7b9aa 779 setlocale(LC_CTYPE, result);
bbc98134
KW
780 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
781 __FILE__, __LINE__,
782 _setlocale_debug_string(LC_CTYPE, result, "not captured")));
89f7b9aa
KW
783 }
784# endif
785# ifdef USE_LOCALE_COLLATE
786 result = PerlEnv_getenv("LC_COLLATE");
730252b2 787 if (result && strNE(result, "")) {
89f7b9aa 788 setlocale(LC_COLLATE, result);
bbc98134
KW
789 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
790 __FILE__, __LINE__,
791 _setlocale_debug_string(LC_COLLATE, result, "not captured")));
89f7b9aa
KW
792 }
793# endif
794# ifdef USE_LOCALE_MONETARY
795 result = PerlEnv_getenv("LC_MONETARY");
730252b2 796 if (result && strNE(result, "")) {
89f7b9aa 797 setlocale(LC_MONETARY, result);
bbc98134
KW
798 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
799 __FILE__, __LINE__,
800 _setlocale_debug_string(LC_MONETARY, result, "not captured")));
89f7b9aa
KW
801 }
802# endif
803# ifdef USE_LOCALE_NUMERIC
804 result = PerlEnv_getenv("LC_NUMERIC");
730252b2 805 if (result && strNE(result, "")) {
89f7b9aa 806 setlocale(LC_NUMERIC, result);
bbc98134
KW
807 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
808 __FILE__, __LINE__,
809 _setlocale_debug_string(LC_NUMERIC, result, "not captured")));
89f7b9aa
KW
810 }
811# endif
812# ifdef USE_LOCALE_MESSAGES
813 result = PerlEnv_getenv("LC_MESSAGES");
730252b2 814 if (result && strNE(result, "")) {
89f7b9aa 815 setlocale(LC_MESSAGES, result);
bbc98134
KW
816 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
817 __FILE__, __LINE__,
818 _setlocale_debug_string(LC_MESSAGES, result, "not captured")));
89f7b9aa
KW
819 }
820# endif
821
bbc98134
KW
822 result = setlocale(LC_ALL, NULL);
823 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
824 __FILE__, __LINE__,
825 _setlocale_debug_string(LC_ALL, NULL, result)));
89f7b9aa 826
bbc98134 827 return result;
b385bb4d
KW
828}
829
830#endif
831
832
98994639
HS
833/*
834 * Initialize locale awareness.
835 */
836int
837Perl_init_i18nl10n(pTHX_ int printwarn)
838{
0e92a118
KW
839 /* printwarn is
840 *
841 * 0 if not to output warning when setup locale is bad
842 * 1 if to output warning based on value of PERL_BADLANG
843 * >1 if to output regardless of PERL_BADLANG
844 *
845 * returns
98994639 846 * 1 = set ok or not applicable,
0e92a118
KW
847 * 0 = fallback to a locale of lower priority
848 * -1 = fallback to all locales failed, not even to the C locale
6b058d42
KW
849 *
850 * Under -DDEBUGGING, if the environment variable PERL_DEBUG_LOCALE_INIT is
851 * set, debugging information is output.
852 *
853 * This looks more complicated than it is, mainly due to the #ifdefs.
854 *
855 * We try to set LC_ALL to the value determined by the environment. If
856 * there is no LC_ALL on this platform, we try the individual categories we
857 * know about. If this works, we are done.
858 *
859 * But if it doesn't work, we have to do something else. We search the
860 * environment variables ourselves instead of relying on the system to do
861 * it. We look at, in order, LC_ALL, LANG, a system default locale (if we
862 * think there is one), and the ultimate fallback "C". This is all done in
863 * the same loop as above to avoid duplicating code, but it makes things
864 * more complex. After the original failure, we add the fallback
865 * possibilities to the list of locales to try, and iterate the loop
866 * through them all until one succeeds.
867 *
868 * On Ultrix, the locale MUST come from the environment, so there is
869 * preliminary code to set it. I (khw) am not sure that it is necessary,
870 * and that this couldn't be folded into the loop, but barring any real
871 * platforms to test on, it's staying as-is
872 *
873 * A slight complication is that in embedded Perls, the locale may already
874 * be set-up, and we don't want to get it from the normal environment
875 * variables. This is handled by having a special environment variable
876 * indicate we're in this situation. We simply set setlocale's 2nd
877 * parameter to be a NULL instead of "". That indicates to setlocale that
878 * it is not to change anything, but to return the current value,
879 * effectively initializing perl's db to what the locale already is.
880 *
881 * We play the same trick with NULL if a LC_ALL succeeds. We call
882 * setlocale() on the individual categores with NULL to get their existing
883 * values for our db, instead of trying to change them.
884 * */
98994639 885
0e92a118
KW
886 int ok = 1;
887
98994639 888#if defined(USE_LOCALE)
98994639
HS
889#ifdef USE_LOCALE_CTYPE
890 char *curctype = NULL;
891#endif /* USE_LOCALE_CTYPE */
892#ifdef USE_LOCALE_COLLATE
893 char *curcoll = NULL;
894#endif /* USE_LOCALE_COLLATE */
895#ifdef USE_LOCALE_NUMERIC
896 char *curnum = NULL;
897#endif /* USE_LOCALE_NUMERIC */
898#ifdef __GLIBC__
175c4cf9 899 const char * const language = savepv(PerlEnv_getenv("LANGUAGE"));
98994639 900#endif
65ebb059 901
ccd65d51
KW
902 /* NULL uses the existing already set up locale */
903 const char * const setlocale_init = (PerlEnv_getenv("PERL_SKIP_LOCALE_INIT"))
904 ? NULL
905 : "";
c3fcd832
KW
906 const char* trial_locales[5]; /* 5 = 1 each for "", LC_ALL, LANG, "", C */
907 unsigned int trial_locales_count;
175c4cf9
KW
908 const char * const lc_all = savepv(PerlEnv_getenv("LC_ALL"));
909 const char * const lang = savepv(PerlEnv_getenv("LANG"));
98994639 910 bool setlocale_failure = FALSE;
65ebb059
KW
911 unsigned int i;
912 char *p;
175c4cf9
KW
913
914 /* A later getenv() could zap this, so only use here */
915 const char * const bad_lang_use_once = PerlEnv_getenv("PERL_BADLANG");
916
917 const bool locwarn = (printwarn > 1
918 || (printwarn
919 && (! bad_lang_use_once
22ff3130
HS
920 || (
921 /* disallow with "" or "0" */
922 *bad_lang_use_once
923 && strNE("0", bad_lang_use_once)))));
0e92a118 924 bool done = FALSE;
5d1187d1
KW
925 char * sl_result; /* return from setlocale() */
926 char * locale_param;
6bce99ee
JH
927#ifdef WIN32
928 /* In some systems you can find out the system default locale
929 * and use that as the fallback locale. */
930# define SYSTEM_DEFAULT_LOCALE
931#endif
932#ifdef SYSTEM_DEFAULT_LOCALE
65ebb059 933 const char *system_default_locale = NULL;
6bce99ee 934#endif
98994639 935
2fcc0ca9
KW
936#ifdef DEBUGGING
937 debug_initialization = (PerlEnv_getenv("PERL_DEBUG_LOCALE_INIT"))
938 ? TRUE
939 : FALSE;
940# define DEBUG_LOCALE_INIT(category, locale, result) \
941 STMT_START { \
942 if (debug_initialization) { \
943 PerlIO_printf(Perl_debug_log, \
944 "%s:%d: %s\n", \
945 __FILE__, __LINE__, \
946 _setlocale_debug_string(category, \
947 locale, \
948 result)); \
949 } \
950 } STMT_END
951#else
952# define DEBUG_LOCALE_INIT(a,b,c)
953#endif
954
0e92a118
KW
955#ifndef LOCALE_ENVIRON_REQUIRED
956 PERL_UNUSED_VAR(done);
5d1187d1 957 PERL_UNUSED_VAR(locale_param);
0e92a118 958#else
98994639
HS
959
960 /*
961 * Ultrix setlocale(..., "") fails if there are no environment
962 * variables from which to get a locale name.
963 */
964
b3e384bf 965# ifdef LC_ALL
98994639 966 if (lang) {
5d1187d1
KW
967 sl_result = my_setlocale(LC_ALL, setlocale_init);
968 DEBUG_LOCALE_INIT(LC_ALL, setlocale_init, sl_result);
969 if (sl_result)
98994639
HS
970 done = TRUE;
971 else
972 setlocale_failure = TRUE;
973 }
5d1187d1 974 if (! setlocale_failure) {
b3e384bf 975# ifdef USE_LOCALE_CTYPE
5d1187d1
KW
976 locale_param = (! done && (lang || PerlEnv_getenv("LC_CTYPE")))
977 ? setlocale_init
978 : NULL;
979 curctype = my_setlocale(LC_CTYPE, locale_param);
980 DEBUG_LOCALE_INIT(LC_CTYPE, locale_param, sl_result);
981 if (! curctype)
98994639
HS
982 setlocale_failure = TRUE;
983 else
984 curctype = savepv(curctype);
b3e384bf
KW
985# endif /* USE_LOCALE_CTYPE */
986# ifdef USE_LOCALE_COLLATE
5d1187d1
KW
987 locale_param = (! done && (lang || PerlEnv_getenv("LC_COLLATE")))
988 ? setlocale_init
989 : NULL;
990 curcoll = my_setlocale(LC_COLLATE, locale_param);
991 DEBUG_LOCALE_INIT(LC_COLLATE, locale_param, sl_result);
992 if (! curcoll)
98994639
HS
993 setlocale_failure = TRUE;
994 else
995 curcoll = savepv(curcoll);
b3e384bf
KW
996# endif /* USE_LOCALE_COLLATE */
997# ifdef USE_LOCALE_NUMERIC
5d1187d1
KW
998 locale_param = (! done && (lang || PerlEnv_getenv("LC_NUMERIC")))
999 ? setlocale_init
1000 : NULL;
1001 curnum = my_setlocale(LC_NUMERIC, locale_param);
1002 DEBUG_LOCALE_INIT(LC_NUMERIC, locale_param, sl_result);
1003 if (! curnum)
98994639
HS
1004 setlocale_failure = TRUE;
1005 else
1006 curnum = savepv(curnum);
b3e384bf 1007# endif /* USE_LOCALE_NUMERIC */
a782673d 1008# ifdef USE_LOCALE_MESSAGES
5d1187d1
KW
1009 locale_param = (! done && (lang || PerlEnv_getenv("LC_MESSAGES")))
1010 ? setlocale_init
1011 : NULL;
1012 sl_result = my_setlocale(LC_MESSAGES, locale_param);
1013 DEBUG_LOCALE_INIT(LC_MESSAGES, locale_param, sl_result);
1014 if (! sl_result)
a782673d
KW
1015 setlocale_failure = TRUE;
1016 }
1017# endif /* USE_LOCALE_MESSAGES */
c835d6be 1018# ifdef USE_LOCALE_MONETARY
5d1187d1
KW
1019 locale_param = (! done && (lang || PerlEnv_getenv("LC_MONETARY")))
1020 ? setlocale_init
1021 : NULL;
1022 sl_result = my_setlocale(LC_MONETARY, locale_param);
1023 DEBUG_LOCALE_INIT(LC_MONETARY, locale_param, sl_result);
1024 if (! sl_result) {
c835d6be
KW
1025 setlocale_failure = TRUE;
1026 }
1027# endif /* USE_LOCALE_MONETARY */
98994639
HS
1028 }
1029
b3e384bf 1030# endif /* LC_ALL */
98994639
HS
1031
1032#endif /* !LOCALE_ENVIRON_REQUIRED */
1033
65ebb059 1034 /* We try each locale in the list until we get one that works, or exhaust
20a240df
KW
1035 * the list. Normally the loop is executed just once. But if setting the
1036 * locale fails, inside the loop we add fallback trials to the array and so
1037 * will execute the loop multiple times */
c3fcd832
KW
1038 trial_locales[0] = setlocale_init;
1039 trial_locales_count = 1;
65ebb059
KW
1040 for (i= 0; i < trial_locales_count; i++) {
1041 const char * trial_locale = trial_locales[i];
1042
1043 if (i > 0) {
1044
1045 /* XXX This is to preserve old behavior for LOCALE_ENVIRON_REQUIRED
1046 * when i==0, but I (khw) don't think that behavior makes much
1047 * sense */
1048 setlocale_failure = FALSE;
1049
6bce99ee
JH
1050#ifdef SYSTEM_DEFAULT_LOCALE
1051# ifdef WIN32
65ebb059
KW
1052 /* On Windows machines, an entry of "" after the 0th means to use
1053 * the system default locale, which we now proceed to get. */
1054 if (strEQ(trial_locale, "")) {
1055 unsigned int j;
1056
1057 /* Note that this may change the locale, but we are going to do
1058 * that anyway just below */
1059 system_default_locale = setlocale(LC_ALL, "");
5d1187d1 1060 DEBUG_LOCALE_INIT(LC_ALL, "", system_default_locale);
65ebb059
KW
1061
1062 /* Skip if invalid or it's already on the list of locales to
1063 * try */
1064 if (! system_default_locale) {
1065 goto next_iteration;
1066 }
1067 for (j = 0; j < trial_locales_count; j++) {
1068 if (strEQ(system_default_locale, trial_locales[j])) {
1069 goto next_iteration;
1070 }
1071 }
1072
1073 trial_locale = system_default_locale;
1074 }
6bce99ee
JH
1075# endif /* WIN32 */
1076#endif /* SYSTEM_DEFAULT_LOCALE */
65ebb059
KW
1077 }
1078
98994639 1079#ifdef LC_ALL
5d1187d1
KW
1080 sl_result = my_setlocale(LC_ALL, trial_locale);
1081 DEBUG_LOCALE_INIT(LC_ALL, trial_locale, sl_result);
1082 if (! sl_result) {
49c85077 1083 setlocale_failure = TRUE;
7cd8b568
KW
1084 }
1085 else {
1086 /* Since LC_ALL succeeded, it should have changed all the other
1087 * categories it can to its value; so we massage things so that the
1088 * setlocales below just return their category's current values.
1089 * This adequately handles the case in NetBSD where LC_COLLATE may
1090 * not be defined for a locale, and setting it individually will
1091 * fail, whereas setting LC_ALL suceeds, leaving LC_COLLATE set to
1092 * the POSIX locale. */
1093 trial_locale = NULL;
1094 }
98994639
HS
1095#endif /* LC_ALL */
1096
49c85077 1097 if (!setlocale_failure) {
98994639 1098#ifdef USE_LOCALE_CTYPE
49c85077 1099 Safefree(curctype);
5d1187d1
KW
1100 curctype = my_setlocale(LC_CTYPE, trial_locale);
1101 DEBUG_LOCALE_INIT(LC_CTYPE, trial_locale, curctype);
1102 if (! curctype)
49c85077
KW
1103 setlocale_failure = TRUE;
1104 else
1105 curctype = savepv(curctype);
98994639
HS
1106#endif /* USE_LOCALE_CTYPE */
1107#ifdef USE_LOCALE_COLLATE
49c85077 1108 Safefree(curcoll);
5d1187d1
KW
1109 curcoll = my_setlocale(LC_COLLATE, trial_locale);
1110 DEBUG_LOCALE_INIT(LC_COLLATE, trial_locale, curcoll);
1111 if (! curcoll)
49c85077
KW
1112 setlocale_failure = TRUE;
1113 else
1114 curcoll = savepv(curcoll);
98994639
HS
1115#endif /* USE_LOCALE_COLLATE */
1116#ifdef USE_LOCALE_NUMERIC
49c85077 1117 Safefree(curnum);
5d1187d1
KW
1118 curnum = my_setlocale(LC_NUMERIC, trial_locale);
1119 DEBUG_LOCALE_INIT(LC_NUMERIC, trial_locale, curnum);
1120 if (! curnum)
49c85077
KW
1121 setlocale_failure = TRUE;
1122 else
1123 curnum = savepv(curnum);
98994639 1124#endif /* USE_LOCALE_NUMERIC */
a782673d 1125#ifdef USE_LOCALE_MESSAGES
5d1187d1
KW
1126 sl_result = my_setlocale(LC_MESSAGES, trial_locale);
1127 DEBUG_LOCALE_INIT(LC_MESSAGES, trial_locale, sl_result);
1128 if (! (sl_result))
a782673d
KW
1129 setlocale_failure = TRUE;
1130#endif /* USE_LOCALE_MESSAGES */
c835d6be 1131#ifdef USE_LOCALE_MONETARY
5d1187d1
KW
1132 sl_result = my_setlocale(LC_MONETARY, trial_locale);
1133 DEBUG_LOCALE_INIT(LC_MONETARY, trial_locale, sl_result);
1134 if (! (sl_result))
c835d6be
KW
1135 setlocale_failure = TRUE;
1136#endif /* USE_LOCALE_MONETARY */
1137
49c85077
KW
1138 if (! setlocale_failure) { /* Success */
1139 break;
1140 }
65ebb059 1141 }
98994639 1142
49c85077
KW
1143 /* Here, something failed; will need to try a fallback. */
1144 ok = 0;
65ebb059 1145
49c85077
KW
1146 if (i == 0) {
1147 unsigned int j;
98994639 1148
65ebb059 1149 if (locwarn) { /* Output failure info only on the first one */
98994639
HS
1150#ifdef LC_ALL
1151
49c85077
KW
1152 PerlIO_printf(Perl_error_log,
1153 "perl: warning: Setting locale failed.\n");
98994639
HS
1154
1155#else /* !LC_ALL */
1156
49c85077
KW
1157 PerlIO_printf(Perl_error_log,
1158 "perl: warning: Setting locale failed for the categories:\n\t");
20a240df 1159# ifdef USE_LOCALE_CTYPE
49c85077
KW
1160 if (! curctype)
1161 PerlIO_printf(Perl_error_log, "LC_CTYPE ");
20a240df
KW
1162# endif /* USE_LOCALE_CTYPE */
1163# ifdef USE_LOCALE_COLLATE
49c85077
KW
1164 if (! curcoll)
1165 PerlIO_printf(Perl_error_log, "LC_COLLATE ");
20a240df
KW
1166# endif /* USE_LOCALE_COLLATE */
1167# ifdef USE_LOCALE_NUMERIC
49c85077
KW
1168 if (! curnum)
1169 PerlIO_printf(Perl_error_log, "LC_NUMERIC ");
20a240df 1170# endif /* USE_LOCALE_NUMERIC */
a782673d 1171 PerlIO_printf(Perl_error_log, "and possibly others\n");
98994639
HS
1172
1173#endif /* LC_ALL */
1174
49c85077
KW
1175 PerlIO_printf(Perl_error_log,
1176 "perl: warning: Please check that your locale settings:\n");
98994639
HS
1177
1178#ifdef __GLIBC__
49c85077
KW
1179 PerlIO_printf(Perl_error_log,
1180 "\tLANGUAGE = %c%s%c,\n",
1181 language ? '"' : '(',
1182 language ? language : "unset",
1183 language ? '"' : ')');
98994639
HS
1184#endif
1185
49c85077
KW
1186 PerlIO_printf(Perl_error_log,
1187 "\tLC_ALL = %c%s%c,\n",
1188 lc_all ? '"' : '(',
1189 lc_all ? lc_all : "unset",
1190 lc_all ? '"' : ')');
98994639
HS
1191
1192#if defined(USE_ENVIRON_ARRAY)
49c85077
KW
1193 {
1194 char **e;
1195 for (e = environ; *e; e++) {
1196 if (strnEQ(*e, "LC_", 3)
1197 && strnNE(*e, "LC_ALL=", 7)
1198 && (p = strchr(*e, '=')))
1199 PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
1200 (int)(p - *e), *e, p + 1);
1201 }
1202 }
98994639 1203#else
49c85077
KW
1204 PerlIO_printf(Perl_error_log,
1205 "\t(possibly more locale environment variables)\n");
98994639
HS
1206#endif
1207
49c85077
KW
1208 PerlIO_printf(Perl_error_log,
1209 "\tLANG = %c%s%c\n",
1210 lang ? '"' : '(',
1211 lang ? lang : "unset",
1212 lang ? '"' : ')');
98994639 1213
49c85077
KW
1214 PerlIO_printf(Perl_error_log,
1215 " are supported and installed on your system.\n");
1216 }
98994639 1217
65ebb059 1218 /* Calculate what fallback locales to try. We have avoided this
f6bab5f6 1219 * until we have to, because failure is quite unlikely. This will
65ebb059
KW
1220 * usually change the upper bound of the loop we are in.
1221 *
1222 * Since the system's default way of setting the locale has not
1223 * found one that works, We use Perl's defined ordering: LC_ALL,
1224 * LANG, and the C locale. We don't try the same locale twice, so
1225 * don't add to the list if already there. (On POSIX systems, the
1226 * LC_ALL element will likely be a repeat of the 0th element "",
6b058d42
KW
1227 * but there's no harm done by doing it explicitly.
1228 *
1229 * Note that this tries the LC_ALL environment variable even on
1230 * systems which have no LC_ALL locale setting. This may or may
1231 * not have been originally intentional, but there's no real need
1232 * to change the behavior. */
65ebb059
KW
1233 if (lc_all) {
1234 for (j = 0; j < trial_locales_count; j++) {
1235 if (strEQ(lc_all, trial_locales[j])) {
1236 goto done_lc_all;
1237 }
1238 }
1239 trial_locales[trial_locales_count++] = lc_all;
1240 }
1241 done_lc_all:
98994639 1242
65ebb059
KW
1243 if (lang) {
1244 for (j = 0; j < trial_locales_count; j++) {
1245 if (strEQ(lang, trial_locales[j])) {
1246 goto done_lang;
1247 }
1248 }
1249 trial_locales[trial_locales_count++] = lang;
1250 }
1251 done_lang:
1252
1253#if defined(WIN32) && defined(LC_ALL)
1254 /* For Windows, we also try the system default locale before "C".
1255 * (If there exists a Windows without LC_ALL we skip this because
1256 * it gets too complicated. For those, the "C" is the next
1257 * fallback possibility). The "" is the same as the 0th element of
1258 * the array, but the code at the loop above knows to treat it
1259 * differently when not the 0th */
1260 trial_locales[trial_locales_count++] = "";
1261#endif
1262
1263 for (j = 0; j < trial_locales_count; j++) {
1264 if (strEQ("C", trial_locales[j])) {
1265 goto done_C;
1266 }
1267 }
1268 trial_locales[trial_locales_count++] = "C";
98994639 1269
65ebb059
KW
1270 done_C: ;
1271 } /* end of first time through the loop */
98994639 1272
65ebb059
KW
1273#ifdef WIN32
1274 next_iteration: ;
1275#endif
1276
1277 } /* end of looping through the trial locales */
1278
1279 if (ok < 1) { /* If we tried to fallback */
1280 const char* msg;
1281 if (! setlocale_failure) { /* fallback succeeded */
1282 msg = "Falling back to";
1283 }
1284 else { /* fallback failed */
98994639 1285
65ebb059
KW
1286 /* We dropped off the end of the loop, so have to decrement i to
1287 * get back to the value the last time through */
1288 i--;
98994639 1289
65ebb059
KW
1290 ok = -1;
1291 msg = "Failed to fall back to";
1292
1293 /* To continue, we should use whatever values we've got */
98994639 1294#ifdef USE_LOCALE_CTYPE
49c85077
KW
1295 Safefree(curctype);
1296 curctype = savepv(setlocale(LC_CTYPE, NULL));
5d1187d1 1297 DEBUG_LOCALE_INIT(LC_CTYPE, NULL, curctype);
98994639
HS
1298#endif /* USE_LOCALE_CTYPE */
1299#ifdef USE_LOCALE_COLLATE
49c85077
KW
1300 Safefree(curcoll);
1301 curcoll = savepv(setlocale(LC_COLLATE, NULL));
5d1187d1 1302 DEBUG_LOCALE_INIT(LC_COLLATE, NULL, curcoll);
98994639
HS
1303#endif /* USE_LOCALE_COLLATE */
1304#ifdef USE_LOCALE_NUMERIC
49c85077
KW
1305 Safefree(curnum);
1306 curnum = savepv(setlocale(LC_NUMERIC, NULL));
5d1187d1 1307 DEBUG_LOCALE_INIT(LC_NUMERIC, NULL, curnum);
98994639 1308#endif /* USE_LOCALE_NUMERIC */
65ebb059
KW
1309 }
1310
1311 if (locwarn) {
1312 const char * description;
1313 const char * name = "";
1314 if (strEQ(trial_locales[i], "C")) {
1315 description = "the standard locale";
1316 name = "C";
1317 }
6bce99ee 1318#ifdef SYSTEM_DEFAULT_LOCALE
65ebb059
KW
1319 else if (strEQ(trial_locales[i], "")) {
1320 description = "the system default locale";
1321 if (system_default_locale) {
1322 name = system_default_locale;
1323 }
1324 }
6bce99ee 1325#endif /* SYSTEM_DEFAULT_LOCALE */
65ebb059
KW
1326 else {
1327 description = "a fallback locale";
1328 name = trial_locales[i];
1329 }
1330 if (name && strNE(name, "")) {
1331 PerlIO_printf(Perl_error_log,
1332 "perl: warning: %s %s (\"%s\").\n", msg, description, name);
1333 }
1334 else {
1335 PerlIO_printf(Perl_error_log,
1336 "perl: warning: %s %s.\n", msg, description);
1337 }
1338 }
1339 } /* End of tried to fallback */
98994639
HS
1340
1341#ifdef USE_LOCALE_CTYPE
1342 new_ctype(curctype);
1343#endif /* USE_LOCALE_CTYPE */
1344
1345#ifdef USE_LOCALE_COLLATE
1346 new_collate(curcoll);
1347#endif /* USE_LOCALE_COLLATE */
1348
1349#ifdef USE_LOCALE_NUMERIC
1350 new_numeric(curnum);
1351#endif /* USE_LOCALE_NUMERIC */
b310b053 1352
8ef6e574 1353#if defined(USE_PERLIO) && defined(USE_LOCALE_CTYPE)
49c85077
KW
1354 /* Set PL_utf8locale to TRUE if using PerlIO _and_ the current LC_CTYPE
1355 * locale is UTF-8. If PL_utf8locale and PL_unicode (set by -C or by
1356 * $ENV{PERL_UNICODE}) are true, perl.c:S_parse_body() will turn on the
1357 * PerlIO :utf8 layer on STDIN, STDOUT, STDERR, _and_ the default open
1358 * discipline. */
c1284011 1359 PL_utf8locale = _is_cur_LC_category_utf8(LC_CTYPE);
49c85077 1360
a05d7ebb 1361 /* Set PL_unicode to $ENV{PERL_UNICODE} if using PerlIO.
fde18df1
JH
1362 This is an alternative to using the -C command line switch
1363 (the -C if present will override this). */
1364 {
dd374669 1365 const char *p = PerlEnv_getenv("PERL_UNICODE");
a05d7ebb 1366 PL_unicode = p ? parse_unicode_opts(&p) : 0;
5a22a2bb
NC
1367 if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
1368 PL_utf8cache = -1;
b310b053 1369 }
ec71e770 1370#endif
b310b053 1371
98994639 1372#ifdef USE_LOCALE_CTYPE
43c5f42d 1373 Safefree(curctype);
98994639
HS
1374#endif /* USE_LOCALE_CTYPE */
1375#ifdef USE_LOCALE_COLLATE
43c5f42d 1376 Safefree(curcoll);
98994639
HS
1377#endif /* USE_LOCALE_COLLATE */
1378#ifdef USE_LOCALE_NUMERIC
43c5f42d 1379 Safefree(curnum);
98994639 1380#endif /* USE_LOCALE_NUMERIC */
8ef6e574 1381
175c4cf9
KW
1382#ifdef __GLIBC__
1383 Safefree(language);
1384#endif
1385
1386 Safefree(lc_all);
1387 Safefree(lang);
1388
e3305790
KW
1389#else /* !USE_LOCALE */
1390 PERL_UNUSED_ARG(printwarn);
1391#endif /* USE_LOCALE */
1392
2fcc0ca9
KW
1393#ifdef DEBUGGING
1394 /* So won't continue to output stuff */
1395 debug_initialization = FALSE;
1396#endif
1397
98994639
HS
1398 return ok;
1399}
1400
98994639
HS
1401#ifdef USE_LOCALE_COLLATE
1402
a4a439fb 1403char *
a4a439fb
KW
1404Perl__mem_collxfrm(pTHX_ const char *input_string,
1405 STRLEN len, /* Length of 'input_string' */
1406 STRLEN *xlen, /* Set to length of returned string
1407 (not including the collation index
1408 prefix) */
1409 bool utf8 /* Is the input in UTF-8? */
6696cfa7 1410 )
98994639 1411{
a4a439fb
KW
1412
1413 /* _mem_collxfrm() is a bit like strxfrm() but with two important
1414 * differences. First, it handles embedded NULs. Second, it allocates a bit
1415 * more memory than needed for the transformed data itself. The real
1416 * transformed data begins at offset sizeof(collationix). *xlen is set to
1417 * the length of that, and doesn't include the collation index size.
1418 * Please see sv_collxfrm() to see how this is used. */
1419
6696cfa7
KW
1420 char * s = (char *) input_string;
1421 STRLEN s_strlen = strlen(input_string);
79f120c8 1422 char *xbuf = NULL;
6696cfa7 1423 STRLEN xAlloc, xout; /* xalloc is a reserved word in VC */
c664130f 1424 bool first_time = TRUE; /* Cleared after first loop iteration */
98994639 1425
a4a439fb
KW
1426 PERL_ARGS_ASSERT__MEM_COLLXFRM;
1427
1428 /* Must be NUL-terminated */
1429 assert(*(input_string + len) == '\0');
7918f24d 1430
79f120c8
KW
1431 /* If this locale has defective collation, skip */
1432 if (PL_collxfrm_base == 0 && PL_collxfrm_mult == 0) {
1433 goto bad;
1434 }
1435
6696cfa7
KW
1436 /* Replace any embedded NULs with the control that sorts before any others.
1437 * This will give as good as possible results on strings that don't
1438 * otherwise contain that character, but otherwise there may be
1439 * less-than-perfect results with that character and NUL. This is
1440 * unavoidable unless we replace strxfrm with our own implementation.
1441 *
1442 * XXX This code may be overkill. khw wrote it before realizing that if
1443 * you change a NUL into some other character, that that may change the
1444 * strxfrm results if that character is part of a sequence with other
1445 * characters for weight calculations. To minimize the chances of this,
1446 * now the replacement is restricted to another control (likely to be
1447 * \001). But the full generality has been retained.
1448 *
1449 * This is one of the few places in the perl core, where we can use
1450 * standard functions like strlen() and strcat(). It's because we're
1451 * looking for NULs. */
1452 if (s_strlen < len) {
1453 char * e = s + len;
1454 char * sans_nuls;
1455 STRLEN cur_min_char_len;
1456
1457 /* If we don't know what control character sorts lowest for this
1458 * locale, find it */
1459 if (*PL_strxfrm_min_char == '\0') {
1460 int j;
1461 char * cur_min_x = NULL; /* Cur cp's xfrm, (except it also
1462 includes the collation index
1463 prefixed. */
1464
1465 /* Look through all legal code points (NUL isn't) */
1466 for (j = 1; j < 256; j++) {
1467 char * x; /* j's xfrm plus collation index */
1468 STRLEN x_len; /* length of 'x' */
1469 STRLEN trial_len = 1;
1470
1471 /* Create a 1 byte string of the current code point, but with
1472 * room to be 2 bytes */
1473 char cur_source[] = { (char) j, '\0' , '\0' };
1474
1475 if (PL_in_utf8_COLLATE_locale) {
1476 if (! isCNTRL_L1(j)) {
1477 continue;
1478 }
1479
1480 /* If needs to be 2 bytes, find them */
1481 if (! UVCHR_IS_INVARIANT(j)) {
a4a439fb
KW
1482 char * d = cur_source;
1483 append_utf8_from_native_byte((U8) j, (U8 **) &d);
1484 trial_len = 2;
6696cfa7
KW
1485 }
1486 }
1487 else if (! isCNTRL_LC(j)) {
1488 continue;
1489 }
1490
1491 /* Then transform it */
a4a439fb
KW
1492 x = _mem_collxfrm(cur_source, trial_len, &x_len,
1493 PL_in_utf8_COLLATE_locale);
6696cfa7
KW
1494
1495 /* If something went wrong (which it shouldn't), just
1496 * ignore this code point */
1497 if ( x_len == 0
1498 || strlen(x + sizeof(PL_collation_ix)) < x_len)
1499 {
1500 continue;
1501 }
1502
1503 /* If this character's transformation is lower than
1504 * the current lowest, this one becomes the lowest */
1505 if ( cur_min_x == NULL
1506 || strLT(x + sizeof(PL_collation_ix),
1507 cur_min_x + sizeof(PL_collation_ix)))
1508 {
1509 strcpy(PL_strxfrm_min_char, cur_source);
1510 cur_min_x = x;
1511 }
1512 else {
1513 Safefree(x);
1514 }
1515 } /* end of loop through all bytes */
1516
1517 /* Unlikely, but possible, if there aren't any controls in the
1518 * locale, arbitrarily use \001 */
1519 if (cur_min_x == NULL) {
1520 STRLEN x_len; /* temporary */
a4a439fb
KW
1521 cur_min_x = _mem_collxfrm("\001", 1, &x_len,
1522 PL_in_utf8_COLLATE_locale);
6696cfa7
KW
1523 /* cur_min_cp was already initialized to 1 */
1524 }
1525
1526 Safefree(cur_min_x);
1527 }
1528
1529 /* The worst case length for the replaced string would be if every
1530 * character in it is NUL. Multiply that by the length of each
1531 * replacement, and allow for a trailing NUL */
1532 cur_min_char_len = strlen(PL_strxfrm_min_char);
1533 Newx(sans_nuls, (len * cur_min_char_len) + 1, char);
1534 *sans_nuls = '\0';
1535
1536
1537 /* Replace each NUL with the lowest collating control. Loop until have
1538 * exhausted all the NULs */
1539 while (s + s_strlen < e) {
1540 strcat(sans_nuls, s);
1541
1542 /* Do the actual replacement */
1543 strcat(sans_nuls, PL_strxfrm_min_char);
1544
1545 /* Move past the input NUL */
1546 s += s_strlen + 1;
1547 s_strlen = strlen(s);
1548 }
1549
1550 /* And add anything that trails the final NUL */
1551 strcat(sans_nuls, s);
1552
1553 /* Switch so below we transform this modified string */
1554 s = sans_nuls;
1555 len = strlen(s);
1556 }
1557
a4a439fb
KW
1558 /* Make sure the UTF8ness of the string and locale match */
1559 if (utf8 != PL_in_utf8_COLLATE_locale) {
1560 const char * const t = s; /* Temporary so we can later find where the
1561 input was */
1562
1563 /* Here they don't match. Change the string's to be what the locale is
1564 * expecting */
1565
1566 if (! utf8) { /* locale is UTF-8, but input isn't; upgrade the input */
1567 s = (char *) bytes_to_utf8((const U8 *) s, &len);
1568 utf8 = TRUE;
1569 }
1570 else { /* locale is not UTF-8; but input is; downgrade the input */
1571
1572 s = (char *) bytes_from_utf8((const U8 *) s, &len, &utf8);
1573
1574 /* If the downgrade was successful we are done, but if the input
1575 * contains things that require UTF-8 to represent, have to do
1576 * damage control ... */
1577 if (UNLIKELY(utf8)) {
1578
1579 /* What we do is construct a non-UTF-8 string with
1580 * 1) the characters representable by a single byte converted
1581 * to be so (if necessary);
1582 * 2) and the rest converted to collate the same as the
1583 * highest collating representable character. That makes
1584 * them collate at the end. This is similar to how we
1585 * handle embedded NULs, but we use the highest collating
1586 * code point instead of the smallest. Like the NUL case,
1587 * this isn't perfect, but is the best we can reasonably
1588 * do. Every above-255 code point will sort the same as
1589 * the highest-sorting 0-255 code point. If that code
1590 * point can combine in a sequence with some other code
1591 * points for weight calculations, us changing something to
1592 * be it can adversely affect the results. But in most
1593 * cases, it should work reasonably. And note that this is
1594 * really an illegal situation: using code points above 255
1595 * on a locale where only 0-255 are valid. If two strings
1596 * sort entirely equal, then the sort order for the
1597 * above-255 code points will be in code point order. */
1598
1599 utf8 = FALSE;
1600
1601 /* If we haven't calculated the code point with the maximum
1602 * collating order for this locale, do so now */
1603 if (! PL_strxfrm_max_cp) {
1604 int j;
1605
1606 /* The current transformed string that collates the
1607 * highest (except it also includes the prefixed collation
1608 * index. */
1609 char * cur_max_x = NULL;
1610
1611 /* Look through all legal code points (NUL isn't) */
1612 for (j = 1; j < 256; j++) {
1613 char * x;
1614 STRLEN x_len;
1615
1616 /* Create a 1-char string of the current code point. */
1617 char cur_source[] = { (char) j, '\0' };
1618
1619 /* Then transform it */
1620 x = _mem_collxfrm(cur_source, 1, &x_len, FALSE);
1621
1622 /* If something went wrong (which it shouldn't), just
1623 * ignore this code point */
1624 if (x_len == 0) {
1625 Safefree(x);
1626 continue;
1627 }
1628
1629 /* If this character's transformation is higher than
1630 * the current highest, this one becomes the highest */
1631 if ( cur_max_x == NULL
1632 || strGT(x + sizeof(PL_collation_ix),
1633 cur_max_x + sizeof(PL_collation_ix)))
1634 {
1635 PL_strxfrm_max_cp = j;
1636 cur_max_x = x;
1637 }
1638 else {
1639 Safefree(x);
1640 }
1641 }
1642
1643 Safefree(cur_max_x);
1644 }
1645
1646 /* Here we know which legal code point collates the highest.
1647 * We are ready to construct the non-UTF-8 string. The length
1648 * will be at least 1 byte smaller than the input string
1649 * (because we changed at least one 2-byte character into a
1650 * single byte), but that is eaten up by the trailing NUL */
1651 Newx(s, len, char);
1652
1653 {
1654 STRLEN i;
1655 STRLEN d= 0;
1656
1657 for (i = 0; i < len; i+= UTF8SKIP(t + i)) {
1658 U8 cur_char = t[i];
1659 if (UTF8_IS_INVARIANT(cur_char)) {
1660 s[d++] = cur_char;
1661 }
1662 else if (UTF8_IS_DOWNGRADEABLE_START(cur_char)) {
1663 s[d++] = EIGHT_BIT_UTF8_TO_NATIVE(cur_char, t[i+1]);
1664 }
1665 else { /* Replace illegal cp with highest collating
1666 one */
1667 s[d++] = PL_strxfrm_max_cp;
1668 }
1669 }
1670 s[d++] = '\0';
1671 Renew(s, d, char); /* Free up unused space */
1672 }
1673 }
1674 }
1675
1676 /* Here, we have constructed a modified version of the input. It could
1677 * be that we already had a modified copy before we did this version.
1678 * If so, that copy is no longer needed */
1679 if (t != input_string) {
1680 Safefree(t);
1681 }
1682 }
1683
59c018b9
KW
1684 /* The first element in the output is the collation id, used by
1685 * sv_collxfrm(); then comes the space for the transformed string. The
1686 * equation should give us a good estimate as to how much is needed */
a4a439fb
KW
1687 xAlloc = sizeof(PL_collation_ix)
1688 + PL_collxfrm_base
1689 + (PL_collxfrm_mult * ((utf8)
1690 ? utf8_length((U8 *) s, (U8 *) s + len)
1691 : len));
a02a5408 1692 Newx(xbuf, xAlloc, char);
bb0f664e 1693 if (UNLIKELY(! xbuf))
98994639
HS
1694 goto bad;
1695
d35fca5f 1696 /* Store the collation id */
98994639
HS
1697 *(U32*)xbuf = PL_collation_ix;
1698 xout = sizeof(PL_collation_ix);
d35fca5f
KW
1699
1700 /* Then the transformation of the input. We loop until successful, or we
1701 * give up */
4ebeff16
KW
1702 for (;;) {
1703 STRLEN xused = strxfrm(xbuf + xout, s, xAlloc - xout);
1704
1705 /* If the transformed string occupies less space than we told strxfrm()
1706 * was available, it means it successfully transformed the whole
1707 * string. */
1708 if (xused < xAlloc - xout) {
1709 xout += xused;
1710 break;
1711 }
bb0f664e 1712
4ebeff16
KW
1713 if (UNLIKELY(xused >= PERL_INT_MAX))
1714 goto bad;
d35fca5f 1715
c664130f
KW
1716 /* A well-behaved strxfrm() returns exactly how much space it needs
1717 * (not including the trailing NUL) when it fails due to not enough
1718 * space being provided. Assume that this is the case unless it's been
1719 * proven otherwise */
1720 if (LIKELY(PL_strxfrm_is_behaved) && first_time) {
1721 xAlloc = xused + sizeof(PL_collation_ix) + 1;
1722 }
1723 else { /* Here, either:
1724 * 1) The strxfrm() has previously shown bad behavior; or
1725 * 2) It isn't the first time through the loop, which means
1726 * that the strxfrm() is now showing bad behavior, because
1727 * we gave it what it said was needed in the previous
1728 * iteration, and it came back saying it needed still more.
1729 * (Many versions of cygwin fit this. When the buffer size
1730 * isn't sufficient, they return the input size instead of
1731 * how much is needed.)
1732 * Increase the buffer size by a fixed percentage and try again. */
1733 xAlloc = (2 * xAlloc) + 1;
1734 PL_strxfrm_is_behaved = FALSE;
1735 }
1736
1737
4ebeff16
KW
1738 Renew(xbuf, xAlloc, char);
1739 if (UNLIKELY(! xbuf))
1740 goto bad;
c664130f
KW
1741
1742 first_time = FALSE;
4ebeff16 1743 }
98994639 1744
6696cfa7
KW
1745 *xlen = xout - sizeof(PL_collation_ix);
1746
3c5f993e
KW
1747 /* Free up unneeded space; retain ehough for trailing NUL */
1748 Renew(xbuf, xout + 1, char);
98994639 1749
6696cfa7
KW
1750 if (s != input_string) {
1751 Safefree(s);
98994639
HS
1752 }
1753
98994639
HS
1754 return xbuf;
1755
1756 bad:
1757 Safefree(xbuf);
6696cfa7
KW
1758 if (s != input_string) {
1759 Safefree(s);
1760 }
98994639
HS
1761 *xlen = 0;
1762 return NULL;
1763}
1764
1765#endif /* USE_LOCALE_COLLATE */
8ef6e574
KW
1766#ifdef USE_LOCALE
1767
c1284011
KW
1768bool
1769Perl__is_cur_LC_category_utf8(pTHX_ int category)
7d74bb61
KW
1770{
1771 /* Returns TRUE if the current locale for 'category' is UTF-8; FALSE
1772 * otherwise. 'category' may not be LC_ALL. If the platform doesn't have
119ee68b 1773 * nl_langinfo(), nor MB_CUR_MAX, this employs a heuristic, which hence
609548d2
KW
1774 * could give the wrong result. The result will very likely be correct for
1775 * languages that have commonly used non-ASCII characters, but for notably
1776 * English, it comes down to if the locale's name ends in something like
1777 * "UTF-8". It errs on the side of not being a UTF-8 locale. */
7d74bb61
KW
1778
1779 char *save_input_locale = NULL;
7d74bb61
KW
1780 STRLEN final_pos;
1781
8ef6e574 1782#ifdef LC_ALL
7d74bb61 1783 assert(category != LC_ALL);
8ef6e574 1784#endif
7d74bb61
KW
1785
1786 /* First dispose of the trivial cases */
b07fffd1 1787 save_input_locale = setlocale(category, NULL);
7d74bb61 1788 if (! save_input_locale) {
69014004
KW
1789 DEBUG_L(PerlIO_printf(Perl_debug_log,
1790 "Could not find current locale for category %d\n",
1791 category));
7d74bb61
KW
1792 return FALSE; /* XXX maybe should croak */
1793 }
b07fffd1 1794 save_input_locale = stdize_locale(savepv(save_input_locale));
a39edc4c 1795 if (isNAME_C_OR_POSIX(save_input_locale)) {
69014004
KW
1796 DEBUG_L(PerlIO_printf(Perl_debug_log,
1797 "Current locale for category %d is %s\n",
1798 category, save_input_locale));
b07fffd1 1799 Safefree(save_input_locale);
7d74bb61
KW
1800 return FALSE;
1801 }
1802
1d958db2
KW
1803#if defined(USE_LOCALE_CTYPE) \
1804 && (defined(MB_CUR_MAX) || (defined(HAS_NL_LANGINFO) && defined(CODESET)))
7d74bb61 1805
1d958db2 1806 { /* Next try nl_langinfo or MB_CUR_MAX if available */
7d74bb61
KW
1807
1808 char *save_ctype_locale = NULL;
119ee68b 1809 bool is_utf8;
7d74bb61 1810
119ee68b 1811 if (category != LC_CTYPE) { /* These work only on LC_CTYPE */
7d74bb61
KW
1812
1813 /* Get the current LC_CTYPE locale */
4f72bb37 1814 save_ctype_locale = setlocale(LC_CTYPE, NULL);
7d74bb61 1815 if (! save_ctype_locale) {
69014004
KW
1816 DEBUG_L(PerlIO_printf(Perl_debug_log,
1817 "Could not find current locale for LC_CTYPE\n"));
7d74bb61
KW
1818 goto cant_use_nllanginfo;
1819 }
4f72bb37 1820 save_ctype_locale = stdize_locale(savepv(save_ctype_locale));
7d74bb61
KW
1821
1822 /* If LC_CTYPE and the desired category use the same locale, this
1823 * means that finding the value for LC_CTYPE is the same as finding
1824 * the value for the desired category. Otherwise, switch LC_CTYPE
1825 * to the desired category's locale */
1826 if (strEQ(save_ctype_locale, save_input_locale)) {
1827 Safefree(save_ctype_locale);
1828 save_ctype_locale = NULL;
1829 }
1830 else if (! setlocale(LC_CTYPE, save_input_locale)) {
69014004
KW
1831 DEBUG_L(PerlIO_printf(Perl_debug_log,
1832 "Could not change LC_CTYPE locale to %s\n",
1833 save_input_locale));
7d74bb61
KW
1834 Safefree(save_ctype_locale);
1835 goto cant_use_nllanginfo;
1836 }
1837 }
1838
69014004
KW
1839 DEBUG_L(PerlIO_printf(Perl_debug_log, "Current LC_CTYPE locale=%s\n",
1840 save_input_locale));
1841
7d74bb61 1842 /* Here the current LC_CTYPE is set to the locale of the category whose
1d958db2
KW
1843 * information is desired. This means that nl_langinfo() and MB_CUR_MAX
1844 * should give the correct results */
119ee68b 1845
1d958db2
KW
1846# if defined(HAS_NL_LANGINFO) && defined(CODESET)
1847 {
4f72bb37 1848 char *codeset = nl_langinfo(CODESET);
1d958db2 1849 if (codeset && strNE(codeset, "")) {
4f72bb37 1850 codeset = savepv(codeset);
119ee68b 1851
1d958db2
KW
1852 /* If we switched LC_CTYPE, switch back */
1853 if (save_ctype_locale) {
1854 setlocale(LC_CTYPE, save_ctype_locale);
1855 Safefree(save_ctype_locale);
1856 }
1857
1858 is_utf8 = foldEQ(codeset, STR_WITH_LEN("UTF-8"))
1859 || foldEQ(codeset, STR_WITH_LEN("UTF8"));
1860
69014004
KW
1861 DEBUG_L(PerlIO_printf(Perl_debug_log,
1862 "\tnllanginfo returned CODESET '%s'; ?UTF8 locale=%d\n",
1863 codeset, is_utf8));
1d958db2
KW
1864 Safefree(codeset);
1865 Safefree(save_input_locale);
1866 return is_utf8;
1867 }
119ee68b
KW
1868 }
1869
1d958db2
KW
1870# endif
1871# ifdef MB_CUR_MAX
1872
1873 /* Here, either we don't have nl_langinfo, or it didn't return a
1874 * codeset. Try MB_CUR_MAX */
1875
119ee68b
KW
1876 /* Standard UTF-8 needs at least 4 bytes to represent the maximum
1877 * Unicode code point. Since UTF-8 is the only non-single byte
1878 * encoding we handle, we just say any such encoding is UTF-8, and if
1879 * turns out to be wrong, other things will fail */
1880 is_utf8 = MB_CUR_MAX >= 4;
1881
69014004
KW
1882 DEBUG_L(PerlIO_printf(Perl_debug_log,
1883 "\tMB_CUR_MAX=%d; ?UTF8 locale=%d\n",
1884 (int) MB_CUR_MAX, is_utf8));
1885
119ee68b
KW
1886 Safefree(save_input_locale);
1887
1888# ifdef HAS_MBTOWC
1889
1890 /* ... But, most system that have MB_CUR_MAX will also have mbtowc(),
1891 * since they are both in the C99 standard. We can feed a known byte
1892 * string to the latter function, and check that it gives the expected
1893 * result */
1894 if (is_utf8) {
1895 wchar_t wc;
856b881c 1896 PERL_UNUSED_RESULT(mbtowc(&wc, NULL, 0));/* Reset any shift state */
69014004 1897 errno = 0;
f019f68f 1898 if ((size_t)mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8))
119ee68b
KW
1899 != strlen(HYPHEN_UTF8)
1900 || wc != (wchar_t) 0x2010)
1901 {
1902 is_utf8 = FALSE;
abdcbdb8 1903 DEBUG_L(PerlIO_printf(Perl_debug_log, "\thyphen=U+%x\n", (unsigned int)wc));
69014004
KW
1904 DEBUG_L(PerlIO_printf(Perl_debug_log,
1905 "\treturn from mbtowc=%d; errno=%d; ?UTF8 locale=0\n",
1906 mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8)), errno));
119ee68b
KW
1907 }
1908 }
119ee68b
KW
1909# endif
1910
1d958db2
KW
1911 /* If we switched LC_CTYPE, switch back */
1912 if (save_ctype_locale) {
1913 setlocale(LC_CTYPE, save_ctype_locale);
1914 Safefree(save_ctype_locale);
119ee68b 1915 }
7d74bb61 1916
1d958db2 1917 return is_utf8;
119ee68b 1918# endif
7d74bb61 1919 }
119ee68b 1920
7d74bb61
KW
1921 cant_use_nllanginfo:
1922
0080c90a
KW
1923#else /* nl_langinfo should work if available, so don't bother compiling this
1924 fallback code. The final fallback of looking at the name is
1925 compiled, and will be executed if nl_langinfo fails */
7d74bb61 1926
97f4de96
KW
1927 /* nl_langinfo not available or failed somehow. Next try looking at the
1928 * currency symbol to see if it disambiguates things. Often that will be
1929 * in the native script, and if the symbol isn't in UTF-8, we know that the
1930 * locale isn't. If it is non-ASCII UTF-8, we infer that the locale is
609548d2
KW
1931 * too, as the odds of a non-UTF8 string being valid UTF-8 are quite small
1932 * */
fa9b773e
KW
1933
1934#ifdef HAS_LOCALECONV
fa9b773e 1935# ifdef USE_LOCALE_MONETARY
fa9b773e
KW
1936 {
1937 char *save_monetary_locale = NULL;
fa9b773e 1938 bool only_ascii = FALSE;
13542a67
KW
1939 bool is_utf8 = FALSE;
1940 struct lconv* lc;
fa9b773e 1941
97f4de96
KW
1942 /* Like above for LC_CTYPE, we first set LC_MONETARY to the locale of
1943 * the desired category, if it isn't that locale already */
1944
fa9b773e
KW
1945 if (category != LC_MONETARY) {
1946
4f72bb37 1947 save_monetary_locale = setlocale(LC_MONETARY, NULL);
fa9b773e 1948 if (! save_monetary_locale) {
69014004
KW
1949 DEBUG_L(PerlIO_printf(Perl_debug_log,
1950 "Could not find current locale for LC_MONETARY\n"));
fa9b773e
KW
1951 goto cant_use_monetary;
1952 }
4f72bb37 1953 save_monetary_locale = stdize_locale(savepv(save_monetary_locale));
fa9b773e 1954
13542a67
KW
1955 if (strEQ(save_monetary_locale, save_input_locale)) {
1956 Safefree(save_monetary_locale);
1957 save_monetary_locale = NULL;
1958 }
1959 else if (! setlocale(LC_MONETARY, save_input_locale)) {
59c234b4
KW
1960 DEBUG_L(PerlIO_printf(Perl_debug_log,
1961 "Could not change LC_MONETARY locale to %s\n",
1962 save_input_locale));
1963 Safefree(save_monetary_locale);
1964 goto cant_use_monetary;
fa9b773e
KW
1965 }
1966 }
1967
1968 /* Here the current LC_MONETARY is set to the locale of the category
1969 * whose information is desired. */
1970
13542a67
KW
1971 lc = localeconv();
1972 if (! lc
1973 || ! lc->currency_symbol
9f10db87 1974 || is_invariant_string((U8 *) lc->currency_symbol, 0))
13542a67
KW
1975 {
1976 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));
1977 only_ascii = TRUE;
1978 }
1979 else {
1980 is_utf8 = is_utf8_string((U8 *) lc->currency_symbol, 0);
fa9b773e
KW
1981 }
1982
1983 /* If we changed it, restore LC_MONETARY to its original locale */
1984 if (save_monetary_locale) {
1985 setlocale(LC_MONETARY, save_monetary_locale);
1986 Safefree(save_monetary_locale);
1987 }
1988
13542a67 1989 if (! only_ascii) {
fa9b773e 1990
59c234b4
KW
1991 /* It isn't a UTF-8 locale if the symbol is not legal UTF-8;
1992 * otherwise assume the locale is UTF-8 if and only if the symbol
1993 * is non-ascii UTF-8. */
1994 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?Currency symbol for %s is UTF-8=%d\n",
1995 save_input_locale, is_utf8));
1996 Safefree(save_input_locale);
1997 return is_utf8;
13542a67 1998 }
fa9b773e
KW
1999 }
2000 cant_use_monetary:
2001
2002# endif /* USE_LOCALE_MONETARY */
2003#endif /* HAS_LOCALECONV */
2004
15f7e74e
KW
2005#if defined(HAS_STRFTIME) && defined(USE_LOCALE_TIME)
2006
2007/* Still haven't found a non-ASCII string to disambiguate UTF-8 or not. Try
2008 * the names of the months and weekdays, timezone, and am/pm indicator */
2009 {
2010 char *save_time_locale = NULL;
2011 int hour = 10;
2012 bool is_dst = FALSE;
2013 int dom = 1;
2014 int month = 0;
2015 int i;
2016 char * formatted_time;
2017
2018
2019 /* Like above for LC_MONETARY, we set LC_TIME to the locale of the
2020 * desired category, if it isn't that locale already */
2021
2022 if (category != LC_TIME) {
2023
2024 save_time_locale = setlocale(LC_TIME, NULL);
2025 if (! save_time_locale) {
2026 DEBUG_L(PerlIO_printf(Perl_debug_log,
2027 "Could not find current locale for LC_TIME\n"));
2028 goto cant_use_time;
2029 }
2030 save_time_locale = stdize_locale(savepv(save_time_locale));
2031
2032 if (strEQ(save_time_locale, save_input_locale)) {
2033 Safefree(save_time_locale);
2034 save_time_locale = NULL;
2035 }
2036 else if (! setlocale(LC_TIME, save_input_locale)) {
2037 DEBUG_L(PerlIO_printf(Perl_debug_log,
2038 "Could not change LC_TIME locale to %s\n",
2039 save_input_locale));
2040 Safefree(save_time_locale);
2041 goto cant_use_time;
2042 }
2043 }
2044
2045 /* Here the current LC_TIME is set to the locale of the category
2046 * whose information is desired. Look at all the days of the week and
9f10db87 2047 * month names, and the timezone and am/pm indicator for UTF-8 variant
15f7e74e
KW
2048 * characters. The first such a one found will tell us if the locale
2049 * is UTF-8 or not */
2050
2051 for (i = 0; i < 7 + 12; i++) { /* 7 days; 12 months */
2052 formatted_time = my_strftime("%A %B %Z %p",
2053 0, 0, hour, dom, month, 112, 0, 0, is_dst);
9f10db87 2054 if (! formatted_time || is_invariant_string((U8 *) formatted_time, 0)) {
15f7e74e
KW
2055
2056 /* Here, we didn't find a non-ASCII. Try the next time through
2057 * with the complemented dst and am/pm, and try with the next
2058 * weekday. After we have gotten all weekdays, try the next
2059 * month */
2060 is_dst = ! is_dst;
2061 hour = (hour + 12) % 24;
2062 dom++;
2063 if (i > 6) {
2064 month++;
2065 }
2066 continue;
2067 }
2068
2069 /* Here, we have a non-ASCII. Return TRUE is it is valid UTF8;
2070 * false otherwise. But first, restore LC_TIME to its original
2071 * locale if we changed it */
2072 if (save_time_locale) {
2073 setlocale(LC_TIME, save_time_locale);
2074 Safefree(save_time_locale);
2075 }
2076
2077 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?time-related strings for %s are UTF-8=%d\n",
2078 save_input_locale,
2079 is_utf8_string((U8 *) formatted_time, 0)));
2080 Safefree(save_input_locale);
2081 return is_utf8_string((U8 *) formatted_time, 0);
2082 }
2083
2084 /* Falling off the end of the loop indicates all the names were just
2085 * ASCII. Go on to the next test. If we changed it, restore LC_TIME
2086 * to its original locale */
2087 if (save_time_locale) {
2088 setlocale(LC_TIME, save_time_locale);
2089 Safefree(save_time_locale);
2090 }
2091 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));
2092 }
2093 cant_use_time:
2094
2095#endif
2096
2097#if 0 && defined(USE_LOCALE_MESSAGES) && defined(HAS_SYS_ERRLIST)
855aeb93
JH
2098
2099/* This code is ifdefd out because it was found to not be necessary in testing
5857e934
KW
2100 * on our dromedary test machine, which has over 700 locales. There, this
2101 * added no value to looking at the currency symbol and the time strings. I
2102 * left it in so as to avoid rewriting it if real-world experience indicates
2103 * that dromedary is an outlier. Essentially, instead of returning abpve if we
855aeb93
JH
2104 * haven't found illegal utf8, we continue on and examine all the strerror()
2105 * messages on the platform for utf8ness. If all are ASCII, we still don't
2106 * know the answer; but otherwise we have a pretty good indication of the
5857e934
KW
2107 * utf8ness. The reason this doesn't help much is that the messages may not
2108 * have been translated into the locale. The currency symbol and time strings
2109 * are much more likely to have been translated. */
2110 {
855aeb93 2111 int e;
5857e934
KW
2112 bool is_utf8 = FALSE;
2113 bool non_ascii = FALSE;
855aeb93 2114 char *save_messages_locale = NULL;
5857e934 2115 const char * errmsg = NULL;
855aeb93 2116
5857e934
KW
2117 /* Like above, we set LC_MESSAGES to the locale of the desired
2118 * category, if it isn't that locale already */
855aeb93
JH
2119
2120 if (category != LC_MESSAGES) {
2121
5857e934 2122 save_messages_locale = setlocale(LC_MESSAGES, NULL);
855aeb93 2123 if (! save_messages_locale) {
5857e934
KW
2124 DEBUG_L(PerlIO_printf(Perl_debug_log,
2125 "Could not find current locale for LC_MESSAGES\n"));
855aeb93
JH
2126 goto cant_use_messages;
2127 }
5857e934 2128 save_messages_locale = stdize_locale(savepv(save_messages_locale));
855aeb93
JH
2129
2130 if (strEQ(save_messages_locale, save_input_locale)) {
5857e934
KW
2131 Safefree(save_messages_locale);
2132 save_messages_locale = NULL;
855aeb93
JH
2133 }
2134 else if (! setlocale(LC_MESSAGES, save_input_locale)) {
5857e934
KW
2135 DEBUG_L(PerlIO_printf(Perl_debug_log,
2136 "Could not change LC_MESSAGES locale to %s\n",
2137 save_input_locale));
855aeb93
JH
2138 Safefree(save_messages_locale);
2139 goto cant_use_messages;
2140 }
2141 }
2142
2143 /* Here the current LC_MESSAGES is set to the locale of the category
5857e934
KW
2144 * whose information is desired. Look through all the messages. We
2145 * can't use Strerror() here because it may expand to code that
2146 * segfaults in miniperl */
855aeb93 2147
5857e934
KW
2148 for (e = 0; e <= sys_nerr; e++) {
2149 errno = 0;
2150 errmsg = sys_errlist[e];
2151 if (errno || !errmsg) {
855aeb93
JH
2152 break;
2153 }
5857e934 2154 errmsg = savepv(errmsg);
9f10db87 2155 if (! is_invariant_string((U8 *) errmsg, 0)) {
5857e934
KW
2156 non_ascii = TRUE;
2157 is_utf8 = is_utf8_string((U8 *) errmsg, 0);
2158 break;
855aeb93
JH
2159 }
2160 }
5857e934 2161 Safefree(errmsg);
855aeb93
JH
2162
2163 /* And, if we changed it, restore LC_MESSAGES to its original locale */
2164 if (save_messages_locale) {
2165 setlocale(LC_MESSAGES, save_messages_locale);
2166 Safefree(save_messages_locale);
2167 }
2168
5857e934
KW
2169 if (non_ascii) {
2170
2171 /* Any non-UTF-8 message means not a UTF-8 locale; if all are valid,
2172 * any non-ascii means it is one; otherwise we assume it isn't */
2173 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?error messages for %s are UTF-8=%d\n",
2174 save_input_locale,
2175 is_utf8));
2176 Safefree(save_input_locale);
2177 return is_utf8;
2178 }
855aeb93 2179
5857e934 2180 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
2181 }
2182 cant_use_messages:
2183
2184#endif
fa9b773e 2185
0080c90a
KW
2186#endif /* the code that is compiled when no nl_langinfo */
2187
92c0a900
KW
2188#ifndef EBCDIC /* On os390, even if the name ends with "UTF-8', it isn't a
2189 UTF-8 locale */
97f4de96
KW
2190 /* As a last resort, look at the locale name to see if it matches
2191 * qr/UTF -? * 8 /ix, or some other common locale names. This "name", the
2192 * return of setlocale(), is actually defined to be opaque, so we can't
2193 * really rely on the absence of various substrings in the name to indicate
2194 * its UTF-8ness, but if it has UTF8 in the name, it is extremely likely to
2195 * be a UTF-8 locale. Similarly for the other common names */
2196
2197 final_pos = strlen(save_input_locale) - 1;
2198 if (final_pos >= 3) {
2199 char *name = save_input_locale;
2200
2201 /* Find next 'U' or 'u' and look from there */
2202 while ((name += strcspn(name, "Uu") + 1)
2203 <= save_input_locale + final_pos - 2)
2204 {
305b8651
KW
2205 if (!isALPHA_FOLD_NE(*name, 't')
2206 || isALPHA_FOLD_NE(*(name + 1), 'f'))
97f4de96
KW
2207 {
2208 continue;
2209 }
2210 name += 2;
2211 if (*(name) == '-') {
2212 if ((name > save_input_locale + final_pos - 1)) {
2213 break;
2214 }
2215 name++;
2216 }
2217 if (*(name) == '8') {
97f4de96
KW
2218 DEBUG_L(PerlIO_printf(Perl_debug_log,
2219 "Locale %s ends with UTF-8 in name\n",
2220 save_input_locale));
00c54b9c 2221 Safefree(save_input_locale);
97f4de96
KW
2222 return TRUE;
2223 }
2224 }
2225 DEBUG_L(PerlIO_printf(Perl_debug_log,
2226 "Locale %s doesn't end with UTF-8 in name\n",
2227 save_input_locale));
2228 }
92c0a900 2229#endif
97f4de96
KW
2230
2231#ifdef WIN32
2232 /* http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756.aspx */
2233 if (final_pos >= 4
2234 && *(save_input_locale + final_pos - 0) == '1'
2235 && *(save_input_locale + final_pos - 1) == '0'
2236 && *(save_input_locale + final_pos - 2) == '0'
2237 && *(save_input_locale + final_pos - 3) == '5'
2238 && *(save_input_locale + final_pos - 4) == '6')
2239 {
2240 DEBUG_L(PerlIO_printf(Perl_debug_log,
2241 "Locale %s ends with 10056 in name, is UTF-8 locale\n",
2242 save_input_locale));
2243 Safefree(save_input_locale);
2244 return TRUE;
2245 }
2246#endif
2247
2248 /* Other common encodings are the ISO 8859 series, which aren't UTF-8. But
2249 * since we are about to return FALSE anyway, there is no point in doing
2250 * this extra work */
2251#if 0
2252 if (instr(save_input_locale, "8859")) {
2253 DEBUG_L(PerlIO_printf(Perl_debug_log,
2254 "Locale %s has 8859 in name, not UTF-8 locale\n",
2255 save_input_locale));
2256 Safefree(save_input_locale);
2257 return FALSE;
2258 }
2259#endif
2260
69014004
KW
2261 DEBUG_L(PerlIO_printf(Perl_debug_log,
2262 "Assuming locale %s is not a UTF-8 locale\n",
2263 save_input_locale));
fa9b773e 2264 Safefree(save_input_locale);
7d74bb61
KW
2265 return FALSE;
2266}
2267
8ef6e574 2268#endif
7d74bb61 2269
d6ded950
KW
2270
2271bool
2272Perl__is_in_locale_category(pTHX_ const bool compiling, const int category)
2273{
1a4f13e1 2274 dVAR;
d6ded950
KW
2275 /* Internal function which returns if we are in the scope of a pragma that
2276 * enables the locale category 'category'. 'compiling' should indicate if
2277 * this is during the compilation phase (TRUE) or not (FALSE). */
2278
2279 const COP * const cop = (compiling) ? &PL_compiling : PL_curcop;
2280
2281 SV *categories = cop_hints_fetch_pvs(cop, "locale", 0);
2282 if (! categories || categories == &PL_sv_placeholder) {
2283 return FALSE;
2284 }
2285
2286 /* The pseudo-category 'not_characters' is -1, so just add 1 to each to get
2287 * a valid unsigned */
2288 assert(category >= -1);
2289 return cBOOL(SvUV(categories) & (1U << (category + 1)));
2290}
2291
2c6ee1a7
KW
2292char *
2293Perl_my_strerror(pTHX_ const int errnum) {
a0b53297 2294 dVAR;
2c6ee1a7
KW
2295
2296 /* Uses C locale for the error text unless within scope of 'use locale' for
2297 * LC_MESSAGES */
2298
2299#ifdef USE_LOCALE_MESSAGES
8ee4b769 2300 if (! IN_LC(LC_MESSAGES)) {
a0b53297
KW
2301 char * save_locale;
2302
2303 /* We have a critical section to prevent another thread from changing
2304 * the locale out from under us (or zapping the buffer returned from
2305 * setlocale() ) */
2306 LOCALE_LOCK;
2307
2308 save_locale = setlocale(LC_MESSAGES, NULL);
a39edc4c 2309 if (! isNAME_C_OR_POSIX(save_locale)) {
2c6ee1a7
KW
2310 char *errstr;
2311
2312 /* The next setlocale likely will zap this, so create a copy */
2313 save_locale = savepv(save_locale);
2314
2315 setlocale(LC_MESSAGES, "C");
2316
2317 /* This points to the static space in Strerror, with all its
2318 * limitations */
2319 errstr = Strerror(errnum);
2320
2321 setlocale(LC_MESSAGES, save_locale);
2322 Safefree(save_locale);
a0b53297
KW
2323
2324 LOCALE_UNLOCK;
2325
2c6ee1a7
KW
2326 return errstr;
2327 }
a0b53297
KW
2328
2329 LOCALE_UNLOCK;
2c6ee1a7
KW
2330 }
2331#endif
2332
2333 return Strerror(errnum);
2334}
2335
66610fdd 2336/*
747c467a
KW
2337
2338=head1 Locale-related functions and macros
2339
2340=for apidoc sync_locale
2341
2342Changing the program's locale should be avoided by XS code. Nevertheless,
2343certain non-Perl libraries called from XS, such as C<Gtk> do so. When this
2344happens, Perl needs to be told that the locale has changed. Use this function
2345to do so, before returning to Perl.
2346
2347=cut
2348*/
2349
2350void
2351Perl_sync_locale(pTHX)
2352{
2353
2354#ifdef USE_LOCALE_CTYPE
2355 new_ctype(setlocale(LC_CTYPE, NULL));
2356#endif /* USE_LOCALE_CTYPE */
2357
2358#ifdef USE_LOCALE_COLLATE
2359 new_collate(setlocale(LC_COLLATE, NULL));
2360#endif
2361
2362#ifdef USE_LOCALE_NUMERIC
2363 set_numeric_local(); /* Switch from "C" to underlying LC_NUMERIC */
2364 new_numeric(setlocale(LC_NUMERIC, NULL));
2365#endif /* USE_LOCALE_NUMERIC */
2366
2367}
2368
5d1187d1
KW
2369#if defined(DEBUGGING) && defined(USE_LOCALE)
2370
2371char *
2372Perl__setlocale_debug_string(const int category, /* category number,
2373 like LC_ALL */
2374 const char* const locale, /* locale name */
2375
2376 /* return value from setlocale() when attempting to
2377 * set 'category' to 'locale' */
2378 const char* const retval)
2379{
2380 /* Returns a pointer to a NUL-terminated string in static storage with
2381 * added text about the info passed in. This is not thread safe and will
2382 * be overwritten by the next call, so this should be used just to
fa07b8e5 2383 * formulate a string to immediately print or savepv() on. */
5d1187d1 2384
398a990f
DM
2385 /* initialise to a non-null value to keep it out of BSS and so keep
2386 * -DPERL_GLOBAL_STRUCT_PRIVATE happy */
2387 static char ret[128] = "x";
5d1187d1 2388
fa07b8e5 2389 my_strlcpy(ret, "setlocale(", sizeof(ret));
5d1187d1
KW
2390
2391 switch (category) {
2392 default:
fa07b8e5 2393 my_snprintf(ret, sizeof(ret), "%s? %d", ret, category);
5d1187d1
KW
2394 break;
2395# ifdef LC_ALL
2396 case LC_ALL:
fa07b8e5 2397 my_strlcat(ret, "LC_ALL", sizeof(ret));
5d1187d1
KW
2398 break;
2399# endif
2400# ifdef LC_CTYPE
2401 case LC_CTYPE:
fa07b8e5 2402 my_strlcat(ret, "LC_CTYPE", sizeof(ret));
5d1187d1
KW
2403 break;
2404# endif
2405# ifdef LC_NUMERIC
2406 case LC_NUMERIC:
fa07b8e5 2407 my_strlcat(ret, "LC_NUMERIC", sizeof(ret));
5d1187d1
KW
2408 break;
2409# endif
2410# ifdef LC_COLLATE
2411 case LC_COLLATE:
fa07b8e5 2412 my_strlcat(ret, "LC_COLLATE", sizeof(ret));
5d1187d1
KW
2413 break;
2414# endif
2415# ifdef LC_TIME
2416 case LC_TIME:
fa07b8e5 2417 my_strlcat(ret, "LC_TIME", sizeof(ret));
5d1187d1
KW
2418 break;
2419# endif
2420# ifdef LC_MONETARY
2421 case LC_MONETARY:
fa07b8e5 2422 my_strlcat(ret, "LC_MONETARY", sizeof(ret));
5d1187d1
KW
2423 break;
2424# endif
2425# ifdef LC_MESSAGES
2426 case LC_MESSAGES:
fa07b8e5 2427 my_strlcat(ret, "LC_MESSAGES", sizeof(ret));
5d1187d1
KW
2428 break;
2429# endif
2430 }
2431
fa07b8e5 2432 my_strlcat(ret, ", ", sizeof(ret));
5d1187d1
KW
2433
2434 if (locale) {
fa07b8e5
KW
2435 my_strlcat(ret, "\"", sizeof(ret));
2436 my_strlcat(ret, locale, sizeof(ret));
2437 my_strlcat(ret, "\"", sizeof(ret));
5d1187d1
KW
2438 }
2439 else {
fa07b8e5 2440 my_strlcat(ret, "NULL", sizeof(ret));
5d1187d1
KW
2441 }
2442
fa07b8e5 2443 my_strlcat(ret, ") returned ", sizeof(ret));
5d1187d1
KW
2444
2445 if (retval) {
fa07b8e5
KW
2446 my_strlcat(ret, "\"", sizeof(ret));
2447 my_strlcat(ret, retval, sizeof(ret));
2448 my_strlcat(ret, "\"", sizeof(ret));
5d1187d1
KW
2449 }
2450 else {
fa07b8e5 2451 my_strlcat(ret, "NULL", sizeof(ret));
5d1187d1
KW
2452 }
2453
2454 assert(strlen(ret) < sizeof(ret));
2455
2456 return ret;
2457}
2458
2459#endif
747c467a
KW
2460
2461
2462/*
14d04a33 2463 * ex: set ts=8 sts=4 sw=4 et:
37442d52 2464 */