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