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