This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
locale.c: Not so aggressive collation memory use guess
[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 }
58eebef2
KW
669
670#ifdef DEBUGGING
671 if (DEBUG_L_TEST || debug_initialization) {
672 PerlIO_printf(Perl_debug_log,
673 "%s:%d: ?UTF-8 locale=%d; x_len_shorter=%"UVuf", "
674 "x_len_longer=%"UVuf","
675 " collate multipler=%"UVuf", collate base=%"UVuf"\n",
676 __FILE__, __LINE__,
677 PL_in_utf8_COLLATE_locale,
678 x_len_shorter, x_len_longer,
679 PL_collxfrm_mult, PL_collxfrm_base);
680 }
681#endif
98994639
HS
682 }
683 }
684
f2ce9e1c
JH
685#else
686 PERL_UNUSED_ARG(newcoll);
98994639
HS
687#endif /* USE_LOCALE_COLLATE */
688}
689
b385bb4d
KW
690#ifdef WIN32
691
692char *
693Perl_my_setlocale(pTHX_ int category, const char* locale)
694{
695 /* This, for Windows, emulates POSIX setlocale() behavior. There is no
696 * difference unless the input locale is "", which means on Windows to get
697 * the machine default, which is set via the computer's "Regional and
698 * Language Options" (or its current equivalent). In POSIX, it instead
699 * means to find the locale from the user's environment. This routine
700 * looks in the environment, and, if anything is found, uses that instead
701 * of going to the machine default. If there is no environment override,
702 * the machine default is used, as normal, by calling the real setlocale()
703 * with "". The POSIX behavior is to use the LC_ALL variable if set;
704 * otherwise to use the particular category's variable if set; otherwise to
705 * use the LANG variable. */
706
175c4cf9 707 bool override_LC_ALL = FALSE;
89f7b9aa
KW
708 char * result;
709
b385bb4d
KW
710 if (locale && strEQ(locale, "")) {
711# ifdef LC_ALL
712 locale = PerlEnv_getenv("LC_ALL");
713 if (! locale) {
714#endif
715 switch (category) {
716# ifdef LC_ALL
717 case LC_ALL:
481465ea 718 override_LC_ALL = TRUE;
b385bb4d
KW
719 break; /* We already know its variable isn't set */
720# endif
721# ifdef USE_LOCALE_TIME
722 case LC_TIME:
723 locale = PerlEnv_getenv("LC_TIME");
724 break;
725# endif
726# ifdef USE_LOCALE_CTYPE
727 case LC_CTYPE:
728 locale = PerlEnv_getenv("LC_CTYPE");
729 break;
730# endif
731# ifdef USE_LOCALE_COLLATE
732 case LC_COLLATE:
733 locale = PerlEnv_getenv("LC_COLLATE");
734 break;
735# endif
736# ifdef USE_LOCALE_MONETARY
737 case LC_MONETARY:
738 locale = PerlEnv_getenv("LC_MONETARY");
739 break;
740# endif
741# ifdef USE_LOCALE_NUMERIC
742 case LC_NUMERIC:
743 locale = PerlEnv_getenv("LC_NUMERIC");
744 break;
745# endif
746# ifdef USE_LOCALE_MESSAGES
747 case LC_MESSAGES:
748 locale = PerlEnv_getenv("LC_MESSAGES");
749 break;
750# endif
751 default:
752 /* This is a category, like PAPER_SIZE that we don't
753 * know about; and so can't provide a wrapper. */
754 break;
755 }
756 if (! locale) {
757 locale = PerlEnv_getenv("LANG");
481465ea 758 if (! locale) {
b385bb4d
KW
759 locale = "";
760 }
761 }
762# ifdef LC_ALL
763 }
764# endif
765 }
766
89f7b9aa 767 result = setlocale(category, locale);
bbc98134
KW
768 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n", __FILE__, __LINE__,
769 _setlocale_debug_string(category, locale, result)));
89f7b9aa 770
481465ea 771 if (! override_LC_ALL) {
89f7b9aa
KW
772 return result;
773 }
774
dfd77d7a 775 /* Here the input category was LC_ALL, and we have set it to what is in the
481465ea
KW
776 * LANG variable or the system default if there is no LANG. But these have
777 * lower priority than the other LC_foo variables, so override it for each
778 * one that is set. (If they are set to "", it means to use the same thing
779 * we just set LC_ALL to, so can skip) */
89f7b9aa
KW
780# ifdef USE_LOCALE_TIME
781 result = PerlEnv_getenv("LC_TIME");
730252b2 782 if (result && strNE(result, "")) {
89f7b9aa 783 setlocale(LC_TIME, result);
bbc98134
KW
784 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
785 __FILE__, __LINE__,
786 _setlocale_debug_string(LC_TIME, result, "not captured")));
89f7b9aa
KW
787 }
788# endif
789# ifdef USE_LOCALE_CTYPE
790 result = PerlEnv_getenv("LC_CTYPE");
730252b2 791 if (result && strNE(result, "")) {
89f7b9aa 792 setlocale(LC_CTYPE, result);
bbc98134
KW
793 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
794 __FILE__, __LINE__,
795 _setlocale_debug_string(LC_CTYPE, result, "not captured")));
89f7b9aa
KW
796 }
797# endif
798# ifdef USE_LOCALE_COLLATE
799 result = PerlEnv_getenv("LC_COLLATE");
730252b2 800 if (result && strNE(result, "")) {
89f7b9aa 801 setlocale(LC_COLLATE, result);
bbc98134
KW
802 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
803 __FILE__, __LINE__,
804 _setlocale_debug_string(LC_COLLATE, result, "not captured")));
89f7b9aa
KW
805 }
806# endif
807# ifdef USE_LOCALE_MONETARY
808 result = PerlEnv_getenv("LC_MONETARY");
730252b2 809 if (result && strNE(result, "")) {
89f7b9aa 810 setlocale(LC_MONETARY, result);
bbc98134
KW
811 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
812 __FILE__, __LINE__,
813 _setlocale_debug_string(LC_MONETARY, result, "not captured")));
89f7b9aa
KW
814 }
815# endif
816# ifdef USE_LOCALE_NUMERIC
817 result = PerlEnv_getenv("LC_NUMERIC");
730252b2 818 if (result && strNE(result, "")) {
89f7b9aa 819 setlocale(LC_NUMERIC, result);
bbc98134
KW
820 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
821 __FILE__, __LINE__,
822 _setlocale_debug_string(LC_NUMERIC, result, "not captured")));
89f7b9aa
KW
823 }
824# endif
825# ifdef USE_LOCALE_MESSAGES
826 result = PerlEnv_getenv("LC_MESSAGES");
730252b2 827 if (result && strNE(result, "")) {
89f7b9aa 828 setlocale(LC_MESSAGES, result);
bbc98134
KW
829 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
830 __FILE__, __LINE__,
831 _setlocale_debug_string(LC_MESSAGES, result, "not captured")));
89f7b9aa
KW
832 }
833# endif
834
bbc98134
KW
835 result = setlocale(LC_ALL, NULL);
836 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
837 __FILE__, __LINE__,
838 _setlocale_debug_string(LC_ALL, NULL, result)));
89f7b9aa 839
bbc98134 840 return result;
b385bb4d
KW
841}
842
843#endif
844
845
98994639
HS
846/*
847 * Initialize locale awareness.
848 */
849int
850Perl_init_i18nl10n(pTHX_ int printwarn)
851{
0e92a118
KW
852 /* printwarn is
853 *
854 * 0 if not to output warning when setup locale is bad
855 * 1 if to output warning based on value of PERL_BADLANG
856 * >1 if to output regardless of PERL_BADLANG
857 *
858 * returns
98994639 859 * 1 = set ok or not applicable,
0e92a118
KW
860 * 0 = fallback to a locale of lower priority
861 * -1 = fallback to all locales failed, not even to the C locale
6b058d42
KW
862 *
863 * Under -DDEBUGGING, if the environment variable PERL_DEBUG_LOCALE_INIT is
864 * set, debugging information is output.
865 *
866 * This looks more complicated than it is, mainly due to the #ifdefs.
867 *
868 * We try to set LC_ALL to the value determined by the environment. If
869 * there is no LC_ALL on this platform, we try the individual categories we
870 * know about. If this works, we are done.
871 *
872 * But if it doesn't work, we have to do something else. We search the
873 * environment variables ourselves instead of relying on the system to do
874 * it. We look at, in order, LC_ALL, LANG, a system default locale (if we
875 * think there is one), and the ultimate fallback "C". This is all done in
876 * the same loop as above to avoid duplicating code, but it makes things
877 * more complex. After the original failure, we add the fallback
878 * possibilities to the list of locales to try, and iterate the loop
879 * through them all until one succeeds.
880 *
881 * On Ultrix, the locale MUST come from the environment, so there is
882 * preliminary code to set it. I (khw) am not sure that it is necessary,
883 * and that this couldn't be folded into the loop, but barring any real
884 * platforms to test on, it's staying as-is
885 *
886 * A slight complication is that in embedded Perls, the locale may already
887 * be set-up, and we don't want to get it from the normal environment
888 * variables. This is handled by having a special environment variable
889 * indicate we're in this situation. We simply set setlocale's 2nd
890 * parameter to be a NULL instead of "". That indicates to setlocale that
891 * it is not to change anything, but to return the current value,
892 * effectively initializing perl's db to what the locale already is.
893 *
894 * We play the same trick with NULL if a LC_ALL succeeds. We call
895 * setlocale() on the individual categores with NULL to get their existing
896 * values for our db, instead of trying to change them.
897 * */
98994639 898
0e92a118
KW
899 int ok = 1;
900
98994639 901#if defined(USE_LOCALE)
98994639
HS
902#ifdef USE_LOCALE_CTYPE
903 char *curctype = NULL;
904#endif /* USE_LOCALE_CTYPE */
905#ifdef USE_LOCALE_COLLATE
906 char *curcoll = NULL;
907#endif /* USE_LOCALE_COLLATE */
908#ifdef USE_LOCALE_NUMERIC
909 char *curnum = NULL;
910#endif /* USE_LOCALE_NUMERIC */
911#ifdef __GLIBC__
175c4cf9 912 const char * const language = savepv(PerlEnv_getenv("LANGUAGE"));
98994639 913#endif
65ebb059 914
ccd65d51
KW
915 /* NULL uses the existing already set up locale */
916 const char * const setlocale_init = (PerlEnv_getenv("PERL_SKIP_LOCALE_INIT"))
917 ? NULL
918 : "";
c3fcd832
KW
919 const char* trial_locales[5]; /* 5 = 1 each for "", LC_ALL, LANG, "", C */
920 unsigned int trial_locales_count;
175c4cf9
KW
921 const char * const lc_all = savepv(PerlEnv_getenv("LC_ALL"));
922 const char * const lang = savepv(PerlEnv_getenv("LANG"));
98994639 923 bool setlocale_failure = FALSE;
65ebb059
KW
924 unsigned int i;
925 char *p;
175c4cf9
KW
926
927 /* A later getenv() could zap this, so only use here */
928 const char * const bad_lang_use_once = PerlEnv_getenv("PERL_BADLANG");
929
930 const bool locwarn = (printwarn > 1
931 || (printwarn
932 && (! bad_lang_use_once
22ff3130
HS
933 || (
934 /* disallow with "" or "0" */
935 *bad_lang_use_once
936 && strNE("0", bad_lang_use_once)))));
0e92a118 937 bool done = FALSE;
5d1187d1
KW
938 char * sl_result; /* return from setlocale() */
939 char * locale_param;
6bce99ee
JH
940#ifdef WIN32
941 /* In some systems you can find out the system default locale
942 * and use that as the fallback locale. */
943# define SYSTEM_DEFAULT_LOCALE
944#endif
945#ifdef SYSTEM_DEFAULT_LOCALE
65ebb059 946 const char *system_default_locale = NULL;
6bce99ee 947#endif
98994639 948
2fcc0ca9
KW
949#ifdef DEBUGGING
950 debug_initialization = (PerlEnv_getenv("PERL_DEBUG_LOCALE_INIT"))
951 ? TRUE
952 : FALSE;
953# define DEBUG_LOCALE_INIT(category, locale, result) \
954 STMT_START { \
955 if (debug_initialization) { \
956 PerlIO_printf(Perl_debug_log, \
957 "%s:%d: %s\n", \
958 __FILE__, __LINE__, \
959 _setlocale_debug_string(category, \
960 locale, \
961 result)); \
962 } \
963 } STMT_END
964#else
965# define DEBUG_LOCALE_INIT(a,b,c)
966#endif
967
0e92a118
KW
968#ifndef LOCALE_ENVIRON_REQUIRED
969 PERL_UNUSED_VAR(done);
5d1187d1 970 PERL_UNUSED_VAR(locale_param);
0e92a118 971#else
98994639
HS
972
973 /*
974 * Ultrix setlocale(..., "") fails if there are no environment
975 * variables from which to get a locale name.
976 */
977
b3e384bf 978# ifdef LC_ALL
98994639 979 if (lang) {
5d1187d1
KW
980 sl_result = my_setlocale(LC_ALL, setlocale_init);
981 DEBUG_LOCALE_INIT(LC_ALL, setlocale_init, sl_result);
982 if (sl_result)
98994639
HS
983 done = TRUE;
984 else
985 setlocale_failure = TRUE;
986 }
5d1187d1 987 if (! setlocale_failure) {
b3e384bf 988# ifdef USE_LOCALE_CTYPE
5d1187d1
KW
989 locale_param = (! done && (lang || PerlEnv_getenv("LC_CTYPE")))
990 ? setlocale_init
991 : NULL;
992 curctype = my_setlocale(LC_CTYPE, locale_param);
993 DEBUG_LOCALE_INIT(LC_CTYPE, locale_param, sl_result);
994 if (! curctype)
98994639
HS
995 setlocale_failure = TRUE;
996 else
997 curctype = savepv(curctype);
b3e384bf
KW
998# endif /* USE_LOCALE_CTYPE */
999# ifdef USE_LOCALE_COLLATE
5d1187d1
KW
1000 locale_param = (! done && (lang || PerlEnv_getenv("LC_COLLATE")))
1001 ? setlocale_init
1002 : NULL;
1003 curcoll = my_setlocale(LC_COLLATE, locale_param);
1004 DEBUG_LOCALE_INIT(LC_COLLATE, locale_param, sl_result);
1005 if (! curcoll)
98994639
HS
1006 setlocale_failure = TRUE;
1007 else
1008 curcoll = savepv(curcoll);
b3e384bf
KW
1009# endif /* USE_LOCALE_COLLATE */
1010# ifdef USE_LOCALE_NUMERIC
5d1187d1
KW
1011 locale_param = (! done && (lang || PerlEnv_getenv("LC_NUMERIC")))
1012 ? setlocale_init
1013 : NULL;
1014 curnum = my_setlocale(LC_NUMERIC, locale_param);
1015 DEBUG_LOCALE_INIT(LC_NUMERIC, locale_param, sl_result);
1016 if (! curnum)
98994639
HS
1017 setlocale_failure = TRUE;
1018 else
1019 curnum = savepv(curnum);
b3e384bf 1020# endif /* USE_LOCALE_NUMERIC */
a782673d 1021# ifdef USE_LOCALE_MESSAGES
5d1187d1
KW
1022 locale_param = (! done && (lang || PerlEnv_getenv("LC_MESSAGES")))
1023 ? setlocale_init
1024 : NULL;
1025 sl_result = my_setlocale(LC_MESSAGES, locale_param);
1026 DEBUG_LOCALE_INIT(LC_MESSAGES, locale_param, sl_result);
1027 if (! sl_result)
a782673d
KW
1028 setlocale_failure = TRUE;
1029 }
1030# endif /* USE_LOCALE_MESSAGES */
c835d6be 1031# ifdef USE_LOCALE_MONETARY
5d1187d1
KW
1032 locale_param = (! done && (lang || PerlEnv_getenv("LC_MONETARY")))
1033 ? setlocale_init
1034 : NULL;
1035 sl_result = my_setlocale(LC_MONETARY, locale_param);
1036 DEBUG_LOCALE_INIT(LC_MONETARY, locale_param, sl_result);
1037 if (! sl_result) {
c835d6be
KW
1038 setlocale_failure = TRUE;
1039 }
1040# endif /* USE_LOCALE_MONETARY */
98994639
HS
1041 }
1042
b3e384bf 1043# endif /* LC_ALL */
98994639
HS
1044
1045#endif /* !LOCALE_ENVIRON_REQUIRED */
1046
65ebb059 1047 /* We try each locale in the list until we get one that works, or exhaust
20a240df
KW
1048 * the list. Normally the loop is executed just once. But if setting the
1049 * locale fails, inside the loop we add fallback trials to the array and so
1050 * will execute the loop multiple times */
c3fcd832
KW
1051 trial_locales[0] = setlocale_init;
1052 trial_locales_count = 1;
65ebb059
KW
1053 for (i= 0; i < trial_locales_count; i++) {
1054 const char * trial_locale = trial_locales[i];
1055
1056 if (i > 0) {
1057
1058 /* XXX This is to preserve old behavior for LOCALE_ENVIRON_REQUIRED
1059 * when i==0, but I (khw) don't think that behavior makes much
1060 * sense */
1061 setlocale_failure = FALSE;
1062
6bce99ee
JH
1063#ifdef SYSTEM_DEFAULT_LOCALE
1064# ifdef WIN32
65ebb059
KW
1065 /* On Windows machines, an entry of "" after the 0th means to use
1066 * the system default locale, which we now proceed to get. */
1067 if (strEQ(trial_locale, "")) {
1068 unsigned int j;
1069
1070 /* Note that this may change the locale, but we are going to do
1071 * that anyway just below */
1072 system_default_locale = setlocale(LC_ALL, "");
5d1187d1 1073 DEBUG_LOCALE_INIT(LC_ALL, "", system_default_locale);
65ebb059
KW
1074
1075 /* Skip if invalid or it's already on the list of locales to
1076 * try */
1077 if (! system_default_locale) {
1078 goto next_iteration;
1079 }
1080 for (j = 0; j < trial_locales_count; j++) {
1081 if (strEQ(system_default_locale, trial_locales[j])) {
1082 goto next_iteration;
1083 }
1084 }
1085
1086 trial_locale = system_default_locale;
1087 }
6bce99ee
JH
1088# endif /* WIN32 */
1089#endif /* SYSTEM_DEFAULT_LOCALE */
65ebb059
KW
1090 }
1091
98994639 1092#ifdef LC_ALL
5d1187d1
KW
1093 sl_result = my_setlocale(LC_ALL, trial_locale);
1094 DEBUG_LOCALE_INIT(LC_ALL, trial_locale, sl_result);
1095 if (! sl_result) {
49c85077 1096 setlocale_failure = TRUE;
7cd8b568
KW
1097 }
1098 else {
1099 /* Since LC_ALL succeeded, it should have changed all the other
1100 * categories it can to its value; so we massage things so that the
1101 * setlocales below just return their category's current values.
1102 * This adequately handles the case in NetBSD where LC_COLLATE may
1103 * not be defined for a locale, and setting it individually will
1104 * fail, whereas setting LC_ALL suceeds, leaving LC_COLLATE set to
1105 * the POSIX locale. */
1106 trial_locale = NULL;
1107 }
98994639
HS
1108#endif /* LC_ALL */
1109
49c85077 1110 if (!setlocale_failure) {
98994639 1111#ifdef USE_LOCALE_CTYPE
49c85077 1112 Safefree(curctype);
5d1187d1
KW
1113 curctype = my_setlocale(LC_CTYPE, trial_locale);
1114 DEBUG_LOCALE_INIT(LC_CTYPE, trial_locale, curctype);
1115 if (! curctype)
49c85077
KW
1116 setlocale_failure = TRUE;
1117 else
1118 curctype = savepv(curctype);
98994639
HS
1119#endif /* USE_LOCALE_CTYPE */
1120#ifdef USE_LOCALE_COLLATE
49c85077 1121 Safefree(curcoll);
5d1187d1
KW
1122 curcoll = my_setlocale(LC_COLLATE, trial_locale);
1123 DEBUG_LOCALE_INIT(LC_COLLATE, trial_locale, curcoll);
1124 if (! curcoll)
49c85077
KW
1125 setlocale_failure = TRUE;
1126 else
1127 curcoll = savepv(curcoll);
98994639
HS
1128#endif /* USE_LOCALE_COLLATE */
1129#ifdef USE_LOCALE_NUMERIC
49c85077 1130 Safefree(curnum);
5d1187d1
KW
1131 curnum = my_setlocale(LC_NUMERIC, trial_locale);
1132 DEBUG_LOCALE_INIT(LC_NUMERIC, trial_locale, curnum);
1133 if (! curnum)
49c85077
KW
1134 setlocale_failure = TRUE;
1135 else
1136 curnum = savepv(curnum);
98994639 1137#endif /* USE_LOCALE_NUMERIC */
a782673d 1138#ifdef USE_LOCALE_MESSAGES
5d1187d1
KW
1139 sl_result = my_setlocale(LC_MESSAGES, trial_locale);
1140 DEBUG_LOCALE_INIT(LC_MESSAGES, trial_locale, sl_result);
1141 if (! (sl_result))
a782673d
KW
1142 setlocale_failure = TRUE;
1143#endif /* USE_LOCALE_MESSAGES */
c835d6be 1144#ifdef USE_LOCALE_MONETARY
5d1187d1
KW
1145 sl_result = my_setlocale(LC_MONETARY, trial_locale);
1146 DEBUG_LOCALE_INIT(LC_MONETARY, trial_locale, sl_result);
1147 if (! (sl_result))
c835d6be
KW
1148 setlocale_failure = TRUE;
1149#endif /* USE_LOCALE_MONETARY */
1150
49c85077
KW
1151 if (! setlocale_failure) { /* Success */
1152 break;
1153 }
65ebb059 1154 }
98994639 1155
49c85077
KW
1156 /* Here, something failed; will need to try a fallback. */
1157 ok = 0;
65ebb059 1158
49c85077
KW
1159 if (i == 0) {
1160 unsigned int j;
98994639 1161
65ebb059 1162 if (locwarn) { /* Output failure info only on the first one */
98994639
HS
1163#ifdef LC_ALL
1164
49c85077
KW
1165 PerlIO_printf(Perl_error_log,
1166 "perl: warning: Setting locale failed.\n");
98994639
HS
1167
1168#else /* !LC_ALL */
1169
49c85077
KW
1170 PerlIO_printf(Perl_error_log,
1171 "perl: warning: Setting locale failed for the categories:\n\t");
20a240df 1172# ifdef USE_LOCALE_CTYPE
49c85077
KW
1173 if (! curctype)
1174 PerlIO_printf(Perl_error_log, "LC_CTYPE ");
20a240df
KW
1175# endif /* USE_LOCALE_CTYPE */
1176# ifdef USE_LOCALE_COLLATE
49c85077
KW
1177 if (! curcoll)
1178 PerlIO_printf(Perl_error_log, "LC_COLLATE ");
20a240df
KW
1179# endif /* USE_LOCALE_COLLATE */
1180# ifdef USE_LOCALE_NUMERIC
49c85077
KW
1181 if (! curnum)
1182 PerlIO_printf(Perl_error_log, "LC_NUMERIC ");
20a240df 1183# endif /* USE_LOCALE_NUMERIC */
a782673d 1184 PerlIO_printf(Perl_error_log, "and possibly others\n");
98994639
HS
1185
1186#endif /* LC_ALL */
1187
49c85077
KW
1188 PerlIO_printf(Perl_error_log,
1189 "perl: warning: Please check that your locale settings:\n");
98994639
HS
1190
1191#ifdef __GLIBC__
49c85077
KW
1192 PerlIO_printf(Perl_error_log,
1193 "\tLANGUAGE = %c%s%c,\n",
1194 language ? '"' : '(',
1195 language ? language : "unset",
1196 language ? '"' : ')');
98994639
HS
1197#endif
1198
49c85077
KW
1199 PerlIO_printf(Perl_error_log,
1200 "\tLC_ALL = %c%s%c,\n",
1201 lc_all ? '"' : '(',
1202 lc_all ? lc_all : "unset",
1203 lc_all ? '"' : ')');
98994639
HS
1204
1205#if defined(USE_ENVIRON_ARRAY)
49c85077
KW
1206 {
1207 char **e;
1208 for (e = environ; *e; e++) {
1209 if (strnEQ(*e, "LC_", 3)
1210 && strnNE(*e, "LC_ALL=", 7)
1211 && (p = strchr(*e, '=')))
1212 PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
1213 (int)(p - *e), *e, p + 1);
1214 }
1215 }
98994639 1216#else
49c85077
KW
1217 PerlIO_printf(Perl_error_log,
1218 "\t(possibly more locale environment variables)\n");
98994639
HS
1219#endif
1220
49c85077
KW
1221 PerlIO_printf(Perl_error_log,
1222 "\tLANG = %c%s%c\n",
1223 lang ? '"' : '(',
1224 lang ? lang : "unset",
1225 lang ? '"' : ')');
98994639 1226
49c85077
KW
1227 PerlIO_printf(Perl_error_log,
1228 " are supported and installed on your system.\n");
1229 }
98994639 1230
65ebb059 1231 /* Calculate what fallback locales to try. We have avoided this
f6bab5f6 1232 * until we have to, because failure is quite unlikely. This will
65ebb059
KW
1233 * usually change the upper bound of the loop we are in.
1234 *
1235 * Since the system's default way of setting the locale has not
1236 * found one that works, We use Perl's defined ordering: LC_ALL,
1237 * LANG, and the C locale. We don't try the same locale twice, so
1238 * don't add to the list if already there. (On POSIX systems, the
1239 * LC_ALL element will likely be a repeat of the 0th element "",
6b058d42
KW
1240 * but there's no harm done by doing it explicitly.
1241 *
1242 * Note that this tries the LC_ALL environment variable even on
1243 * systems which have no LC_ALL locale setting. This may or may
1244 * not have been originally intentional, but there's no real need
1245 * to change the behavior. */
65ebb059
KW
1246 if (lc_all) {
1247 for (j = 0; j < trial_locales_count; j++) {
1248 if (strEQ(lc_all, trial_locales[j])) {
1249 goto done_lc_all;
1250 }
1251 }
1252 trial_locales[trial_locales_count++] = lc_all;
1253 }
1254 done_lc_all:
98994639 1255
65ebb059
KW
1256 if (lang) {
1257 for (j = 0; j < trial_locales_count; j++) {
1258 if (strEQ(lang, trial_locales[j])) {
1259 goto done_lang;
1260 }
1261 }
1262 trial_locales[trial_locales_count++] = lang;
1263 }
1264 done_lang:
1265
1266#if defined(WIN32) && defined(LC_ALL)
1267 /* For Windows, we also try the system default locale before "C".
1268 * (If there exists a Windows without LC_ALL we skip this because
1269 * it gets too complicated. For those, the "C" is the next
1270 * fallback possibility). The "" is the same as the 0th element of
1271 * the array, but the code at the loop above knows to treat it
1272 * differently when not the 0th */
1273 trial_locales[trial_locales_count++] = "";
1274#endif
1275
1276 for (j = 0; j < trial_locales_count; j++) {
1277 if (strEQ("C", trial_locales[j])) {
1278 goto done_C;
1279 }
1280 }
1281 trial_locales[trial_locales_count++] = "C";
98994639 1282
65ebb059
KW
1283 done_C: ;
1284 } /* end of first time through the loop */
98994639 1285
65ebb059
KW
1286#ifdef WIN32
1287 next_iteration: ;
1288#endif
1289
1290 } /* end of looping through the trial locales */
1291
1292 if (ok < 1) { /* If we tried to fallback */
1293 const char* msg;
1294 if (! setlocale_failure) { /* fallback succeeded */
1295 msg = "Falling back to";
1296 }
1297 else { /* fallback failed */
98994639 1298
65ebb059
KW
1299 /* We dropped off the end of the loop, so have to decrement i to
1300 * get back to the value the last time through */
1301 i--;
98994639 1302
65ebb059
KW
1303 ok = -1;
1304 msg = "Failed to fall back to";
1305
1306 /* To continue, we should use whatever values we've got */
98994639 1307#ifdef USE_LOCALE_CTYPE
49c85077
KW
1308 Safefree(curctype);
1309 curctype = savepv(setlocale(LC_CTYPE, NULL));
5d1187d1 1310 DEBUG_LOCALE_INIT(LC_CTYPE, NULL, curctype);
98994639
HS
1311#endif /* USE_LOCALE_CTYPE */
1312#ifdef USE_LOCALE_COLLATE
49c85077
KW
1313 Safefree(curcoll);
1314 curcoll = savepv(setlocale(LC_COLLATE, NULL));
5d1187d1 1315 DEBUG_LOCALE_INIT(LC_COLLATE, NULL, curcoll);
98994639
HS
1316#endif /* USE_LOCALE_COLLATE */
1317#ifdef USE_LOCALE_NUMERIC
49c85077
KW
1318 Safefree(curnum);
1319 curnum = savepv(setlocale(LC_NUMERIC, NULL));
5d1187d1 1320 DEBUG_LOCALE_INIT(LC_NUMERIC, NULL, curnum);
98994639 1321#endif /* USE_LOCALE_NUMERIC */
65ebb059
KW
1322 }
1323
1324 if (locwarn) {
1325 const char * description;
1326 const char * name = "";
1327 if (strEQ(trial_locales[i], "C")) {
1328 description = "the standard locale";
1329 name = "C";
1330 }
6bce99ee 1331#ifdef SYSTEM_DEFAULT_LOCALE
65ebb059
KW
1332 else if (strEQ(trial_locales[i], "")) {
1333 description = "the system default locale";
1334 if (system_default_locale) {
1335 name = system_default_locale;
1336 }
1337 }
6bce99ee 1338#endif /* SYSTEM_DEFAULT_LOCALE */
65ebb059
KW
1339 else {
1340 description = "a fallback locale";
1341 name = trial_locales[i];
1342 }
1343 if (name && strNE(name, "")) {
1344 PerlIO_printf(Perl_error_log,
1345 "perl: warning: %s %s (\"%s\").\n", msg, description, name);
1346 }
1347 else {
1348 PerlIO_printf(Perl_error_log,
1349 "perl: warning: %s %s.\n", msg, description);
1350 }
1351 }
1352 } /* End of tried to fallback */
98994639
HS
1353
1354#ifdef USE_LOCALE_CTYPE
1355 new_ctype(curctype);
1356#endif /* USE_LOCALE_CTYPE */
1357
1358#ifdef USE_LOCALE_COLLATE
1359 new_collate(curcoll);
1360#endif /* USE_LOCALE_COLLATE */
1361
1362#ifdef USE_LOCALE_NUMERIC
1363 new_numeric(curnum);
1364#endif /* USE_LOCALE_NUMERIC */
b310b053 1365
8ef6e574 1366#if defined(USE_PERLIO) && defined(USE_LOCALE_CTYPE)
49c85077
KW
1367 /* Set PL_utf8locale to TRUE if using PerlIO _and_ the current LC_CTYPE
1368 * locale is UTF-8. If PL_utf8locale and PL_unicode (set by -C or by
1369 * $ENV{PERL_UNICODE}) are true, perl.c:S_parse_body() will turn on the
1370 * PerlIO :utf8 layer on STDIN, STDOUT, STDERR, _and_ the default open
1371 * discipline. */
c1284011 1372 PL_utf8locale = _is_cur_LC_category_utf8(LC_CTYPE);
49c85077 1373
a05d7ebb 1374 /* Set PL_unicode to $ENV{PERL_UNICODE} if using PerlIO.
fde18df1
JH
1375 This is an alternative to using the -C command line switch
1376 (the -C if present will override this). */
1377 {
dd374669 1378 const char *p = PerlEnv_getenv("PERL_UNICODE");
a05d7ebb 1379 PL_unicode = p ? parse_unicode_opts(&p) : 0;
5a22a2bb
NC
1380 if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
1381 PL_utf8cache = -1;
b310b053 1382 }
ec71e770 1383#endif
b310b053 1384
98994639 1385#ifdef USE_LOCALE_CTYPE
43c5f42d 1386 Safefree(curctype);
98994639
HS
1387#endif /* USE_LOCALE_CTYPE */
1388#ifdef USE_LOCALE_COLLATE
43c5f42d 1389 Safefree(curcoll);
98994639
HS
1390#endif /* USE_LOCALE_COLLATE */
1391#ifdef USE_LOCALE_NUMERIC
43c5f42d 1392 Safefree(curnum);
98994639 1393#endif /* USE_LOCALE_NUMERIC */
8ef6e574 1394
175c4cf9
KW
1395#ifdef __GLIBC__
1396 Safefree(language);
1397#endif
1398
1399 Safefree(lc_all);
1400 Safefree(lang);
1401
e3305790
KW
1402#else /* !USE_LOCALE */
1403 PERL_UNUSED_ARG(printwarn);
1404#endif /* USE_LOCALE */
1405
2fcc0ca9
KW
1406#ifdef DEBUGGING
1407 /* So won't continue to output stuff */
1408 debug_initialization = FALSE;
1409#endif
1410
98994639
HS
1411 return ok;
1412}
1413
98994639
HS
1414#ifdef USE_LOCALE_COLLATE
1415
a4a439fb 1416char *
a4a439fb
KW
1417Perl__mem_collxfrm(pTHX_ const char *input_string,
1418 STRLEN len, /* Length of 'input_string' */
1419 STRLEN *xlen, /* Set to length of returned string
1420 (not including the collation index
1421 prefix) */
1422 bool utf8 /* Is the input in UTF-8? */
6696cfa7 1423 )
98994639 1424{
a4a439fb
KW
1425
1426 /* _mem_collxfrm() is a bit like strxfrm() but with two important
1427 * differences. First, it handles embedded NULs. Second, it allocates a bit
1428 * more memory than needed for the transformed data itself. The real
55e5378d 1429 * transformed data begins at offset COLLXFRM_HDR_LEN. *xlen is set to
a4a439fb
KW
1430 * the length of that, and doesn't include the collation index size.
1431 * Please see sv_collxfrm() to see how this is used. */
1432
55e5378d
KW
1433#define COLLXFRM_HDR_LEN sizeof(PL_collation_ix)
1434
6696cfa7
KW
1435 char * s = (char *) input_string;
1436 STRLEN s_strlen = strlen(input_string);
79f120c8 1437 char *xbuf = NULL;
55e5378d 1438 STRLEN xAlloc; /* xalloc is a reserved word in VC */
c664130f 1439 bool first_time = TRUE; /* Cleared after first loop iteration */
98994639 1440
a4a439fb
KW
1441 PERL_ARGS_ASSERT__MEM_COLLXFRM;
1442
1443 /* Must be NUL-terminated */
1444 assert(*(input_string + len) == '\0');
7918f24d 1445
79f120c8
KW
1446 /* If this locale has defective collation, skip */
1447 if (PL_collxfrm_base == 0 && PL_collxfrm_mult == 0) {
1448 goto bad;
1449 }
1450
6696cfa7
KW
1451 /* Replace any embedded NULs with the control that sorts before any others.
1452 * This will give as good as possible results on strings that don't
1453 * otherwise contain that character, but otherwise there may be
1454 * less-than-perfect results with that character and NUL. This is
1455 * unavoidable unless we replace strxfrm with our own implementation.
1456 *
1457 * XXX This code may be overkill. khw wrote it before realizing that if
1458 * you change a NUL into some other character, that that may change the
1459 * strxfrm results if that character is part of a sequence with other
1460 * characters for weight calculations. To minimize the chances of this,
1461 * now the replacement is restricted to another control (likely to be
1462 * \001). But the full generality has been retained.
1463 *
1464 * This is one of the few places in the perl core, where we can use
1465 * standard functions like strlen() and strcat(). It's because we're
1466 * looking for NULs. */
1467 if (s_strlen < len) {
1468 char * e = s + len;
1469 char * sans_nuls;
1470 STRLEN cur_min_char_len;
1471
1472 /* If we don't know what control character sorts lowest for this
1473 * locale, find it */
1474 if (*PL_strxfrm_min_char == '\0') {
1475 int j;
58eebef2
KW
1476#ifdef DEBUGGING
1477 U8 cur_min_cp = 1; /* The code point that sorts lowest, so far */
1478#endif
1479 char * cur_min_x = NULL; /* And its xfrm, (except it also
6696cfa7
KW
1480 includes the collation index
1481 prefixed. */
1482
1483 /* Look through all legal code points (NUL isn't) */
1484 for (j = 1; j < 256; j++) {
1485 char * x; /* j's xfrm plus collation index */
1486 STRLEN x_len; /* length of 'x' */
1487 STRLEN trial_len = 1;
1488
1489 /* Create a 1 byte string of the current code point, but with
1490 * room to be 2 bytes */
1491 char cur_source[] = { (char) j, '\0' , '\0' };
1492
1493 if (PL_in_utf8_COLLATE_locale) {
1494 if (! isCNTRL_L1(j)) {
1495 continue;
1496 }
1497
1498 /* If needs to be 2 bytes, find them */
1499 if (! UVCHR_IS_INVARIANT(j)) {
a4a439fb
KW
1500 char * d = cur_source;
1501 append_utf8_from_native_byte((U8) j, (U8 **) &d);
1502 trial_len = 2;
6696cfa7
KW
1503 }
1504 }
1505 else if (! isCNTRL_LC(j)) {
1506 continue;
1507 }
1508
1509 /* Then transform it */
a4a439fb
KW
1510 x = _mem_collxfrm(cur_source, trial_len, &x_len,
1511 PL_in_utf8_COLLATE_locale);
6696cfa7
KW
1512
1513 /* If something went wrong (which it shouldn't), just
1514 * ignore this code point */
1515 if ( x_len == 0
55e5378d 1516 || strlen(x + COLLXFRM_HDR_LEN) < x_len)
6696cfa7
KW
1517 {
1518 continue;
1519 }
1520
1521 /* If this character's transformation is lower than
1522 * the current lowest, this one becomes the lowest */
1523 if ( cur_min_x == NULL
55e5378d
KW
1524 || strLT(x + COLLXFRM_HDR_LEN,
1525 cur_min_x + COLLXFRM_HDR_LEN))
6696cfa7
KW
1526 {
1527 strcpy(PL_strxfrm_min_char, cur_source);
1528 cur_min_x = x;
58eebef2
KW
1529#ifdef DEBUGGING
1530 cur_min_cp = j;
1531#endif
6696cfa7
KW
1532 }
1533 else {
1534 Safefree(x);
1535 }
1536 } /* end of loop through all bytes */
1537
1538 /* Unlikely, but possible, if there aren't any controls in the
1539 * locale, arbitrarily use \001 */
1540 if (cur_min_x == NULL) {
1541 STRLEN x_len; /* temporary */
a4a439fb
KW
1542 cur_min_x = _mem_collxfrm("\001", 1, &x_len,
1543 PL_in_utf8_COLLATE_locale);
6696cfa7
KW
1544 /* cur_min_cp was already initialized to 1 */
1545 }
1546
58eebef2
KW
1547 DEBUG_L(PerlIO_printf(Perl_debug_log,
1548 "_mem_collxfrm: lowest collating control in the 0-255 "
1549 "range in locale %s is 0x%02X\n",
1550 PL_collation_name,
1551 cur_min_cp));
1552 if (DEBUG_Lv_TEST) {
1553 unsigned i;
1554 PerlIO_printf(Perl_debug_log, "Its xfrm is");
1555 for (i = 0; i < strlen(cur_min_x + COLLXFRM_HDR_LEN); i ++) {
1556 PerlIO_printf(Perl_debug_log, " %02x",
1557 (U8) *(cur_min_x + COLLXFRM_HDR_LEN + i));
1558 }
1559 PerlIO_printf(Perl_debug_log, "\n");
1560 }
1561
6696cfa7
KW
1562 Safefree(cur_min_x);
1563 }
1564
1565 /* The worst case length for the replaced string would be if every
1566 * character in it is NUL. Multiply that by the length of each
1567 * replacement, and allow for a trailing NUL */
1568 cur_min_char_len = strlen(PL_strxfrm_min_char);
1569 Newx(sans_nuls, (len * cur_min_char_len) + 1, char);
1570 *sans_nuls = '\0';
1571
1572
1573 /* Replace each NUL with the lowest collating control. Loop until have
1574 * exhausted all the NULs */
1575 while (s + s_strlen < e) {
1576 strcat(sans_nuls, s);
1577
1578 /* Do the actual replacement */
1579 strcat(sans_nuls, PL_strxfrm_min_char);
1580
1581 /* Move past the input NUL */
1582 s += s_strlen + 1;
1583 s_strlen = strlen(s);
1584 }
1585
1586 /* And add anything that trails the final NUL */
1587 strcat(sans_nuls, s);
1588
1589 /* Switch so below we transform this modified string */
1590 s = sans_nuls;
1591 len = strlen(s);
1592 }
1593
a4a439fb
KW
1594 /* Make sure the UTF8ness of the string and locale match */
1595 if (utf8 != PL_in_utf8_COLLATE_locale) {
1596 const char * const t = s; /* Temporary so we can later find where the
1597 input was */
1598
1599 /* Here they don't match. Change the string's to be what the locale is
1600 * expecting */
1601
1602 if (! utf8) { /* locale is UTF-8, but input isn't; upgrade the input */
1603 s = (char *) bytes_to_utf8((const U8 *) s, &len);
1604 utf8 = TRUE;
1605 }
1606 else { /* locale is not UTF-8; but input is; downgrade the input */
1607
1608 s = (char *) bytes_from_utf8((const U8 *) s, &len, &utf8);
1609
1610 /* If the downgrade was successful we are done, but if the input
1611 * contains things that require UTF-8 to represent, have to do
1612 * damage control ... */
1613 if (UNLIKELY(utf8)) {
1614
1615 /* What we do is construct a non-UTF-8 string with
1616 * 1) the characters representable by a single byte converted
1617 * to be so (if necessary);
1618 * 2) and the rest converted to collate the same as the
1619 * highest collating representable character. That makes
1620 * them collate at the end. This is similar to how we
1621 * handle embedded NULs, but we use the highest collating
1622 * code point instead of the smallest. Like the NUL case,
1623 * this isn't perfect, but is the best we can reasonably
1624 * do. Every above-255 code point will sort the same as
1625 * the highest-sorting 0-255 code point. If that code
1626 * point can combine in a sequence with some other code
1627 * points for weight calculations, us changing something to
1628 * be it can adversely affect the results. But in most
1629 * cases, it should work reasonably. And note that this is
1630 * really an illegal situation: using code points above 255
1631 * on a locale where only 0-255 are valid. If two strings
1632 * sort entirely equal, then the sort order for the
1633 * above-255 code points will be in code point order. */
1634
1635 utf8 = FALSE;
1636
1637 /* If we haven't calculated the code point with the maximum
1638 * collating order for this locale, do so now */
1639 if (! PL_strxfrm_max_cp) {
1640 int j;
1641
1642 /* The current transformed string that collates the
1643 * highest (except it also includes the prefixed collation
1644 * index. */
1645 char * cur_max_x = NULL;
1646
1647 /* Look through all legal code points (NUL isn't) */
1648 for (j = 1; j < 256; j++) {
1649 char * x;
1650 STRLEN x_len;
1651
1652 /* Create a 1-char string of the current code point. */
1653 char cur_source[] = { (char) j, '\0' };
1654
1655 /* Then transform it */
1656 x = _mem_collxfrm(cur_source, 1, &x_len, FALSE);
1657
1658 /* If something went wrong (which it shouldn't), just
1659 * ignore this code point */
1660 if (x_len == 0) {
1661 Safefree(x);
1662 continue;
1663 }
1664
1665 /* If this character's transformation is higher than
1666 * the current highest, this one becomes the highest */
1667 if ( cur_max_x == NULL
55e5378d
KW
1668 || strGT(x + COLLXFRM_HDR_LEN,
1669 cur_max_x + COLLXFRM_HDR_LEN))
a4a439fb
KW
1670 {
1671 PL_strxfrm_max_cp = j;
1672 cur_max_x = x;
1673 }
1674 else {
1675 Safefree(x);
1676 }
1677 }
1678
58eebef2
KW
1679 DEBUG_L(PerlIO_printf(Perl_debug_log,
1680 "_mem_collxfrm: highest 1-byte collating character"
1681 " in locale %s is 0x%02X\n",
1682 PL_collation_name,
1683 PL_strxfrm_max_cp));
1684 if (DEBUG_Lv_TEST) {
1685 unsigned i;
1686 PerlIO_printf(Perl_debug_log, "Its xfrm is ");
1687 for (i = 0;
1688 i < strlen(cur_max_x + COLLXFRM_HDR_LEN);
1689 i++)
1690 {
1691 PerlIO_printf(Perl_debug_log, " %02x",
1692 (U8) cur_max_x[i + COLLXFRM_HDR_LEN]);
1693 }
1694 PerlIO_printf(Perl_debug_log, "\n");
1695 }
1696
a4a439fb
KW
1697 Safefree(cur_max_x);
1698 }
1699
1700 /* Here we know which legal code point collates the highest.
1701 * We are ready to construct the non-UTF-8 string. The length
1702 * will be at least 1 byte smaller than the input string
1703 * (because we changed at least one 2-byte character into a
1704 * single byte), but that is eaten up by the trailing NUL */
1705 Newx(s, len, char);
1706
1707 {
1708 STRLEN i;
1709 STRLEN d= 0;
1710
1711 for (i = 0; i < len; i+= UTF8SKIP(t + i)) {
1712 U8 cur_char = t[i];
1713 if (UTF8_IS_INVARIANT(cur_char)) {
1714 s[d++] = cur_char;
1715 }
1716 else if (UTF8_IS_DOWNGRADEABLE_START(cur_char)) {
1717 s[d++] = EIGHT_BIT_UTF8_TO_NATIVE(cur_char, t[i+1]);
1718 }
1719 else { /* Replace illegal cp with highest collating
1720 one */
1721 s[d++] = PL_strxfrm_max_cp;
1722 }
1723 }
1724 s[d++] = '\0';
1725 Renew(s, d, char); /* Free up unused space */
1726 }
1727 }
1728 }
1729
1730 /* Here, we have constructed a modified version of the input. It could
1731 * be that we already had a modified copy before we did this version.
1732 * If so, that copy is no longer needed */
1733 if (t != input_string) {
1734 Safefree(t);
1735 }
1736 }
1737
59c018b9
KW
1738 /* The first element in the output is the collation id, used by
1739 * sv_collxfrm(); then comes the space for the transformed string. The
1740 * equation should give us a good estimate as to how much is needed */
55e5378d 1741 xAlloc = COLLXFRM_HDR_LEN
a4a439fb
KW
1742 + PL_collxfrm_base
1743 + (PL_collxfrm_mult * ((utf8)
1744 ? utf8_length((U8 *) s, (U8 *) s + len)
1745 : len));
a02a5408 1746 Newx(xbuf, xAlloc, char);
bb0f664e 1747 if (UNLIKELY(! xbuf))
98994639
HS
1748 goto bad;
1749
d35fca5f 1750 /* Store the collation id */
98994639 1751 *(U32*)xbuf = PL_collation_ix;
d35fca5f
KW
1752
1753 /* Then the transformation of the input. We loop until successful, or we
1754 * give up */
4ebeff16 1755 for (;;) {
55e5378d 1756 *xlen = strxfrm(xbuf + COLLXFRM_HDR_LEN, s, xAlloc - COLLXFRM_HDR_LEN);
4ebeff16
KW
1757
1758 /* If the transformed string occupies less space than we told strxfrm()
1759 * was available, it means it successfully transformed the whole
1760 * string. */
55e5378d 1761 if (*xlen < xAlloc - COLLXFRM_HDR_LEN) {
4ebeff16
KW
1762 break;
1763 }
bb0f664e 1764
55e5378d 1765 if (UNLIKELY(*xlen >= PERL_INT_MAX))
4ebeff16 1766 goto bad;
d35fca5f 1767
c664130f
KW
1768 /* A well-behaved strxfrm() returns exactly how much space it needs
1769 * (not including the trailing NUL) when it fails due to not enough
1770 * space being provided. Assume that this is the case unless it's been
1771 * proven otherwise */
1772 if (LIKELY(PL_strxfrm_is_behaved) && first_time) {
55e5378d 1773 xAlloc = *xlen + COLLXFRM_HDR_LEN + 1;
c664130f
KW
1774 }
1775 else { /* Here, either:
1776 * 1) The strxfrm() has previously shown bad behavior; or
1777 * 2) It isn't the first time through the loop, which means
1778 * that the strxfrm() is now showing bad behavior, because
1779 * we gave it what it said was needed in the previous
1780 * iteration, and it came back saying it needed still more.
1781 * (Many versions of cygwin fit this. When the buffer size
1782 * isn't sufficient, they return the input size instead of
1783 * how much is needed.)
1784 * Increase the buffer size by a fixed percentage and try again. */
6ddd902c 1785 xAlloc += (xAlloc / 4) + 1;
c664130f 1786 PL_strxfrm_is_behaved = FALSE;
c664130f 1787
58eebef2
KW
1788#ifdef DEBUGGING
1789 if (DEBUG_Lv_TEST || debug_initialization) {
1790 PerlIO_printf(Perl_debug_log,
1791 "_mem_collxfrm required more space than previously calculated"
1792 " for locale %s, trying again with new guess=%d+%"UVuf"\n",
1793 PL_collation_name, (int) COLLXFRM_HDR_LEN,
1794 (UV) xAlloc - COLLXFRM_HDR_LEN);
1795 }
1796#endif
1797 }
c664130f 1798
4ebeff16
KW
1799 Renew(xbuf, xAlloc, char);
1800 if (UNLIKELY(! xbuf))
1801 goto bad;
c664130f
KW
1802
1803 first_time = FALSE;
4ebeff16 1804 }
98994639 1805
6696cfa7 1806
58eebef2
KW
1807#ifdef DEBUGGING
1808 if (DEBUG_Lv_TEST || debug_initialization) {
1809 unsigned i;
1810 PerlIO_printf(Perl_debug_log,
1811 "_mem_collxfrm[%d]: returning %"UVuf" for locale %s '%s'\n",
1812 PL_collation_ix, *xlen, PL_collation_name, input_string);
1813 PerlIO_printf(Perl_debug_log, "Its xfrm is");
1814 for (i = COLLXFRM_HDR_LEN; i < *xlen + COLLXFRM_HDR_LEN; i++) {
1815 PerlIO_printf(Perl_debug_log, " %02x", (U8) xbuf[i]);
1816 }
1817 PerlIO_printf(Perl_debug_log, "\n");
1818 }
1819#endif
1820
3c5f993e 1821 /* Free up unneeded space; retain ehough for trailing NUL */
55e5378d 1822 Renew(xbuf, COLLXFRM_HDR_LEN + *xlen + 1, char);
98994639 1823
6696cfa7
KW
1824 if (s != input_string) {
1825 Safefree(s);
98994639
HS
1826 }
1827
98994639
HS
1828 return xbuf;
1829
1830 bad:
1831 Safefree(xbuf);
6696cfa7
KW
1832 if (s != input_string) {
1833 Safefree(s);
1834 }
98994639 1835 *xlen = 0;
58eebef2
KW
1836#ifdef DEBUGGING
1837 if (DEBUG_Lv_TEST || debug_initialization) {
1838 PerlIO_printf(Perl_debug_log, "_mem_collxfrm[%d] returning NULL\n",
1839 PL_collation_ix);
1840 }
1841#endif
98994639
HS
1842 return NULL;
1843}
1844
1845#endif /* USE_LOCALE_COLLATE */
58eebef2 1846
8ef6e574
KW
1847#ifdef USE_LOCALE
1848
c1284011
KW
1849bool
1850Perl__is_cur_LC_category_utf8(pTHX_ int category)
7d74bb61
KW
1851{
1852 /* Returns TRUE if the current locale for 'category' is UTF-8; FALSE
1853 * otherwise. 'category' may not be LC_ALL. If the platform doesn't have
119ee68b 1854 * nl_langinfo(), nor MB_CUR_MAX, this employs a heuristic, which hence
609548d2
KW
1855 * could give the wrong result. The result will very likely be correct for
1856 * languages that have commonly used non-ASCII characters, but for notably
1857 * English, it comes down to if the locale's name ends in something like
1858 * "UTF-8". It errs on the side of not being a UTF-8 locale. */
7d74bb61
KW
1859
1860 char *save_input_locale = NULL;
7d74bb61
KW
1861 STRLEN final_pos;
1862
8ef6e574 1863#ifdef LC_ALL
7d74bb61 1864 assert(category != LC_ALL);
8ef6e574 1865#endif
7d74bb61
KW
1866
1867 /* First dispose of the trivial cases */
b07fffd1 1868 save_input_locale = setlocale(category, NULL);
7d74bb61 1869 if (! save_input_locale) {
69014004
KW
1870 DEBUG_L(PerlIO_printf(Perl_debug_log,
1871 "Could not find current locale for category %d\n",
1872 category));
7d74bb61
KW
1873 return FALSE; /* XXX maybe should croak */
1874 }
b07fffd1 1875 save_input_locale = stdize_locale(savepv(save_input_locale));
a39edc4c 1876 if (isNAME_C_OR_POSIX(save_input_locale)) {
69014004
KW
1877 DEBUG_L(PerlIO_printf(Perl_debug_log,
1878 "Current locale for category %d is %s\n",
1879 category, save_input_locale));
b07fffd1 1880 Safefree(save_input_locale);
7d74bb61
KW
1881 return FALSE;
1882 }
1883
1d958db2
KW
1884#if defined(USE_LOCALE_CTYPE) \
1885 && (defined(MB_CUR_MAX) || (defined(HAS_NL_LANGINFO) && defined(CODESET)))
7d74bb61 1886
1d958db2 1887 { /* Next try nl_langinfo or MB_CUR_MAX if available */
7d74bb61
KW
1888
1889 char *save_ctype_locale = NULL;
119ee68b 1890 bool is_utf8;
7d74bb61 1891
119ee68b 1892 if (category != LC_CTYPE) { /* These work only on LC_CTYPE */
7d74bb61
KW
1893
1894 /* Get the current LC_CTYPE locale */
4f72bb37 1895 save_ctype_locale = setlocale(LC_CTYPE, NULL);
7d74bb61 1896 if (! save_ctype_locale) {
69014004
KW
1897 DEBUG_L(PerlIO_printf(Perl_debug_log,
1898 "Could not find current locale for LC_CTYPE\n"));
7d74bb61
KW
1899 goto cant_use_nllanginfo;
1900 }
4f72bb37 1901 save_ctype_locale = stdize_locale(savepv(save_ctype_locale));
7d74bb61
KW
1902
1903 /* If LC_CTYPE and the desired category use the same locale, this
1904 * means that finding the value for LC_CTYPE is the same as finding
1905 * the value for the desired category. Otherwise, switch LC_CTYPE
1906 * to the desired category's locale */
1907 if (strEQ(save_ctype_locale, save_input_locale)) {
1908 Safefree(save_ctype_locale);
1909 save_ctype_locale = NULL;
1910 }
1911 else if (! setlocale(LC_CTYPE, save_input_locale)) {
69014004
KW
1912 DEBUG_L(PerlIO_printf(Perl_debug_log,
1913 "Could not change LC_CTYPE locale to %s\n",
1914 save_input_locale));
7d74bb61
KW
1915 Safefree(save_ctype_locale);
1916 goto cant_use_nllanginfo;
1917 }
1918 }
1919
69014004
KW
1920 DEBUG_L(PerlIO_printf(Perl_debug_log, "Current LC_CTYPE locale=%s\n",
1921 save_input_locale));
1922
7d74bb61 1923 /* Here the current LC_CTYPE is set to the locale of the category whose
1d958db2
KW
1924 * information is desired. This means that nl_langinfo() and MB_CUR_MAX
1925 * should give the correct results */
119ee68b 1926
1d958db2
KW
1927# if defined(HAS_NL_LANGINFO) && defined(CODESET)
1928 {
4f72bb37 1929 char *codeset = nl_langinfo(CODESET);
1d958db2 1930 if (codeset && strNE(codeset, "")) {
4f72bb37 1931 codeset = savepv(codeset);
119ee68b 1932
1d958db2
KW
1933 /* If we switched LC_CTYPE, switch back */
1934 if (save_ctype_locale) {
1935 setlocale(LC_CTYPE, save_ctype_locale);
1936 Safefree(save_ctype_locale);
1937 }
1938
1939 is_utf8 = foldEQ(codeset, STR_WITH_LEN("UTF-8"))
1940 || foldEQ(codeset, STR_WITH_LEN("UTF8"));
1941
69014004
KW
1942 DEBUG_L(PerlIO_printf(Perl_debug_log,
1943 "\tnllanginfo returned CODESET '%s'; ?UTF8 locale=%d\n",
1944 codeset, is_utf8));
1d958db2
KW
1945 Safefree(codeset);
1946 Safefree(save_input_locale);
1947 return is_utf8;
1948 }
119ee68b
KW
1949 }
1950
1d958db2
KW
1951# endif
1952# ifdef MB_CUR_MAX
1953
1954 /* Here, either we don't have nl_langinfo, or it didn't return a
1955 * codeset. Try MB_CUR_MAX */
1956
119ee68b
KW
1957 /* Standard UTF-8 needs at least 4 bytes to represent the maximum
1958 * Unicode code point. Since UTF-8 is the only non-single byte
1959 * encoding we handle, we just say any such encoding is UTF-8, and if
1960 * turns out to be wrong, other things will fail */
1961 is_utf8 = MB_CUR_MAX >= 4;
1962
69014004
KW
1963 DEBUG_L(PerlIO_printf(Perl_debug_log,
1964 "\tMB_CUR_MAX=%d; ?UTF8 locale=%d\n",
1965 (int) MB_CUR_MAX, is_utf8));
1966
119ee68b
KW
1967 Safefree(save_input_locale);
1968
1969# ifdef HAS_MBTOWC
1970
1971 /* ... But, most system that have MB_CUR_MAX will also have mbtowc(),
1972 * since they are both in the C99 standard. We can feed a known byte
1973 * string to the latter function, and check that it gives the expected
1974 * result */
1975 if (is_utf8) {
1976 wchar_t wc;
856b881c 1977 PERL_UNUSED_RESULT(mbtowc(&wc, NULL, 0));/* Reset any shift state */
69014004 1978 errno = 0;
f019f68f 1979 if ((size_t)mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8))
119ee68b
KW
1980 != strlen(HYPHEN_UTF8)
1981 || wc != (wchar_t) 0x2010)
1982 {
1983 is_utf8 = FALSE;
abdcbdb8 1984 DEBUG_L(PerlIO_printf(Perl_debug_log, "\thyphen=U+%x\n", (unsigned int)wc));
69014004
KW
1985 DEBUG_L(PerlIO_printf(Perl_debug_log,
1986 "\treturn from mbtowc=%d; errno=%d; ?UTF8 locale=0\n",
1987 mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8)), errno));
119ee68b
KW
1988 }
1989 }
119ee68b
KW
1990# endif
1991
1d958db2
KW
1992 /* If we switched LC_CTYPE, switch back */
1993 if (save_ctype_locale) {
1994 setlocale(LC_CTYPE, save_ctype_locale);
1995 Safefree(save_ctype_locale);
119ee68b 1996 }
7d74bb61 1997
1d958db2 1998 return is_utf8;
119ee68b 1999# endif
7d74bb61 2000 }
119ee68b 2001
7d74bb61
KW
2002 cant_use_nllanginfo:
2003
0080c90a
KW
2004#else /* nl_langinfo should work if available, so don't bother compiling this
2005 fallback code. The final fallback of looking at the name is
2006 compiled, and will be executed if nl_langinfo fails */
7d74bb61 2007
97f4de96
KW
2008 /* nl_langinfo not available or failed somehow. Next try looking at the
2009 * currency symbol to see if it disambiguates things. Often that will be
2010 * in the native script, and if the symbol isn't in UTF-8, we know that the
2011 * locale isn't. If it is non-ASCII UTF-8, we infer that the locale is
609548d2
KW
2012 * too, as the odds of a non-UTF8 string being valid UTF-8 are quite small
2013 * */
fa9b773e
KW
2014
2015#ifdef HAS_LOCALECONV
fa9b773e 2016# ifdef USE_LOCALE_MONETARY
fa9b773e
KW
2017 {
2018 char *save_monetary_locale = NULL;
fa9b773e 2019 bool only_ascii = FALSE;
13542a67
KW
2020 bool is_utf8 = FALSE;
2021 struct lconv* lc;
fa9b773e 2022
97f4de96
KW
2023 /* Like above for LC_CTYPE, we first set LC_MONETARY to the locale of
2024 * the desired category, if it isn't that locale already */
2025
fa9b773e
KW
2026 if (category != LC_MONETARY) {
2027
4f72bb37 2028 save_monetary_locale = setlocale(LC_MONETARY, NULL);
fa9b773e 2029 if (! save_monetary_locale) {
69014004
KW
2030 DEBUG_L(PerlIO_printf(Perl_debug_log,
2031 "Could not find current locale for LC_MONETARY\n"));
fa9b773e
KW
2032 goto cant_use_monetary;
2033 }
4f72bb37 2034 save_monetary_locale = stdize_locale(savepv(save_monetary_locale));
fa9b773e 2035
13542a67
KW
2036 if (strEQ(save_monetary_locale, save_input_locale)) {
2037 Safefree(save_monetary_locale);
2038 save_monetary_locale = NULL;
2039 }
2040 else if (! setlocale(LC_MONETARY, save_input_locale)) {
59c234b4
KW
2041 DEBUG_L(PerlIO_printf(Perl_debug_log,
2042 "Could not change LC_MONETARY locale to %s\n",
2043 save_input_locale));
2044 Safefree(save_monetary_locale);
2045 goto cant_use_monetary;
fa9b773e
KW
2046 }
2047 }
2048
2049 /* Here the current LC_MONETARY is set to the locale of the category
2050 * whose information is desired. */
2051
13542a67
KW
2052 lc = localeconv();
2053 if (! lc
2054 || ! lc->currency_symbol
9f10db87 2055 || is_invariant_string((U8 *) lc->currency_symbol, 0))
13542a67
KW
2056 {
2057 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));
2058 only_ascii = TRUE;
2059 }
2060 else {
2061 is_utf8 = is_utf8_string((U8 *) lc->currency_symbol, 0);
fa9b773e
KW
2062 }
2063
2064 /* If we changed it, restore LC_MONETARY to its original locale */
2065 if (save_monetary_locale) {
2066 setlocale(LC_MONETARY, save_monetary_locale);
2067 Safefree(save_monetary_locale);
2068 }
2069
13542a67 2070 if (! only_ascii) {
fa9b773e 2071
59c234b4
KW
2072 /* It isn't a UTF-8 locale if the symbol is not legal UTF-8;
2073 * otherwise assume the locale is UTF-8 if and only if the symbol
2074 * is non-ascii UTF-8. */
2075 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?Currency symbol for %s is UTF-8=%d\n",
2076 save_input_locale, is_utf8));
2077 Safefree(save_input_locale);
2078 return is_utf8;
13542a67 2079 }
fa9b773e
KW
2080 }
2081 cant_use_monetary:
2082
2083# endif /* USE_LOCALE_MONETARY */
2084#endif /* HAS_LOCALECONV */
2085
15f7e74e
KW
2086#if defined(HAS_STRFTIME) && defined(USE_LOCALE_TIME)
2087
2088/* Still haven't found a non-ASCII string to disambiguate UTF-8 or not. Try
2089 * the names of the months and weekdays, timezone, and am/pm indicator */
2090 {
2091 char *save_time_locale = NULL;
2092 int hour = 10;
2093 bool is_dst = FALSE;
2094 int dom = 1;
2095 int month = 0;
2096 int i;
2097 char * formatted_time;
2098
2099
2100 /* Like above for LC_MONETARY, we set LC_TIME to the locale of the
2101 * desired category, if it isn't that locale already */
2102
2103 if (category != LC_TIME) {
2104
2105 save_time_locale = setlocale(LC_TIME, NULL);
2106 if (! save_time_locale) {
2107 DEBUG_L(PerlIO_printf(Perl_debug_log,
2108 "Could not find current locale for LC_TIME\n"));
2109 goto cant_use_time;
2110 }
2111 save_time_locale = stdize_locale(savepv(save_time_locale));
2112
2113 if (strEQ(save_time_locale, save_input_locale)) {
2114 Safefree(save_time_locale);
2115 save_time_locale = NULL;
2116 }
2117 else if (! setlocale(LC_TIME, save_input_locale)) {
2118 DEBUG_L(PerlIO_printf(Perl_debug_log,
2119 "Could not change LC_TIME locale to %s\n",
2120 save_input_locale));
2121 Safefree(save_time_locale);
2122 goto cant_use_time;
2123 }
2124 }
2125
2126 /* Here the current LC_TIME is set to the locale of the category
2127 * whose information is desired. Look at all the days of the week and
9f10db87 2128 * month names, and the timezone and am/pm indicator for UTF-8 variant
15f7e74e
KW
2129 * characters. The first such a one found will tell us if the locale
2130 * is UTF-8 or not */
2131
2132 for (i = 0; i < 7 + 12; i++) { /* 7 days; 12 months */
2133 formatted_time = my_strftime("%A %B %Z %p",
2134 0, 0, hour, dom, month, 112, 0, 0, is_dst);
9f10db87 2135 if (! formatted_time || is_invariant_string((U8 *) formatted_time, 0)) {
15f7e74e
KW
2136
2137 /* Here, we didn't find a non-ASCII. Try the next time through
2138 * with the complemented dst and am/pm, and try with the next
2139 * weekday. After we have gotten all weekdays, try the next
2140 * month */
2141 is_dst = ! is_dst;
2142 hour = (hour + 12) % 24;
2143 dom++;
2144 if (i > 6) {
2145 month++;
2146 }
2147 continue;
2148 }
2149
2150 /* Here, we have a non-ASCII. Return TRUE is it is valid UTF8;
2151 * false otherwise. But first, restore LC_TIME to its original
2152 * locale if we changed it */
2153 if (save_time_locale) {
2154 setlocale(LC_TIME, save_time_locale);
2155 Safefree(save_time_locale);
2156 }
2157
2158 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?time-related strings for %s are UTF-8=%d\n",
2159 save_input_locale,
2160 is_utf8_string((U8 *) formatted_time, 0)));
2161 Safefree(save_input_locale);
2162 return is_utf8_string((U8 *) formatted_time, 0);
2163 }
2164
2165 /* Falling off the end of the loop indicates all the names were just
2166 * ASCII. Go on to the next test. If we changed it, restore LC_TIME
2167 * to its original locale */
2168 if (save_time_locale) {
2169 setlocale(LC_TIME, save_time_locale);
2170 Safefree(save_time_locale);
2171 }
2172 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));
2173 }
2174 cant_use_time:
2175
2176#endif
2177
2178#if 0 && defined(USE_LOCALE_MESSAGES) && defined(HAS_SYS_ERRLIST)
855aeb93
JH
2179
2180/* This code is ifdefd out because it was found to not be necessary in testing
5857e934
KW
2181 * on our dromedary test machine, which has over 700 locales. There, this
2182 * added no value to looking at the currency symbol and the time strings. I
2183 * left it in so as to avoid rewriting it if real-world experience indicates
2184 * that dromedary is an outlier. Essentially, instead of returning abpve if we
855aeb93
JH
2185 * haven't found illegal utf8, we continue on and examine all the strerror()
2186 * messages on the platform for utf8ness. If all are ASCII, we still don't
2187 * know the answer; but otherwise we have a pretty good indication of the
5857e934
KW
2188 * utf8ness. The reason this doesn't help much is that the messages may not
2189 * have been translated into the locale. The currency symbol and time strings
2190 * are much more likely to have been translated. */
2191 {
855aeb93 2192 int e;
5857e934
KW
2193 bool is_utf8 = FALSE;
2194 bool non_ascii = FALSE;
855aeb93 2195 char *save_messages_locale = NULL;
5857e934 2196 const char * errmsg = NULL;
855aeb93 2197
5857e934
KW
2198 /* Like above, we set LC_MESSAGES to the locale of the desired
2199 * category, if it isn't that locale already */
855aeb93
JH
2200
2201 if (category != LC_MESSAGES) {
2202
5857e934 2203 save_messages_locale = setlocale(LC_MESSAGES, NULL);
855aeb93 2204 if (! save_messages_locale) {
5857e934
KW
2205 DEBUG_L(PerlIO_printf(Perl_debug_log,
2206 "Could not find current locale for LC_MESSAGES\n"));
855aeb93
JH
2207 goto cant_use_messages;
2208 }
5857e934 2209 save_messages_locale = stdize_locale(savepv(save_messages_locale));
855aeb93
JH
2210
2211 if (strEQ(save_messages_locale, save_input_locale)) {
5857e934
KW
2212 Safefree(save_messages_locale);
2213 save_messages_locale = NULL;
855aeb93
JH
2214 }
2215 else if (! setlocale(LC_MESSAGES, save_input_locale)) {
5857e934
KW
2216 DEBUG_L(PerlIO_printf(Perl_debug_log,
2217 "Could not change LC_MESSAGES locale to %s\n",
2218 save_input_locale));
855aeb93
JH
2219 Safefree(save_messages_locale);
2220 goto cant_use_messages;
2221 }
2222 }
2223
2224 /* Here the current LC_MESSAGES is set to the locale of the category
5857e934
KW
2225 * whose information is desired. Look through all the messages. We
2226 * can't use Strerror() here because it may expand to code that
2227 * segfaults in miniperl */
855aeb93 2228
5857e934
KW
2229 for (e = 0; e <= sys_nerr; e++) {
2230 errno = 0;
2231 errmsg = sys_errlist[e];
2232 if (errno || !errmsg) {
855aeb93
JH
2233 break;
2234 }
5857e934 2235 errmsg = savepv(errmsg);
9f10db87 2236 if (! is_invariant_string((U8 *) errmsg, 0)) {
5857e934
KW
2237 non_ascii = TRUE;
2238 is_utf8 = is_utf8_string((U8 *) errmsg, 0);
2239 break;
855aeb93
JH
2240 }
2241 }
5857e934 2242 Safefree(errmsg);
855aeb93
JH
2243
2244 /* And, if we changed it, restore LC_MESSAGES to its original locale */
2245 if (save_messages_locale) {
2246 setlocale(LC_MESSAGES, save_messages_locale);
2247 Safefree(save_messages_locale);
2248 }
2249
5857e934
KW
2250 if (non_ascii) {
2251
2252 /* Any non-UTF-8 message means not a UTF-8 locale; if all are valid,
2253 * any non-ascii means it is one; otherwise we assume it isn't */
2254 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?error messages for %s are UTF-8=%d\n",
2255 save_input_locale,
2256 is_utf8));
2257 Safefree(save_input_locale);
2258 return is_utf8;
2259 }
855aeb93 2260
5857e934 2261 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
2262 }
2263 cant_use_messages:
2264
2265#endif
fa9b773e 2266
0080c90a
KW
2267#endif /* the code that is compiled when no nl_langinfo */
2268
92c0a900
KW
2269#ifndef EBCDIC /* On os390, even if the name ends with "UTF-8', it isn't a
2270 UTF-8 locale */
97f4de96
KW
2271 /* As a last resort, look at the locale name to see if it matches
2272 * qr/UTF -? * 8 /ix, or some other common locale names. This "name", the
2273 * return of setlocale(), is actually defined to be opaque, so we can't
2274 * really rely on the absence of various substrings in the name to indicate
2275 * its UTF-8ness, but if it has UTF8 in the name, it is extremely likely to
2276 * be a UTF-8 locale. Similarly for the other common names */
2277
2278 final_pos = strlen(save_input_locale) - 1;
2279 if (final_pos >= 3) {
2280 char *name = save_input_locale;
2281
2282 /* Find next 'U' or 'u' and look from there */
2283 while ((name += strcspn(name, "Uu") + 1)
2284 <= save_input_locale + final_pos - 2)
2285 {
305b8651
KW
2286 if (!isALPHA_FOLD_NE(*name, 't')
2287 || isALPHA_FOLD_NE(*(name + 1), 'f'))
97f4de96
KW
2288 {
2289 continue;
2290 }
2291 name += 2;
2292 if (*(name) == '-') {
2293 if ((name > save_input_locale + final_pos - 1)) {
2294 break;
2295 }
2296 name++;
2297 }
2298 if (*(name) == '8') {
97f4de96
KW
2299 DEBUG_L(PerlIO_printf(Perl_debug_log,
2300 "Locale %s ends with UTF-8 in name\n",
2301 save_input_locale));
00c54b9c 2302 Safefree(save_input_locale);
97f4de96
KW
2303 return TRUE;
2304 }
2305 }
2306 DEBUG_L(PerlIO_printf(Perl_debug_log,
2307 "Locale %s doesn't end with UTF-8 in name\n",
2308 save_input_locale));
2309 }
92c0a900 2310#endif
97f4de96
KW
2311
2312#ifdef WIN32
2313 /* http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756.aspx */
2314 if (final_pos >= 4
2315 && *(save_input_locale + final_pos - 0) == '1'
2316 && *(save_input_locale + final_pos - 1) == '0'
2317 && *(save_input_locale + final_pos - 2) == '0'
2318 && *(save_input_locale + final_pos - 3) == '5'
2319 && *(save_input_locale + final_pos - 4) == '6')
2320 {
2321 DEBUG_L(PerlIO_printf(Perl_debug_log,
2322 "Locale %s ends with 10056 in name, is UTF-8 locale\n",
2323 save_input_locale));
2324 Safefree(save_input_locale);
2325 return TRUE;
2326 }
2327#endif
2328
2329 /* Other common encodings are the ISO 8859 series, which aren't UTF-8. But
2330 * since we are about to return FALSE anyway, there is no point in doing
2331 * this extra work */
2332#if 0
2333 if (instr(save_input_locale, "8859")) {
2334 DEBUG_L(PerlIO_printf(Perl_debug_log,
2335 "Locale %s has 8859 in name, not UTF-8 locale\n",
2336 save_input_locale));
2337 Safefree(save_input_locale);
2338 return FALSE;
2339 }
2340#endif
2341
69014004
KW
2342 DEBUG_L(PerlIO_printf(Perl_debug_log,
2343 "Assuming locale %s is not a UTF-8 locale\n",
2344 save_input_locale));
fa9b773e 2345 Safefree(save_input_locale);
7d74bb61
KW
2346 return FALSE;
2347}
2348
8ef6e574 2349#endif
7d74bb61 2350
d6ded950
KW
2351
2352bool
2353Perl__is_in_locale_category(pTHX_ const bool compiling, const int category)
2354{
1a4f13e1 2355 dVAR;
d6ded950
KW
2356 /* Internal function which returns if we are in the scope of a pragma that
2357 * enables the locale category 'category'. 'compiling' should indicate if
2358 * this is during the compilation phase (TRUE) or not (FALSE). */
2359
2360 const COP * const cop = (compiling) ? &PL_compiling : PL_curcop;
2361
2362 SV *categories = cop_hints_fetch_pvs(cop, "locale", 0);
2363 if (! categories || categories == &PL_sv_placeholder) {
2364 return FALSE;
2365 }
2366
2367 /* The pseudo-category 'not_characters' is -1, so just add 1 to each to get
2368 * a valid unsigned */
2369 assert(category >= -1);
2370 return cBOOL(SvUV(categories) & (1U << (category + 1)));
2371}
2372
2c6ee1a7
KW
2373char *
2374Perl_my_strerror(pTHX_ const int errnum) {
a0b53297 2375 dVAR;
2c6ee1a7
KW
2376
2377 /* Uses C locale for the error text unless within scope of 'use locale' for
2378 * LC_MESSAGES */
2379
2380#ifdef USE_LOCALE_MESSAGES
8ee4b769 2381 if (! IN_LC(LC_MESSAGES)) {
a0b53297
KW
2382 char * save_locale;
2383
2384 /* We have a critical section to prevent another thread from changing
2385 * the locale out from under us (or zapping the buffer returned from
2386 * setlocale() ) */
2387 LOCALE_LOCK;
2388
2389 save_locale = setlocale(LC_MESSAGES, NULL);
a39edc4c 2390 if (! isNAME_C_OR_POSIX(save_locale)) {
2c6ee1a7
KW
2391 char *errstr;
2392
2393 /* The next setlocale likely will zap this, so create a copy */
2394 save_locale = savepv(save_locale);
2395
2396 setlocale(LC_MESSAGES, "C");
2397
2398 /* This points to the static space in Strerror, with all its
2399 * limitations */
2400 errstr = Strerror(errnum);
2401
2402 setlocale(LC_MESSAGES, save_locale);
2403 Safefree(save_locale);
a0b53297
KW
2404
2405 LOCALE_UNLOCK;
2406
2c6ee1a7
KW
2407 return errstr;
2408 }
a0b53297
KW
2409
2410 LOCALE_UNLOCK;
2c6ee1a7
KW
2411 }
2412#endif
2413
2414 return Strerror(errnum);
2415}
2416
66610fdd 2417/*
747c467a
KW
2418
2419=head1 Locale-related functions and macros
2420
2421=for apidoc sync_locale
2422
2423Changing the program's locale should be avoided by XS code. Nevertheless,
2424certain non-Perl libraries called from XS, such as C<Gtk> do so. When this
2425happens, Perl needs to be told that the locale has changed. Use this function
2426to do so, before returning to Perl.
2427
2428=cut
2429*/
2430
2431void
2432Perl_sync_locale(pTHX)
2433{
2434
2435#ifdef USE_LOCALE_CTYPE
2436 new_ctype(setlocale(LC_CTYPE, NULL));
2437#endif /* USE_LOCALE_CTYPE */
2438
2439#ifdef USE_LOCALE_COLLATE
2440 new_collate(setlocale(LC_COLLATE, NULL));
2441#endif
2442
2443#ifdef USE_LOCALE_NUMERIC
2444 set_numeric_local(); /* Switch from "C" to underlying LC_NUMERIC */
2445 new_numeric(setlocale(LC_NUMERIC, NULL));
2446#endif /* USE_LOCALE_NUMERIC */
2447
2448}
2449
5d1187d1
KW
2450#if defined(DEBUGGING) && defined(USE_LOCALE)
2451
2452char *
2453Perl__setlocale_debug_string(const int category, /* category number,
2454 like LC_ALL */
2455 const char* const locale, /* locale name */
2456
2457 /* return value from setlocale() when attempting to
2458 * set 'category' to 'locale' */
2459 const char* const retval)
2460{
2461 /* Returns a pointer to a NUL-terminated string in static storage with
2462 * added text about the info passed in. This is not thread safe and will
2463 * be overwritten by the next call, so this should be used just to
fa07b8e5 2464 * formulate a string to immediately print or savepv() on. */
5d1187d1 2465
398a990f
DM
2466 /* initialise to a non-null value to keep it out of BSS and so keep
2467 * -DPERL_GLOBAL_STRUCT_PRIVATE happy */
2468 static char ret[128] = "x";
5d1187d1 2469
fa07b8e5 2470 my_strlcpy(ret, "setlocale(", sizeof(ret));
5d1187d1
KW
2471
2472 switch (category) {
2473 default:
fa07b8e5 2474 my_snprintf(ret, sizeof(ret), "%s? %d", ret, category);
5d1187d1
KW
2475 break;
2476# ifdef LC_ALL
2477 case LC_ALL:
fa07b8e5 2478 my_strlcat(ret, "LC_ALL", sizeof(ret));
5d1187d1
KW
2479 break;
2480# endif
2481# ifdef LC_CTYPE
2482 case LC_CTYPE:
fa07b8e5 2483 my_strlcat(ret, "LC_CTYPE", sizeof(ret));
5d1187d1
KW
2484 break;
2485# endif
2486# ifdef LC_NUMERIC
2487 case LC_NUMERIC:
fa07b8e5 2488 my_strlcat(ret, "LC_NUMERIC", sizeof(ret));
5d1187d1
KW
2489 break;
2490# endif
2491# ifdef LC_COLLATE
2492 case LC_COLLATE:
fa07b8e5 2493 my_strlcat(ret, "LC_COLLATE", sizeof(ret));
5d1187d1
KW
2494 break;
2495# endif
2496# ifdef LC_TIME
2497 case LC_TIME:
fa07b8e5 2498 my_strlcat(ret, "LC_TIME", sizeof(ret));
5d1187d1
KW
2499 break;
2500# endif
2501# ifdef LC_MONETARY
2502 case LC_MONETARY:
fa07b8e5 2503 my_strlcat(ret, "LC_MONETARY", sizeof(ret));
5d1187d1
KW
2504 break;
2505# endif
2506# ifdef LC_MESSAGES
2507 case LC_MESSAGES:
fa07b8e5 2508 my_strlcat(ret, "LC_MESSAGES", sizeof(ret));
5d1187d1
KW
2509 break;
2510# endif
2511 }
2512
fa07b8e5 2513 my_strlcat(ret, ", ", sizeof(ret));
5d1187d1
KW
2514
2515 if (locale) {
fa07b8e5
KW
2516 my_strlcat(ret, "\"", sizeof(ret));
2517 my_strlcat(ret, locale, sizeof(ret));
2518 my_strlcat(ret, "\"", sizeof(ret));
5d1187d1
KW
2519 }
2520 else {
fa07b8e5 2521 my_strlcat(ret, "NULL", sizeof(ret));
5d1187d1
KW
2522 }
2523
fa07b8e5 2524 my_strlcat(ret, ") returned ", sizeof(ret));
5d1187d1
KW
2525
2526 if (retval) {
fa07b8e5
KW
2527 my_strlcat(ret, "\"", sizeof(ret));
2528 my_strlcat(ret, retval, sizeof(ret));
2529 my_strlcat(ret, "\"", sizeof(ret));
5d1187d1
KW
2530 }
2531 else {
fa07b8e5 2532 my_strlcat(ret, "NULL", sizeof(ret));
5d1187d1
KW
2533 }
2534
2535 assert(strlen(ret) < sizeof(ret));
2536
2537 return ret;
2538}
2539
2540#endif
747c467a
KW
2541
2542
2543/*
14d04a33 2544 * ex: set ts=8 sts=4 sw=4 et:
37442d52 2545 */