This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
op.c: Remove assert exception for OP_REPEAT
[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
32 * the desired behavior of those functions at the moment.
166f8a29
DM
33 */
34
98994639
HS
35#include "EXTERN.h"
36#define PERL_IN_LOCALE_C
37#include "perl.h"
38
b310b053
JH
39#ifdef I_LANGINFO
40# include <langinfo.h>
41#endif
42
a4af207c
JH
43#include "reentr.h"
44
8ef6e574
KW
45#ifdef USE_LOCALE
46
98994639 47/*
0d071d52
KW
48 * Standardize the locale name from a string returned by 'setlocale', possibly
49 * modifying that string.
98994639 50 *
0ef2a2b2 51 * The typical return value of setlocale() is either
98994639
HS
52 * (1) "xx_YY" if the first argument of setlocale() is not LC_ALL
53 * (2) "xa_YY xb_YY ..." if the first argument of setlocale() is LC_ALL
54 * (the space-separated values represent the various sublocales,
0ef2a2b2 55 * in some unspecified order). This is not handled by this function.
98994639
HS
56 *
57 * In some platforms it has a form like "LC_SOMETHING=Lang_Country.866\n",
0ef2a2b2
KW
58 * which is harmful for further use of the string in setlocale(). This
59 * function removes the trailing new line and everything up through the '='
98994639
HS
60 *
61 */
62STATIC char *
63S_stdize_locale(pTHX_ char *locs)
64{
7452cf6a 65 const char * const s = strchr(locs, '=');
98994639
HS
66 bool okay = TRUE;
67
7918f24d
NC
68 PERL_ARGS_ASSERT_STDIZE_LOCALE;
69
8772537c
AL
70 if (s) {
71 const char * const t = strchr(s, '.');
98994639 72 okay = FALSE;
8772537c
AL
73 if (t) {
74 const char * const u = strchr(t, '\n');
75 if (u && (u[1] == 0)) {
76 const STRLEN len = u - s;
77 Move(s + 1, locs, len, char);
78 locs[len] = 0;
79 okay = TRUE;
98994639
HS
80 }
81 }
82 }
83
84 if (!okay)
85 Perl_croak(aTHX_ "Can't fix broken locale name \"%s\"", locs);
86
87 return locs;
88}
89
8ef6e574
KW
90#endif
91
98994639
HS
92void
93Perl_set_numeric_radix(pTHX)
94{
95#ifdef USE_LOCALE_NUMERIC
96# ifdef HAS_LOCALECONV
7452cf6a 97 const struct lconv* const lc = localeconv();
98994639 98
98994639
HS
99 if (lc && lc->decimal_point) {
100 if (lc->decimal_point[0] == '.' && lc->decimal_point[1] == 0) {
101 SvREFCNT_dec(PL_numeric_radix_sv);
a0714e2c 102 PL_numeric_radix_sv = NULL;
98994639
HS
103 }
104 else {
105 if (PL_numeric_radix_sv)
106 sv_setpv(PL_numeric_radix_sv, lc->decimal_point);
107 else
108 PL_numeric_radix_sv = newSVpv(lc->decimal_point, 0);
9f10db87 109 if (! is_invariant_string((U8 *) lc->decimal_point, 0)
28acfe03 110 && is_utf8_string((U8 *) lc->decimal_point, 0)
c1284011 111 && _is_cur_LC_category_utf8(LC_NUMERIC))
28acfe03
KW
112 {
113 SvUTF8_on(PL_numeric_radix_sv);
114 }
98994639
HS
115 }
116 }
117 else
a0714e2c 118 PL_numeric_radix_sv = NULL;
69014004
KW
119
120 DEBUG_L(PerlIO_printf(Perl_debug_log, "Locale radix is %s\n",
121 (PL_numeric_radix_sv)
122 ? lc->decimal_point
123 : "NULL"));
124
98994639
HS
125# endif /* HAS_LOCALECONV */
126#endif /* USE_LOCALE_NUMERIC */
127}
128
a39edc4c
KW
129/* Is the C string input 'name' "C" or "POSIX"? If so, and 'name' is the
130 * return of setlocale(), then this is extremely likely to be the C or POSIX
131 * locale. However, the output of setlocale() is documented to be opaque, but
132 * the odds are extremely small that it would return these two strings for some
133 * other locale. Note that VMS in these two locales includes many non-ASCII
134 * characters as controls and punctuation (below are hex bytes):
135 * cntrl: 00-1F 7F 84-97 9B-9F
136 * 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
137 * Oddly, none there are listed as alphas, though some represent alphabetics
138 * http://www.nntp.perl.org/group/perl.perl5.porters/2013/02/msg198753.html */
98b630b3
KW
139#define isNAME_C_OR_POSIX(name) ((name) != NULL \
140 && ((*(name) == 'C' && (*(name + 1)) == '\0') \
a39edc4c
KW
141 || strEQ((name), "POSIX")))
142
98994639 143void
8772537c 144Perl_new_numeric(pTHX_ const char *newnum)
98994639
HS
145{
146#ifdef USE_LOCALE_NUMERIC
0d071d52
KW
147
148 /* Called after all libc setlocale() calls affecting LC_NUMERIC, to tell
149 * core Perl this and that 'newnum' is the name of the new locale.
150 * It installs this locale as the current underlying default.
151 *
152 * The default locale and the C locale can be toggled between by use of the
153 * set_numeric_local() and set_numeric_standard() functions, which should
154 * probably not be called directly, but only via macros like
155 * SET_NUMERIC_STANDARD() in perl.h.
156 *
157 * The toggling is necessary mainly so that a non-dot radix decimal point
158 * character can be output, while allowing internal calculations to use a
159 * dot.
160 *
161 * This sets several interpreter-level variables:
bb304765 162 * PL_numeric_name The underlying locale's name: a copy of 'newnum'
0d071d52 163 * PL_numeric_local A boolean indicating if the toggled state is such
7738054c
KW
164 * that the current locale is the program's underlying
165 * locale
166 * PL_numeric_standard An int indicating if the toggled state is such
167 * that the current locale is the C locale. If non-zero,
168 * it is in C; if > 1, it means it may not be toggled away
169 * from C.
0d071d52
KW
170 * Note that both of the last two variables can be true at the same time,
171 * if the underlying locale is C. (Toggling is a no-op under these
172 * circumstances.)
173 *
174 * Any code changing the locale (outside this file) should use
175 * POSIX::setlocale, which calls this function. Therefore this function
176 * should be called directly only from this file and from
177 * POSIX::setlocale() */
178
b03f34cf 179 char *save_newnum;
98994639
HS
180
181 if (! newnum) {
43c5f42d
NC
182 Safefree(PL_numeric_name);
183 PL_numeric_name = NULL;
98994639
HS
184 PL_numeric_standard = TRUE;
185 PL_numeric_local = TRUE;
186 return;
187 }
188
b03f34cf
KW
189 save_newnum = stdize_locale(savepv(newnum));
190 if (! PL_numeric_name || strNE(PL_numeric_name, save_newnum)) {
98994639 191 Safefree(PL_numeric_name);
b03f34cf 192 PL_numeric_name = save_newnum;
b03f34cf 193 }
98994639 194
a39edc4c 195 PL_numeric_standard = isNAME_C_OR_POSIX(save_newnum);
e19f01cb 196 PL_numeric_local = TRUE;
4c28b29c
KW
197
198 /* Keep LC_NUMERIC in the C locale. This is for XS modules, so they don't
199 * have to worry about the radix being a non-dot. (Core operations that
200 * need the underlying locale change to it temporarily). */
201 set_numeric_standard();
202
e19f01cb 203 set_numeric_radix();
6959d69d 204
f2ce9e1c
JH
205#else
206 PERL_UNUSED_ARG(newnum);
98994639
HS
207#endif /* USE_LOCALE_NUMERIC */
208}
209
210void
211Perl_set_numeric_standard(pTHX)
212{
213#ifdef USE_LOCALE_NUMERIC
28c1bf33
KW
214 /* Toggle the LC_NUMERIC locale to C. Most code should use the macros like
215 * SET_NUMERIC_STANDARD() in perl.h instead of calling this directly. The
216 * macro avoids calling this routine if toggling isn't necessary according
217 * to our records (which could be wrong if some XS code has changed the
218 * locale behind our back) */
0d071d52 219
a9b8c0d8
KW
220 setlocale(LC_NUMERIC, "C");
221 PL_numeric_standard = TRUE;
222 PL_numeric_local = isNAME_C_OR_POSIX(PL_numeric_name);
223 set_numeric_radix();
69014004
KW
224 DEBUG_L(PerlIO_printf(Perl_debug_log,
225 "Underlying LC_NUMERIC locale now is C\n"));
98994639
HS
226
227#endif /* USE_LOCALE_NUMERIC */
228}
229
230void
231Perl_set_numeric_local(pTHX)
232{
233#ifdef USE_LOCALE_NUMERIC
28c1bf33
KW
234 /* Toggle the LC_NUMERIC locale to the current underlying default. Most
235 * code should use the macros like SET_NUMERIC_LOCAL() in perl.h instead of
236 * calling this directly. The macro avoids calling this routine if
237 * toggling isn't necessary according to our records (which could be wrong
238 * if some XS code has changed the locale behind our back) */
a9b8c0d8
KW
239
240 setlocale(LC_NUMERIC, PL_numeric_name);
241 PL_numeric_standard = isNAME_C_OR_POSIX(PL_numeric_name);
242 PL_numeric_local = TRUE;
243 set_numeric_radix();
69014004
KW
244 DEBUG_L(PerlIO_printf(Perl_debug_log,
245 "Underlying LC_NUMERIC locale now is %s\n",
246 PL_numeric_name));
98994639
HS
247
248#endif /* USE_LOCALE_NUMERIC */
249}
250
251/*
252 * Set up for a new ctype locale.
253 */
254void
8772537c 255Perl_new_ctype(pTHX_ const char *newctype)
98994639
HS
256{
257#ifdef USE_LOCALE_CTYPE
0d071d52
KW
258
259 /* Called after all libc setlocale() calls affecting LC_CTYPE, to tell
260 * core Perl this and that 'newctype' is the name of the new locale.
261 *
262 * This function sets up the folding arrays for all 256 bytes, assuming
263 * that tofold() is tolc() since fold case is not a concept in POSIX,
264 *
265 * Any code changing the locale (outside this file) should use
266 * POSIX::setlocale, which calls this function. Therefore this function
267 * should be called directly only from this file and from
268 * POSIX::setlocale() */
269
27da23d5 270 dVAR;
68067e4e 271 UV i;
98994639 272
7918f24d
NC
273 PERL_ARGS_ASSERT_NEW_CTYPE;
274
c1284011 275 PL_in_utf8_CTYPE_locale = _is_cur_LC_category_utf8(LC_CTYPE);
31f05a37
KW
276
277 /* A UTF-8 locale gets standard rules. But note that code still has to
278 * handle this specially because of the three problematic code points */
279 if (PL_in_utf8_CTYPE_locale) {
280 Copy(PL_fold_latin1, PL_fold_locale, 256, U8);
281 }
282 else {
8c6180a9
KW
283 /* Assume enough space for every character being bad. 4 spaces each
284 * for the 94 printable characters that are output like "'x' "; and 5
285 * spaces each for "'\\' ", "'\t' ", and "'\n' "; plus a terminating
286 * NUL */
287 char bad_chars_list[ (94 * 4) + (3 * 5) + 1 ];
288
289 bool check_for_problems = ckWARN_d(WARN_LOCALE); /* No warnings means
290 no check */
291 bool multi_byte_locale = FALSE; /* Assume is a single-byte locale
292 to start */
293 unsigned int bad_count = 0; /* Count of bad characters */
294
baa60164
KW
295 for (i = 0; i < 256; i++) {
296 if (isUPPER_LC((U8) i))
297 PL_fold_locale[i] = (U8) toLOWER_LC((U8) i);
298 else if (isLOWER_LC((U8) i))
299 PL_fold_locale[i] = (U8) toUPPER_LC((U8) i);
300 else
301 PL_fold_locale[i] = (U8) i;
8c6180a9
KW
302
303 /* If checking for locale problems, see if the native ASCII-range
304 * printables plus \n and \t are in their expected categories in
305 * the new locale. If not, this could mean big trouble, upending
306 * Perl's and most programs' assumptions, like having a
307 * metacharacter with special meaning become a \w. Fortunately,
308 * it's very rare to find locales that aren't supersets of ASCII
309 * nowadays. It isn't a problem for most controls to be changed
310 * into something else; we check only \n and \t, though perhaps \r
311 * could be an issue as well. */
312 if (check_for_problems
313 && (isGRAPH_A(i) || isBLANK_A(i) || i == '\n'))
314 {
315 if ((isALPHANUMERIC_A(i) && ! isALPHANUMERIC_LC(i))
316 || (isPUNCT_A(i) && ! isPUNCT_LC(i))
317 || (isBLANK_A(i) && ! isBLANK_LC(i))
318 || (i == '\n' && ! isCNTRL_LC(i)))
319 {
320 if (bad_count) { /* Separate multiple entries with a
321 blank */
322 bad_chars_list[bad_count++] = ' ';
323 }
324 bad_chars_list[bad_count++] = '\'';
325 if (isPRINT_A(i)) {
326 bad_chars_list[bad_count++] = (char) i;
327 }
328 else {
329 bad_chars_list[bad_count++] = '\\';
330 if (i == '\n') {
331 bad_chars_list[bad_count++] = 'n';
332 }
333 else {
334 assert(i == '\t');
335 bad_chars_list[bad_count++] = 't';
336 }
337 }
338 bad_chars_list[bad_count++] = '\'';
339 bad_chars_list[bad_count] = '\0';
340 }
341 }
342 }
343
344#ifdef MB_CUR_MAX
345 /* We only handle single-byte locales (outside of UTF-8 ones; so if
346 * this locale requires than one byte, there are going to be
347 * problems. */
ba1a4362
KW
348 if (check_for_problems && MB_CUR_MAX > 1
349
350 /* Some platforms return MB_CUR_MAX > 1 for even the "C"
351 * locale. Just assume that the implementation for them (plus
352 * for POSIX) is correct and the > 1 value is spurious. (Since
353 * these are specially handled to never be considered UTF-8
354 * locales, as long as this is the only problem, everything
355 * should work fine */
356 && strNE(newctype, "C") && strNE(newctype, "POSIX"))
357 {
8c6180a9
KW
358 multi_byte_locale = TRUE;
359 }
360#endif
361
362 if (bad_count || multi_byte_locale) {
eb9d0228
KW
363
364 /* We have to save 'newctype' because the setlocale() just below
365 * may destroy it. The next setlocale() further down should
366 * restore it properly so that the intermediate change here is
367 * transparent to this function's caller */
368 const char * const badlocale = savepv(newctype);
369
8c6180a9
KW
370 setlocale(LC_CTYPE, "C");
371 Perl_warner(aTHX_ packWARN(WARN_LOCALE),
372 "Locale '%s' may not work well.%s%s%s\n",
eb9d0228 373 badlocale,
8c6180a9
KW
374 (multi_byte_locale)
375 ? " Some characters in it are not recognized by"
376 " Perl."
377 : "",
378 (bad_count)
379 ? "\nThe following characters (and maybe others)"
380 " may not have the same meaning as the Perl"
381 " program expects:\n"
382 : "",
383 (bad_count)
384 ? bad_chars_list
385 : ""
386 );
eb9d0228 387 setlocale(LC_CTYPE, badlocale);
baa60164 388 }
31f05a37 389 }
98994639
HS
390
391#endif /* USE_LOCALE_CTYPE */
7918f24d 392 PERL_ARGS_ASSERT_NEW_CTYPE;
8772537c 393 PERL_UNUSED_ARG(newctype);
96a5add6 394 PERL_UNUSED_CONTEXT;
98994639
HS
395}
396
98994639 397void
8772537c 398Perl_new_collate(pTHX_ const char *newcoll)
98994639
HS
399{
400#ifdef USE_LOCALE_COLLATE
0d071d52
KW
401
402 /* Called after all libc setlocale() calls affecting LC_COLLATE, to tell
403 * core Perl this and that 'newcoll' is the name of the new locale.
404 *
405 * Any code changing the locale (outside this file) should use
406 * POSIX::setlocale, which calls this function. Therefore this function
407 * should be called directly only from this file and from
408 * POSIX::setlocale() */
409
98994639
HS
410 if (! newcoll) {
411 if (PL_collation_name) {
412 ++PL_collation_ix;
413 Safefree(PL_collation_name);
414 PL_collation_name = NULL;
415 }
416 PL_collation_standard = TRUE;
417 PL_collxfrm_base = 0;
418 PL_collxfrm_mult = 2;
419 return;
420 }
421
422 if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
423 ++PL_collation_ix;
424 Safefree(PL_collation_name);
425 PL_collation_name = stdize_locale(savepv(newcoll));
a39edc4c 426 PL_collation_standard = isNAME_C_OR_POSIX(newcoll);
98994639
HS
427
428 {
429 /* 2: at most so many chars ('a', 'b'). */
430 /* 50: surely no system expands a char more. */
431#define XFRMBUFSIZE (2 * 50)
432 char xbuf[XFRMBUFSIZE];
8772537c
AL
433 const Size_t fa = strxfrm(xbuf, "a", XFRMBUFSIZE);
434 const Size_t fb = strxfrm(xbuf, "ab", XFRMBUFSIZE);
435 const SSize_t mult = fb - fa;
e0601d3c 436 if (mult < 1 && !(fa == 0 && fb == 0))
ad49ad39
NC
437 Perl_croak(aTHX_ "panic: strxfrm() gets absurd - a => %"UVuf", ab => %"UVuf,
438 (UV) fa, (UV) fb);
eb160463 439 PL_collxfrm_base = (fa > (Size_t)mult) ? (fa - mult) : 0;
98994639
HS
440 PL_collxfrm_mult = mult;
441 }
442 }
443
f2ce9e1c
JH
444#else
445 PERL_UNUSED_ARG(newcoll);
98994639
HS
446#endif /* USE_LOCALE_COLLATE */
447}
448
b385bb4d
KW
449#ifdef WIN32
450
451char *
452Perl_my_setlocale(pTHX_ int category, const char* locale)
453{
454 /* This, for Windows, emulates POSIX setlocale() behavior. There is no
455 * difference unless the input locale is "", which means on Windows to get
456 * the machine default, which is set via the computer's "Regional and
457 * Language Options" (or its current equivalent). In POSIX, it instead
458 * means to find the locale from the user's environment. This routine
459 * looks in the environment, and, if anything is found, uses that instead
460 * of going to the machine default. If there is no environment override,
461 * the machine default is used, as normal, by calling the real setlocale()
462 * with "". The POSIX behavior is to use the LC_ALL variable if set;
463 * otherwise to use the particular category's variable if set; otherwise to
464 * use the LANG variable. */
465
481465ea 466 bool override_LC_ALL = 0;
89f7b9aa
KW
467 char * result;
468
b385bb4d
KW
469 if (locale && strEQ(locale, "")) {
470# ifdef LC_ALL
471 locale = PerlEnv_getenv("LC_ALL");
472 if (! locale) {
473#endif
474 switch (category) {
475# ifdef LC_ALL
476 case LC_ALL:
481465ea 477 override_LC_ALL = TRUE;
b385bb4d
KW
478 break; /* We already know its variable isn't set */
479# endif
480# ifdef USE_LOCALE_TIME
481 case LC_TIME:
482 locale = PerlEnv_getenv("LC_TIME");
483 break;
484# endif
485# ifdef USE_LOCALE_CTYPE
486 case LC_CTYPE:
487 locale = PerlEnv_getenv("LC_CTYPE");
488 break;
489# endif
490# ifdef USE_LOCALE_COLLATE
491 case LC_COLLATE:
492 locale = PerlEnv_getenv("LC_COLLATE");
493 break;
494# endif
495# ifdef USE_LOCALE_MONETARY
496 case LC_MONETARY:
497 locale = PerlEnv_getenv("LC_MONETARY");
498 break;
499# endif
500# ifdef USE_LOCALE_NUMERIC
501 case LC_NUMERIC:
502 locale = PerlEnv_getenv("LC_NUMERIC");
503 break;
504# endif
505# ifdef USE_LOCALE_MESSAGES
506 case LC_MESSAGES:
507 locale = PerlEnv_getenv("LC_MESSAGES");
508 break;
509# endif
510 default:
511 /* This is a category, like PAPER_SIZE that we don't
512 * know about; and so can't provide a wrapper. */
513 break;
514 }
515 if (! locale) {
516 locale = PerlEnv_getenv("LANG");
481465ea 517 if (! locale) {
b385bb4d
KW
518 locale = "";
519 }
520 }
521# ifdef LC_ALL
522 }
523# endif
524 }
525
89f7b9aa
KW
526 result = setlocale(category, locale);
527
481465ea 528 if (! override_LC_ALL) {
89f7b9aa
KW
529 return result;
530 }
531
532 /* Here the input locale was LC_ALL, and we have set it to what is in the
481465ea
KW
533 * LANG variable or the system default if there is no LANG. But these have
534 * lower priority than the other LC_foo variables, so override it for each
535 * one that is set. (If they are set to "", it means to use the same thing
536 * we just set LC_ALL to, so can skip) */
89f7b9aa
KW
537# ifdef USE_LOCALE_TIME
538 result = PerlEnv_getenv("LC_TIME");
730252b2 539 if (result && strNE(result, "")) {
89f7b9aa
KW
540 setlocale(LC_TIME, result);
541 }
542# endif
543# ifdef USE_LOCALE_CTYPE
544 result = PerlEnv_getenv("LC_CTYPE");
730252b2 545 if (result && strNE(result, "")) {
89f7b9aa
KW
546 setlocale(LC_CTYPE, result);
547 }
548# endif
549# ifdef USE_LOCALE_COLLATE
550 result = PerlEnv_getenv("LC_COLLATE");
730252b2 551 if (result && strNE(result, "")) {
89f7b9aa
KW
552 setlocale(LC_COLLATE, result);
553 }
554# endif
555# ifdef USE_LOCALE_MONETARY
556 result = PerlEnv_getenv("LC_MONETARY");
730252b2 557 if (result && strNE(result, "")) {
89f7b9aa
KW
558 setlocale(LC_MONETARY, result);
559 }
560# endif
561# ifdef USE_LOCALE_NUMERIC
562 result = PerlEnv_getenv("LC_NUMERIC");
730252b2 563 if (result && strNE(result, "")) {
89f7b9aa
KW
564 setlocale(LC_NUMERIC, result);
565 }
566# endif
567# ifdef USE_LOCALE_MESSAGES
568 result = PerlEnv_getenv("LC_MESSAGES");
730252b2 569 if (result && strNE(result, "")) {
89f7b9aa
KW
570 setlocale(LC_MESSAGES, result);
571 }
572# endif
573
574 return setlocale(LC_ALL, NULL);
575
b385bb4d
KW
576}
577
578#endif
579
580
98994639
HS
581/*
582 * Initialize locale awareness.
583 */
584int
585Perl_init_i18nl10n(pTHX_ int printwarn)
586{
0e92a118
KW
587 /* printwarn is
588 *
589 * 0 if not to output warning when setup locale is bad
590 * 1 if to output warning based on value of PERL_BADLANG
591 * >1 if to output regardless of PERL_BADLANG
592 *
593 * returns
98994639 594 * 1 = set ok or not applicable,
0e92a118
KW
595 * 0 = fallback to a locale of lower priority
596 * -1 = fallback to all locales failed, not even to the C locale
98994639
HS
597 */
598
0e92a118
KW
599 int ok = 1;
600
98994639 601#if defined(USE_LOCALE)
98994639
HS
602#ifdef USE_LOCALE_CTYPE
603 char *curctype = NULL;
604#endif /* USE_LOCALE_CTYPE */
605#ifdef USE_LOCALE_COLLATE
606 char *curcoll = NULL;
607#endif /* USE_LOCALE_COLLATE */
608#ifdef USE_LOCALE_NUMERIC
609 char *curnum = NULL;
610#endif /* USE_LOCALE_NUMERIC */
611#ifdef __GLIBC__
7452cf6a 612 char * const language = PerlEnv_getenv("LANGUAGE");
98994639 613#endif
65ebb059 614
ccd65d51
KW
615 /* NULL uses the existing already set up locale */
616 const char * const setlocale_init = (PerlEnv_getenv("PERL_SKIP_LOCALE_INIT"))
617 ? NULL
618 : "";
c3fcd832
KW
619 const char* trial_locales[5]; /* 5 = 1 each for "", LC_ALL, LANG, "", C */
620 unsigned int trial_locales_count;
7452cf6a
AL
621 char * const lc_all = PerlEnv_getenv("LC_ALL");
622 char * const lang = PerlEnv_getenv("LANG");
98994639 623 bool setlocale_failure = FALSE;
65ebb059
KW
624 unsigned int i;
625 char *p;
626 const bool locwarn = (printwarn > 1 ||
627 (printwarn &&
96e440d2
JH
628 (!(p = PerlEnv_getenv("PERL_BADLANG")) ||
629 grok_atou(p, NULL))));
0e92a118 630 bool done = FALSE;
6bce99ee
JH
631#ifdef WIN32
632 /* In some systems you can find out the system default locale
633 * and use that as the fallback locale. */
634# define SYSTEM_DEFAULT_LOCALE
635#endif
636#ifdef SYSTEM_DEFAULT_LOCALE
65ebb059 637 const char *system_default_locale = NULL;
6bce99ee 638#endif
98994639 639
0e92a118
KW
640#ifndef LOCALE_ENVIRON_REQUIRED
641 PERL_UNUSED_VAR(done);
642#else
98994639
HS
643
644 /*
645 * Ultrix setlocale(..., "") fails if there are no environment
646 * variables from which to get a locale name.
647 */
648
b3e384bf 649# ifdef LC_ALL
98994639 650 if (lang) {
b385bb4d 651 if (my_setlocale(LC_ALL, setlocale_init))
98994639
HS
652 done = TRUE;
653 else
654 setlocale_failure = TRUE;
655 }
656 if (!setlocale_failure) {
b3e384bf 657# ifdef USE_LOCALE_CTYPE
56279a21 658 Safefree(curctype);
98994639 659 if (! (curctype =
b385bb4d 660 my_setlocale(LC_CTYPE,
98994639 661 (!done && (lang || PerlEnv_getenv("LC_CTYPE")))
ccd65d51 662 ? setlocale_init : NULL)))
98994639
HS
663 setlocale_failure = TRUE;
664 else
665 curctype = savepv(curctype);
b3e384bf
KW
666# endif /* USE_LOCALE_CTYPE */
667# ifdef USE_LOCALE_COLLATE
56279a21 668 Safefree(curcoll);
98994639 669 if (! (curcoll =
b385bb4d 670 my_setlocale(LC_COLLATE,
98994639 671 (!done && (lang || PerlEnv_getenv("LC_COLLATE")))
ccd65d51 672 ? setlocale_init : NULL)))
98994639
HS
673 setlocale_failure = TRUE;
674 else
675 curcoll = savepv(curcoll);
b3e384bf
KW
676# endif /* USE_LOCALE_COLLATE */
677# ifdef USE_LOCALE_NUMERIC
56279a21 678 Safefree(curnum);
98994639 679 if (! (curnum =
b385bb4d 680 my_setlocale(LC_NUMERIC,
98994639 681 (!done && (lang || PerlEnv_getenv("LC_NUMERIC")))
ccd65d51 682 ? setlocale_init : NULL)))
98994639
HS
683 setlocale_failure = TRUE;
684 else
685 curnum = savepv(curnum);
b3e384bf 686# endif /* USE_LOCALE_NUMERIC */
a782673d
KW
687# ifdef USE_LOCALE_MESSAGES
688 if (! my_setlocale(LC_MESSAGES,
689 (!done && (lang || PerlEnv_getenv("LC_MESSAGES")))
690 ? setlocale_init : NULL))
691 {
692 setlocale_failure = TRUE;
693 }
694# endif /* USE_LOCALE_MESSAGES */
c835d6be
KW
695# ifdef USE_LOCALE_MONETARY
696 if (! my_setlocale(LC_MONETARY,
697 (!done && (lang || PerlEnv_getenv("LC_MONETARY")))
698 ? setlocale_init : NULL))
699 {
700 setlocale_failure = TRUE;
701 }
702# endif /* USE_LOCALE_MONETARY */
98994639
HS
703 }
704
b3e384bf 705# endif /* LC_ALL */
98994639
HS
706
707#endif /* !LOCALE_ENVIRON_REQUIRED */
708
65ebb059
KW
709 /* We try each locale in the list until we get one that works, or exhaust
710 * the list */
c3fcd832
KW
711 trial_locales[0] = setlocale_init;
712 trial_locales_count = 1;
65ebb059
KW
713 for (i= 0; i < trial_locales_count; i++) {
714 const char * trial_locale = trial_locales[i];
715
716 if (i > 0) {
717
718 /* XXX This is to preserve old behavior for LOCALE_ENVIRON_REQUIRED
719 * when i==0, but I (khw) don't think that behavior makes much
720 * sense */
721 setlocale_failure = FALSE;
722
6bce99ee
JH
723#ifdef SYSTEM_DEFAULT_LOCALE
724# ifdef WIN32
65ebb059
KW
725 /* On Windows machines, an entry of "" after the 0th means to use
726 * the system default locale, which we now proceed to get. */
727 if (strEQ(trial_locale, "")) {
728 unsigned int j;
729
730 /* Note that this may change the locale, but we are going to do
731 * that anyway just below */
732 system_default_locale = setlocale(LC_ALL, "");
733
734 /* Skip if invalid or it's already on the list of locales to
735 * try */
736 if (! system_default_locale) {
737 goto next_iteration;
738 }
739 for (j = 0; j < trial_locales_count; j++) {
740 if (strEQ(system_default_locale, trial_locales[j])) {
741 goto next_iteration;
742 }
743 }
744
745 trial_locale = system_default_locale;
746 }
6bce99ee
JH
747# endif /* WIN32 */
748#endif /* SYSTEM_DEFAULT_LOCALE */
65ebb059
KW
749 }
750
98994639 751#ifdef LC_ALL
7cd8b568 752 if (! my_setlocale(LC_ALL, trial_locale)) {
49c85077 753 setlocale_failure = TRUE;
7cd8b568
KW
754 }
755 else {
756 /* Since LC_ALL succeeded, it should have changed all the other
757 * categories it can to its value; so we massage things so that the
758 * setlocales below just return their category's current values.
759 * This adequately handles the case in NetBSD where LC_COLLATE may
760 * not be defined for a locale, and setting it individually will
761 * fail, whereas setting LC_ALL suceeds, leaving LC_COLLATE set to
762 * the POSIX locale. */
763 trial_locale = NULL;
764 }
98994639
HS
765#endif /* LC_ALL */
766
49c85077 767 if (!setlocale_failure) {
98994639 768#ifdef USE_LOCALE_CTYPE
49c85077
KW
769 Safefree(curctype);
770 if (! (curctype = my_setlocale(LC_CTYPE, trial_locale)))
771 setlocale_failure = TRUE;
772 else
773 curctype = savepv(curctype);
98994639
HS
774#endif /* USE_LOCALE_CTYPE */
775#ifdef USE_LOCALE_COLLATE
49c85077
KW
776 Safefree(curcoll);
777 if (! (curcoll = my_setlocale(LC_COLLATE, trial_locale)))
778 setlocale_failure = TRUE;
779 else
780 curcoll = savepv(curcoll);
98994639
HS
781#endif /* USE_LOCALE_COLLATE */
782#ifdef USE_LOCALE_NUMERIC
49c85077
KW
783 Safefree(curnum);
784 if (! (curnum = my_setlocale(LC_NUMERIC, trial_locale)))
785 setlocale_failure = TRUE;
786 else
787 curnum = savepv(curnum);
98994639 788#endif /* USE_LOCALE_NUMERIC */
a782673d
KW
789#ifdef USE_LOCALE_MESSAGES
790 if (! (my_setlocale(LC_MESSAGES, trial_locale)))
791 setlocale_failure = TRUE;
792#endif /* USE_LOCALE_MESSAGES */
c835d6be
KW
793#ifdef USE_LOCALE_MONETARY
794 if (! (my_setlocale(LC_MONETARY, trial_locale)))
795 setlocale_failure = TRUE;
796#endif /* USE_LOCALE_MONETARY */
797
49c85077
KW
798 if (! setlocale_failure) { /* Success */
799 break;
800 }
65ebb059 801 }
98994639 802
49c85077
KW
803 /* Here, something failed; will need to try a fallback. */
804 ok = 0;
65ebb059 805
49c85077
KW
806 if (i == 0) {
807 unsigned int j;
98994639 808
65ebb059 809 if (locwarn) { /* Output failure info only on the first one */
98994639
HS
810#ifdef LC_ALL
811
49c85077
KW
812 PerlIO_printf(Perl_error_log,
813 "perl: warning: Setting locale failed.\n");
98994639
HS
814
815#else /* !LC_ALL */
816
49c85077
KW
817 PerlIO_printf(Perl_error_log,
818 "perl: warning: Setting locale failed for the categories:\n\t");
98994639 819#ifdef USE_LOCALE_CTYPE
49c85077
KW
820 if (! curctype)
821 PerlIO_printf(Perl_error_log, "LC_CTYPE ");
98994639
HS
822#endif /* USE_LOCALE_CTYPE */
823#ifdef USE_LOCALE_COLLATE
49c85077
KW
824 if (! curcoll)
825 PerlIO_printf(Perl_error_log, "LC_COLLATE ");
98994639
HS
826#endif /* USE_LOCALE_COLLATE */
827#ifdef USE_LOCALE_NUMERIC
49c85077
KW
828 if (! curnum)
829 PerlIO_printf(Perl_error_log, "LC_NUMERIC ");
98994639 830#endif /* USE_LOCALE_NUMERIC */
a782673d 831 PerlIO_printf(Perl_error_log, "and possibly others\n");
98994639
HS
832
833#endif /* LC_ALL */
834
49c85077
KW
835 PerlIO_printf(Perl_error_log,
836 "perl: warning: Please check that your locale settings:\n");
98994639
HS
837
838#ifdef __GLIBC__
49c85077
KW
839 PerlIO_printf(Perl_error_log,
840 "\tLANGUAGE = %c%s%c,\n",
841 language ? '"' : '(',
842 language ? language : "unset",
843 language ? '"' : ')');
98994639
HS
844#endif
845
49c85077
KW
846 PerlIO_printf(Perl_error_log,
847 "\tLC_ALL = %c%s%c,\n",
848 lc_all ? '"' : '(',
849 lc_all ? lc_all : "unset",
850 lc_all ? '"' : ')');
98994639
HS
851
852#if defined(USE_ENVIRON_ARRAY)
49c85077
KW
853 {
854 char **e;
855 for (e = environ; *e; e++) {
856 if (strnEQ(*e, "LC_", 3)
857 && strnNE(*e, "LC_ALL=", 7)
858 && (p = strchr(*e, '=')))
859 PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
860 (int)(p - *e), *e, p + 1);
861 }
862 }
98994639 863#else
49c85077
KW
864 PerlIO_printf(Perl_error_log,
865 "\t(possibly more locale environment variables)\n");
98994639
HS
866#endif
867
49c85077
KW
868 PerlIO_printf(Perl_error_log,
869 "\tLANG = %c%s%c\n",
870 lang ? '"' : '(',
871 lang ? lang : "unset",
872 lang ? '"' : ')');
98994639 873
49c85077
KW
874 PerlIO_printf(Perl_error_log,
875 " are supported and installed on your system.\n");
876 }
98994639 877
65ebb059
KW
878 /* Calculate what fallback locales to try. We have avoided this
879 * until we have to, becuase failure is quite unlikely. This will
880 * usually change the upper bound of the loop we are in.
881 *
882 * Since the system's default way of setting the locale has not
883 * found one that works, We use Perl's defined ordering: LC_ALL,
884 * LANG, and the C locale. We don't try the same locale twice, so
885 * don't add to the list if already there. (On POSIX systems, the
886 * LC_ALL element will likely be a repeat of the 0th element "",
887 * but there's no harm done by doing it explicitly */
888 if (lc_all) {
889 for (j = 0; j < trial_locales_count; j++) {
890 if (strEQ(lc_all, trial_locales[j])) {
891 goto done_lc_all;
892 }
893 }
894 trial_locales[trial_locales_count++] = lc_all;
895 }
896 done_lc_all:
98994639 897
65ebb059
KW
898 if (lang) {
899 for (j = 0; j < trial_locales_count; j++) {
900 if (strEQ(lang, trial_locales[j])) {
901 goto done_lang;
902 }
903 }
904 trial_locales[trial_locales_count++] = lang;
905 }
906 done_lang:
907
908#if defined(WIN32) && defined(LC_ALL)
909 /* For Windows, we also try the system default locale before "C".
910 * (If there exists a Windows without LC_ALL we skip this because
911 * it gets too complicated. For those, the "C" is the next
912 * fallback possibility). The "" is the same as the 0th element of
913 * the array, but the code at the loop above knows to treat it
914 * differently when not the 0th */
915 trial_locales[trial_locales_count++] = "";
916#endif
917
918 for (j = 0; j < trial_locales_count; j++) {
919 if (strEQ("C", trial_locales[j])) {
920 goto done_C;
921 }
922 }
923 trial_locales[trial_locales_count++] = "C";
98994639 924
65ebb059
KW
925 done_C: ;
926 } /* end of first time through the loop */
98994639 927
65ebb059
KW
928#ifdef WIN32
929 next_iteration: ;
930#endif
931
932 } /* end of looping through the trial locales */
933
934 if (ok < 1) { /* If we tried to fallback */
935 const char* msg;
936 if (! setlocale_failure) { /* fallback succeeded */
937 msg = "Falling back to";
938 }
939 else { /* fallback failed */
98994639 940
65ebb059
KW
941 /* We dropped off the end of the loop, so have to decrement i to
942 * get back to the value the last time through */
943 i--;
98994639 944
65ebb059
KW
945 ok = -1;
946 msg = "Failed to fall back to";
947
948 /* To continue, we should use whatever values we've got */
98994639 949#ifdef USE_LOCALE_CTYPE
49c85077
KW
950 Safefree(curctype);
951 curctype = savepv(setlocale(LC_CTYPE, NULL));
98994639
HS
952#endif /* USE_LOCALE_CTYPE */
953#ifdef USE_LOCALE_COLLATE
49c85077
KW
954 Safefree(curcoll);
955 curcoll = savepv(setlocale(LC_COLLATE, NULL));
98994639
HS
956#endif /* USE_LOCALE_COLLATE */
957#ifdef USE_LOCALE_NUMERIC
49c85077
KW
958 Safefree(curnum);
959 curnum = savepv(setlocale(LC_NUMERIC, NULL));
98994639 960#endif /* USE_LOCALE_NUMERIC */
65ebb059
KW
961 }
962
963 if (locwarn) {
964 const char * description;
965 const char * name = "";
966 if (strEQ(trial_locales[i], "C")) {
967 description = "the standard locale";
968 name = "C";
969 }
6bce99ee 970#ifdef SYSTEM_DEFAULT_LOCALE
65ebb059
KW
971 else if (strEQ(trial_locales[i], "")) {
972 description = "the system default locale";
973 if (system_default_locale) {
974 name = system_default_locale;
975 }
976 }
6bce99ee 977#endif /* SYSTEM_DEFAULT_LOCALE */
65ebb059
KW
978 else {
979 description = "a fallback locale";
980 name = trial_locales[i];
981 }
982 if (name && strNE(name, "")) {
983 PerlIO_printf(Perl_error_log,
984 "perl: warning: %s %s (\"%s\").\n", msg, description, name);
985 }
986 else {
987 PerlIO_printf(Perl_error_log,
988 "perl: warning: %s %s.\n", msg, description);
989 }
990 }
991 } /* End of tried to fallback */
98994639
HS
992
993#ifdef USE_LOCALE_CTYPE
994 new_ctype(curctype);
995#endif /* USE_LOCALE_CTYPE */
996
997#ifdef USE_LOCALE_COLLATE
998 new_collate(curcoll);
999#endif /* USE_LOCALE_COLLATE */
1000
1001#ifdef USE_LOCALE_NUMERIC
1002 new_numeric(curnum);
1003#endif /* USE_LOCALE_NUMERIC */
b310b053 1004
8ef6e574 1005#if defined(USE_PERLIO) && defined(USE_LOCALE_CTYPE)
49c85077
KW
1006 /* Set PL_utf8locale to TRUE if using PerlIO _and_ the current LC_CTYPE
1007 * locale is UTF-8. If PL_utf8locale and PL_unicode (set by -C or by
1008 * $ENV{PERL_UNICODE}) are true, perl.c:S_parse_body() will turn on the
1009 * PerlIO :utf8 layer on STDIN, STDOUT, STDERR, _and_ the default open
1010 * discipline. */
c1284011 1011 PL_utf8locale = _is_cur_LC_category_utf8(LC_CTYPE);
49c85077 1012
a05d7ebb 1013 /* Set PL_unicode to $ENV{PERL_UNICODE} if using PerlIO.
fde18df1
JH
1014 This is an alternative to using the -C command line switch
1015 (the -C if present will override this). */
1016 {
dd374669 1017 const char *p = PerlEnv_getenv("PERL_UNICODE");
a05d7ebb 1018 PL_unicode = p ? parse_unicode_opts(&p) : 0;
5a22a2bb
NC
1019 if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
1020 PL_utf8cache = -1;
b310b053 1021 }
ec71e770 1022#endif
b310b053 1023
98994639 1024#ifdef USE_LOCALE_CTYPE
43c5f42d 1025 Safefree(curctype);
98994639
HS
1026#endif /* USE_LOCALE_CTYPE */
1027#ifdef USE_LOCALE_COLLATE
43c5f42d 1028 Safefree(curcoll);
98994639
HS
1029#endif /* USE_LOCALE_COLLATE */
1030#ifdef USE_LOCALE_NUMERIC
43c5f42d 1031 Safefree(curnum);
98994639 1032#endif /* USE_LOCALE_NUMERIC */
8ef6e574 1033
f2ce9e1c
JH
1034#else /* !USE_LOCALE */
1035 PERL_UNUSED_ARG(printwarn);
8ef6e574
KW
1036#endif /* USE_LOCALE */
1037
98994639
HS
1038 return ok;
1039}
1040
49c85077 1041
98994639
HS
1042#ifdef USE_LOCALE_COLLATE
1043
1044/*
1045 * mem_collxfrm() is a bit like strxfrm() but with two important
1046 * differences. First, it handles embedded NULs. Second, it allocates
1047 * a bit more memory than needed for the transformed data itself.
1048 * The real transformed data begins at offset sizeof(collationix).
1049 * Please see sv_collxfrm() to see how this is used.
1050 */
166f8a29 1051
98994639
HS
1052char *
1053Perl_mem_collxfrm(pTHX_ const char *s, STRLEN len, STRLEN *xlen)
1054{
1055 char *xbuf;
1056 STRLEN xAlloc, xin, xout; /* xalloc is a reserved word in VC */
1057
7918f24d
NC
1058 PERL_ARGS_ASSERT_MEM_COLLXFRM;
1059
98994639
HS
1060 /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
1061 /* the +1 is for the terminating NUL. */
1062
1063 xAlloc = sizeof(PL_collation_ix) + PL_collxfrm_base + (PL_collxfrm_mult * len) + 1;
a02a5408 1064 Newx(xbuf, xAlloc, char);
98994639
HS
1065 if (! xbuf)
1066 goto bad;
1067
1068 *(U32*)xbuf = PL_collation_ix;
1069 xout = sizeof(PL_collation_ix);
1070 for (xin = 0; xin < len; ) {
224e8ef5 1071 Size_t xused;
98994639
HS
1072
1073 for (;;) {
1074 xused = strxfrm(xbuf + xout, s + xin, xAlloc - xout);
224e8ef5 1075 if (xused >= PERL_INT_MAX)
98994639 1076 goto bad;
eb160463 1077 if ((STRLEN)xused < xAlloc - xout)
98994639
HS
1078 break;
1079 xAlloc = (2 * xAlloc) + 1;
1080 Renew(xbuf, xAlloc, char);
1081 if (! xbuf)
1082 goto bad;
1083 }
1084
1085 xin += strlen(s + xin) + 1;
1086 xout += xused;
1087
1088 /* Embedded NULs are understood but silently skipped
1089 * because they make no sense in locale collation. */
1090 }
1091
1092 xbuf[xout] = '\0';
1093 *xlen = xout - sizeof(PL_collation_ix);
1094 return xbuf;
1095
1096 bad:
1097 Safefree(xbuf);
1098 *xlen = 0;
1099 return NULL;
1100}
1101
1102#endif /* USE_LOCALE_COLLATE */
1103
8ef6e574
KW
1104#ifdef USE_LOCALE
1105
c1284011
KW
1106bool
1107Perl__is_cur_LC_category_utf8(pTHX_ int category)
7d74bb61
KW
1108{
1109 /* Returns TRUE if the current locale for 'category' is UTF-8; FALSE
1110 * otherwise. 'category' may not be LC_ALL. If the platform doesn't have
119ee68b 1111 * nl_langinfo(), nor MB_CUR_MAX, this employs a heuristic, which hence
609548d2
KW
1112 * could give the wrong result. The result will very likely be correct for
1113 * languages that have commonly used non-ASCII characters, but for notably
1114 * English, it comes down to if the locale's name ends in something like
1115 * "UTF-8". It errs on the side of not being a UTF-8 locale. */
7d74bb61
KW
1116
1117 char *save_input_locale = NULL;
7d74bb61
KW
1118 STRLEN final_pos;
1119
8ef6e574 1120#ifdef LC_ALL
7d74bb61 1121 assert(category != LC_ALL);
8ef6e574 1122#endif
7d74bb61
KW
1123
1124 /* First dispose of the trivial cases */
b07fffd1 1125 save_input_locale = setlocale(category, NULL);
7d74bb61 1126 if (! save_input_locale) {
69014004
KW
1127 DEBUG_L(PerlIO_printf(Perl_debug_log,
1128 "Could not find current locale for category %d\n",
1129 category));
7d74bb61
KW
1130 return FALSE; /* XXX maybe should croak */
1131 }
b07fffd1 1132 save_input_locale = stdize_locale(savepv(save_input_locale));
a39edc4c 1133 if (isNAME_C_OR_POSIX(save_input_locale)) {
69014004
KW
1134 DEBUG_L(PerlIO_printf(Perl_debug_log,
1135 "Current locale for category %d is %s\n",
1136 category, save_input_locale));
b07fffd1 1137 Safefree(save_input_locale);
7d74bb61
KW
1138 return FALSE;
1139 }
1140
1d958db2
KW
1141#if defined(USE_LOCALE_CTYPE) \
1142 && (defined(MB_CUR_MAX) || (defined(HAS_NL_LANGINFO) && defined(CODESET)))
7d74bb61 1143
1d958db2 1144 { /* Next try nl_langinfo or MB_CUR_MAX if available */
7d74bb61
KW
1145
1146 char *save_ctype_locale = NULL;
119ee68b 1147 bool is_utf8;
7d74bb61 1148
119ee68b 1149 if (category != LC_CTYPE) { /* These work only on LC_CTYPE */
7d74bb61
KW
1150
1151 /* Get the current LC_CTYPE locale */
4f72bb37 1152 save_ctype_locale = setlocale(LC_CTYPE, NULL);
7d74bb61 1153 if (! save_ctype_locale) {
69014004
KW
1154 DEBUG_L(PerlIO_printf(Perl_debug_log,
1155 "Could not find current locale for LC_CTYPE\n"));
7d74bb61
KW
1156 goto cant_use_nllanginfo;
1157 }
4f72bb37 1158 save_ctype_locale = stdize_locale(savepv(save_ctype_locale));
7d74bb61
KW
1159
1160 /* If LC_CTYPE and the desired category use the same locale, this
1161 * means that finding the value for LC_CTYPE is the same as finding
1162 * the value for the desired category. Otherwise, switch LC_CTYPE
1163 * to the desired category's locale */
1164 if (strEQ(save_ctype_locale, save_input_locale)) {
1165 Safefree(save_ctype_locale);
1166 save_ctype_locale = NULL;
1167 }
1168 else if (! setlocale(LC_CTYPE, save_input_locale)) {
69014004
KW
1169 DEBUG_L(PerlIO_printf(Perl_debug_log,
1170 "Could not change LC_CTYPE locale to %s\n",
1171 save_input_locale));
7d74bb61
KW
1172 Safefree(save_ctype_locale);
1173 goto cant_use_nllanginfo;
1174 }
1175 }
1176
69014004
KW
1177 DEBUG_L(PerlIO_printf(Perl_debug_log, "Current LC_CTYPE locale=%s\n",
1178 save_input_locale));
1179
7d74bb61 1180 /* Here the current LC_CTYPE is set to the locale of the category whose
1d958db2
KW
1181 * information is desired. This means that nl_langinfo() and MB_CUR_MAX
1182 * should give the correct results */
119ee68b 1183
1d958db2
KW
1184# if defined(HAS_NL_LANGINFO) && defined(CODESET)
1185 {
4f72bb37 1186 char *codeset = nl_langinfo(CODESET);
1d958db2 1187 if (codeset && strNE(codeset, "")) {
4f72bb37 1188 codeset = savepv(codeset);
119ee68b 1189
1d958db2
KW
1190 /* If we switched LC_CTYPE, switch back */
1191 if (save_ctype_locale) {
1192 setlocale(LC_CTYPE, save_ctype_locale);
1193 Safefree(save_ctype_locale);
1194 }
1195
1196 is_utf8 = foldEQ(codeset, STR_WITH_LEN("UTF-8"))
1197 || foldEQ(codeset, STR_WITH_LEN("UTF8"));
1198
69014004
KW
1199 DEBUG_L(PerlIO_printf(Perl_debug_log,
1200 "\tnllanginfo returned CODESET '%s'; ?UTF8 locale=%d\n",
1201 codeset, is_utf8));
1d958db2
KW
1202 Safefree(codeset);
1203 Safefree(save_input_locale);
1204 return is_utf8;
1205 }
119ee68b
KW
1206 }
1207
1d958db2
KW
1208# endif
1209# ifdef MB_CUR_MAX
1210
1211 /* Here, either we don't have nl_langinfo, or it didn't return a
1212 * codeset. Try MB_CUR_MAX */
1213
119ee68b
KW
1214 /* Standard UTF-8 needs at least 4 bytes to represent the maximum
1215 * Unicode code point. Since UTF-8 is the only non-single byte
1216 * encoding we handle, we just say any such encoding is UTF-8, and if
1217 * turns out to be wrong, other things will fail */
1218 is_utf8 = MB_CUR_MAX >= 4;
1219
69014004
KW
1220 DEBUG_L(PerlIO_printf(Perl_debug_log,
1221 "\tMB_CUR_MAX=%d; ?UTF8 locale=%d\n",
1222 (int) MB_CUR_MAX, is_utf8));
1223
119ee68b
KW
1224 Safefree(save_input_locale);
1225
1226# ifdef HAS_MBTOWC
1227
1228 /* ... But, most system that have MB_CUR_MAX will also have mbtowc(),
1229 * since they are both in the C99 standard. We can feed a known byte
1230 * string to the latter function, and check that it gives the expected
1231 * result */
1232 if (is_utf8) {
1233 wchar_t wc;
856b881c 1234 PERL_UNUSED_RESULT(mbtowc(&wc, NULL, 0));/* Reset any shift state */
69014004 1235 errno = 0;
f019f68f 1236 if ((size_t)mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8))
119ee68b
KW
1237 != strlen(HYPHEN_UTF8)
1238 || wc != (wchar_t) 0x2010)
1239 {
1240 is_utf8 = FALSE;
abdcbdb8 1241 DEBUG_L(PerlIO_printf(Perl_debug_log, "\thyphen=U+%x\n", (unsigned int)wc));
69014004
KW
1242 DEBUG_L(PerlIO_printf(Perl_debug_log,
1243 "\treturn from mbtowc=%d; errno=%d; ?UTF8 locale=0\n",
1244 mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8)), errno));
119ee68b
KW
1245 }
1246 }
119ee68b
KW
1247# endif
1248
1d958db2
KW
1249 /* If we switched LC_CTYPE, switch back */
1250 if (save_ctype_locale) {
1251 setlocale(LC_CTYPE, save_ctype_locale);
1252 Safefree(save_ctype_locale);
119ee68b 1253 }
7d74bb61 1254
1d958db2 1255 return is_utf8;
119ee68b 1256# endif
7d74bb61 1257 }
119ee68b 1258
7d74bb61
KW
1259 cant_use_nllanginfo:
1260
0080c90a
KW
1261#else /* nl_langinfo should work if available, so don't bother compiling this
1262 fallback code. The final fallback of looking at the name is
1263 compiled, and will be executed if nl_langinfo fails */
7d74bb61 1264
97f4de96
KW
1265 /* nl_langinfo not available or failed somehow. Next try looking at the
1266 * currency symbol to see if it disambiguates things. Often that will be
1267 * in the native script, and if the symbol isn't in UTF-8, we know that the
1268 * locale isn't. If it is non-ASCII UTF-8, we infer that the locale is
609548d2
KW
1269 * too, as the odds of a non-UTF8 string being valid UTF-8 are quite small
1270 * */
fa9b773e
KW
1271
1272#ifdef HAS_LOCALECONV
fa9b773e 1273# ifdef USE_LOCALE_MONETARY
fa9b773e
KW
1274 {
1275 char *save_monetary_locale = NULL;
fa9b773e 1276 bool only_ascii = FALSE;
13542a67
KW
1277 bool is_utf8 = FALSE;
1278 struct lconv* lc;
fa9b773e 1279
97f4de96
KW
1280 /* Like above for LC_CTYPE, we first set LC_MONETARY to the locale of
1281 * the desired category, if it isn't that locale already */
1282
fa9b773e
KW
1283 if (category != LC_MONETARY) {
1284
4f72bb37 1285 save_monetary_locale = setlocale(LC_MONETARY, NULL);
fa9b773e 1286 if (! save_monetary_locale) {
69014004
KW
1287 DEBUG_L(PerlIO_printf(Perl_debug_log,
1288 "Could not find current locale for LC_MONETARY\n"));
fa9b773e
KW
1289 goto cant_use_monetary;
1290 }
4f72bb37 1291 save_monetary_locale = stdize_locale(savepv(save_monetary_locale));
fa9b773e 1292
13542a67
KW
1293 if (strEQ(save_monetary_locale, save_input_locale)) {
1294 Safefree(save_monetary_locale);
1295 save_monetary_locale = NULL;
1296 }
1297 else if (! setlocale(LC_MONETARY, save_input_locale)) {
59c234b4
KW
1298 DEBUG_L(PerlIO_printf(Perl_debug_log,
1299 "Could not change LC_MONETARY locale to %s\n",
1300 save_input_locale));
1301 Safefree(save_monetary_locale);
1302 goto cant_use_monetary;
fa9b773e
KW
1303 }
1304 }
1305
1306 /* Here the current LC_MONETARY is set to the locale of the category
1307 * whose information is desired. */
1308
13542a67
KW
1309 lc = localeconv();
1310 if (! lc
1311 || ! lc->currency_symbol
9f10db87 1312 || is_invariant_string((U8 *) lc->currency_symbol, 0))
13542a67
KW
1313 {
1314 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));
1315 only_ascii = TRUE;
1316 }
1317 else {
1318 is_utf8 = is_utf8_string((U8 *) lc->currency_symbol, 0);
fa9b773e
KW
1319 }
1320
1321 /* If we changed it, restore LC_MONETARY to its original locale */
1322 if (save_monetary_locale) {
1323 setlocale(LC_MONETARY, save_monetary_locale);
1324 Safefree(save_monetary_locale);
1325 }
1326
13542a67 1327 if (! only_ascii) {
fa9b773e 1328
59c234b4
KW
1329 /* It isn't a UTF-8 locale if the symbol is not legal UTF-8;
1330 * otherwise assume the locale is UTF-8 if and only if the symbol
1331 * is non-ascii UTF-8. */
1332 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?Currency symbol for %s is UTF-8=%d\n",
1333 save_input_locale, is_utf8));
1334 Safefree(save_input_locale);
1335 return is_utf8;
13542a67 1336 }
fa9b773e
KW
1337 }
1338 cant_use_monetary:
1339
1340# endif /* USE_LOCALE_MONETARY */
1341#endif /* HAS_LOCALECONV */
1342
15f7e74e
KW
1343#if defined(HAS_STRFTIME) && defined(USE_LOCALE_TIME)
1344
1345/* Still haven't found a non-ASCII string to disambiguate UTF-8 or not. Try
1346 * the names of the months and weekdays, timezone, and am/pm indicator */
1347 {
1348 char *save_time_locale = NULL;
1349 int hour = 10;
1350 bool is_dst = FALSE;
1351 int dom = 1;
1352 int month = 0;
1353 int i;
1354 char * formatted_time;
1355
1356
1357 /* Like above for LC_MONETARY, we set LC_TIME to the locale of the
1358 * desired category, if it isn't that locale already */
1359
1360 if (category != LC_TIME) {
1361
1362 save_time_locale = setlocale(LC_TIME, NULL);
1363 if (! save_time_locale) {
1364 DEBUG_L(PerlIO_printf(Perl_debug_log,
1365 "Could not find current locale for LC_TIME\n"));
1366 goto cant_use_time;
1367 }
1368 save_time_locale = stdize_locale(savepv(save_time_locale));
1369
1370 if (strEQ(save_time_locale, save_input_locale)) {
1371 Safefree(save_time_locale);
1372 save_time_locale = NULL;
1373 }
1374 else if (! setlocale(LC_TIME, save_input_locale)) {
1375 DEBUG_L(PerlIO_printf(Perl_debug_log,
1376 "Could not change LC_TIME locale to %s\n",
1377 save_input_locale));
1378 Safefree(save_time_locale);
1379 goto cant_use_time;
1380 }
1381 }
1382
1383 /* Here the current LC_TIME is set to the locale of the category
1384 * whose information is desired. Look at all the days of the week and
9f10db87 1385 * month names, and the timezone and am/pm indicator for UTF-8 variant
15f7e74e
KW
1386 * characters. The first such a one found will tell us if the locale
1387 * is UTF-8 or not */
1388
1389 for (i = 0; i < 7 + 12; i++) { /* 7 days; 12 months */
1390 formatted_time = my_strftime("%A %B %Z %p",
1391 0, 0, hour, dom, month, 112, 0, 0, is_dst);
9f10db87 1392 if (! formatted_time || is_invariant_string((U8 *) formatted_time, 0)) {
15f7e74e
KW
1393
1394 /* Here, we didn't find a non-ASCII. Try the next time through
1395 * with the complemented dst and am/pm, and try with the next
1396 * weekday. After we have gotten all weekdays, try the next
1397 * month */
1398 is_dst = ! is_dst;
1399 hour = (hour + 12) % 24;
1400 dom++;
1401 if (i > 6) {
1402 month++;
1403 }
1404 continue;
1405 }
1406
1407 /* Here, we have a non-ASCII. Return TRUE is it is valid UTF8;
1408 * false otherwise. But first, restore LC_TIME to its original
1409 * locale if we changed it */
1410 if (save_time_locale) {
1411 setlocale(LC_TIME, save_time_locale);
1412 Safefree(save_time_locale);
1413 }
1414
1415 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?time-related strings for %s are UTF-8=%d\n",
1416 save_input_locale,
1417 is_utf8_string((U8 *) formatted_time, 0)));
1418 Safefree(save_input_locale);
1419 return is_utf8_string((U8 *) formatted_time, 0);
1420 }
1421
1422 /* Falling off the end of the loop indicates all the names were just
1423 * ASCII. Go on to the next test. If we changed it, restore LC_TIME
1424 * to its original locale */
1425 if (save_time_locale) {
1426 setlocale(LC_TIME, save_time_locale);
1427 Safefree(save_time_locale);
1428 }
1429 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));
1430 }
1431 cant_use_time:
1432
1433#endif
1434
1435#if 0 && defined(USE_LOCALE_MESSAGES) && defined(HAS_SYS_ERRLIST)
855aeb93
JH
1436
1437/* This code is ifdefd out because it was found to not be necessary in testing
5857e934
KW
1438 * on our dromedary test machine, which has over 700 locales. There, this
1439 * added no value to looking at the currency symbol and the time strings. I
1440 * left it in so as to avoid rewriting it if real-world experience indicates
1441 * that dromedary is an outlier. Essentially, instead of returning abpve if we
855aeb93
JH
1442 * haven't found illegal utf8, we continue on and examine all the strerror()
1443 * messages on the platform for utf8ness. If all are ASCII, we still don't
1444 * know the answer; but otherwise we have a pretty good indication of the
5857e934
KW
1445 * utf8ness. The reason this doesn't help much is that the messages may not
1446 * have been translated into the locale. The currency symbol and time strings
1447 * are much more likely to have been translated. */
1448 {
855aeb93 1449 int e;
5857e934
KW
1450 bool is_utf8 = FALSE;
1451 bool non_ascii = FALSE;
855aeb93 1452 char *save_messages_locale = NULL;
5857e934 1453 const char * errmsg = NULL;
855aeb93 1454
5857e934
KW
1455 /* Like above, we set LC_MESSAGES to the locale of the desired
1456 * category, if it isn't that locale already */
855aeb93
JH
1457
1458 if (category != LC_MESSAGES) {
1459
5857e934 1460 save_messages_locale = setlocale(LC_MESSAGES, NULL);
855aeb93 1461 if (! save_messages_locale) {
5857e934
KW
1462 DEBUG_L(PerlIO_printf(Perl_debug_log,
1463 "Could not find current locale for LC_MESSAGES\n"));
855aeb93
JH
1464 goto cant_use_messages;
1465 }
5857e934 1466 save_messages_locale = stdize_locale(savepv(save_messages_locale));
855aeb93
JH
1467
1468 if (strEQ(save_messages_locale, save_input_locale)) {
5857e934
KW
1469 Safefree(save_messages_locale);
1470 save_messages_locale = NULL;
855aeb93
JH
1471 }
1472 else if (! setlocale(LC_MESSAGES, save_input_locale)) {
5857e934
KW
1473 DEBUG_L(PerlIO_printf(Perl_debug_log,
1474 "Could not change LC_MESSAGES locale to %s\n",
1475 save_input_locale));
855aeb93
JH
1476 Safefree(save_messages_locale);
1477 goto cant_use_messages;
1478 }
1479 }
1480
1481 /* Here the current LC_MESSAGES is set to the locale of the category
5857e934
KW
1482 * whose information is desired. Look through all the messages. We
1483 * can't use Strerror() here because it may expand to code that
1484 * segfaults in miniperl */
855aeb93 1485
5857e934
KW
1486 for (e = 0; e <= sys_nerr; e++) {
1487 errno = 0;
1488 errmsg = sys_errlist[e];
1489 if (errno || !errmsg) {
855aeb93
JH
1490 break;
1491 }
5857e934 1492 errmsg = savepv(errmsg);
9f10db87 1493 if (! is_invariant_string((U8 *) errmsg, 0)) {
5857e934
KW
1494 non_ascii = TRUE;
1495 is_utf8 = is_utf8_string((U8 *) errmsg, 0);
1496 break;
855aeb93
JH
1497 }
1498 }
5857e934 1499 Safefree(errmsg);
855aeb93
JH
1500
1501 /* And, if we changed it, restore LC_MESSAGES to its original locale */
1502 if (save_messages_locale) {
1503 setlocale(LC_MESSAGES, save_messages_locale);
1504 Safefree(save_messages_locale);
1505 }
1506
5857e934
KW
1507 if (non_ascii) {
1508
1509 /* Any non-UTF-8 message means not a UTF-8 locale; if all are valid,
1510 * any non-ascii means it is one; otherwise we assume it isn't */
1511 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?error messages for %s are UTF-8=%d\n",
1512 save_input_locale,
1513 is_utf8));
1514 Safefree(save_input_locale);
1515 return is_utf8;
1516 }
855aeb93 1517
5857e934 1518 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
1519 }
1520 cant_use_messages:
1521
1522#endif
fa9b773e 1523
0080c90a
KW
1524#endif /* the code that is compiled when no nl_langinfo */
1525
92c0a900
KW
1526#ifndef EBCDIC /* On os390, even if the name ends with "UTF-8', it isn't a
1527 UTF-8 locale */
97f4de96
KW
1528 /* As a last resort, look at the locale name to see if it matches
1529 * qr/UTF -? * 8 /ix, or some other common locale names. This "name", the
1530 * return of setlocale(), is actually defined to be opaque, so we can't
1531 * really rely on the absence of various substrings in the name to indicate
1532 * its UTF-8ness, but if it has UTF8 in the name, it is extremely likely to
1533 * be a UTF-8 locale. Similarly for the other common names */
1534
1535 final_pos = strlen(save_input_locale) - 1;
1536 if (final_pos >= 3) {
1537 char *name = save_input_locale;
1538
1539 /* Find next 'U' or 'u' and look from there */
1540 while ((name += strcspn(name, "Uu") + 1)
1541 <= save_input_locale + final_pos - 2)
1542 {
305b8651
KW
1543 if (!isALPHA_FOLD_NE(*name, 't')
1544 || isALPHA_FOLD_NE(*(name + 1), 'f'))
97f4de96
KW
1545 {
1546 continue;
1547 }
1548 name += 2;
1549 if (*(name) == '-') {
1550 if ((name > save_input_locale + final_pos - 1)) {
1551 break;
1552 }
1553 name++;
1554 }
1555 if (*(name) == '8') {
97f4de96
KW
1556 DEBUG_L(PerlIO_printf(Perl_debug_log,
1557 "Locale %s ends with UTF-8 in name\n",
1558 save_input_locale));
00c54b9c 1559 Safefree(save_input_locale);
97f4de96
KW
1560 return TRUE;
1561 }
1562 }
1563 DEBUG_L(PerlIO_printf(Perl_debug_log,
1564 "Locale %s doesn't end with UTF-8 in name\n",
1565 save_input_locale));
1566 }
92c0a900 1567#endif
97f4de96
KW
1568
1569#ifdef WIN32
1570 /* http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756.aspx */
1571 if (final_pos >= 4
1572 && *(save_input_locale + final_pos - 0) == '1'
1573 && *(save_input_locale + final_pos - 1) == '0'
1574 && *(save_input_locale + final_pos - 2) == '0'
1575 && *(save_input_locale + final_pos - 3) == '5'
1576 && *(save_input_locale + final_pos - 4) == '6')
1577 {
1578 DEBUG_L(PerlIO_printf(Perl_debug_log,
1579 "Locale %s ends with 10056 in name, is UTF-8 locale\n",
1580 save_input_locale));
1581 Safefree(save_input_locale);
1582 return TRUE;
1583 }
1584#endif
1585
1586 /* Other common encodings are the ISO 8859 series, which aren't UTF-8. But
1587 * since we are about to return FALSE anyway, there is no point in doing
1588 * this extra work */
1589#if 0
1590 if (instr(save_input_locale, "8859")) {
1591 DEBUG_L(PerlIO_printf(Perl_debug_log,
1592 "Locale %s has 8859 in name, not UTF-8 locale\n",
1593 save_input_locale));
1594 Safefree(save_input_locale);
1595 return FALSE;
1596 }
1597#endif
1598
69014004
KW
1599 DEBUG_L(PerlIO_printf(Perl_debug_log,
1600 "Assuming locale %s is not a UTF-8 locale\n",
1601 save_input_locale));
fa9b773e 1602 Safefree(save_input_locale);
7d74bb61
KW
1603 return FALSE;
1604}
1605
8ef6e574 1606#endif
7d74bb61 1607
d6ded950
KW
1608
1609bool
1610Perl__is_in_locale_category(pTHX_ const bool compiling, const int category)
1611{
1a4f13e1 1612 dVAR;
d6ded950
KW
1613 /* Internal function which returns if we are in the scope of a pragma that
1614 * enables the locale category 'category'. 'compiling' should indicate if
1615 * this is during the compilation phase (TRUE) or not (FALSE). */
1616
1617 const COP * const cop = (compiling) ? &PL_compiling : PL_curcop;
1618
1619 SV *categories = cop_hints_fetch_pvs(cop, "locale", 0);
1620 if (! categories || categories == &PL_sv_placeholder) {
1621 return FALSE;
1622 }
1623
1624 /* The pseudo-category 'not_characters' is -1, so just add 1 to each to get
1625 * a valid unsigned */
1626 assert(category >= -1);
1627 return cBOOL(SvUV(categories) & (1U << (category + 1)));
1628}
1629
2c6ee1a7
KW
1630char *
1631Perl_my_strerror(pTHX_ const int errnum) {
1632
1633 /* Uses C locale for the error text unless within scope of 'use locale' for
1634 * LC_MESSAGES */
1635
1636#ifdef USE_LOCALE_MESSAGES
8ee4b769 1637 if (! IN_LC(LC_MESSAGES)) {
2c6ee1a7 1638 char * save_locale = setlocale(LC_MESSAGES, NULL);
a39edc4c 1639 if (! isNAME_C_OR_POSIX(save_locale)) {
2c6ee1a7
KW
1640 char *errstr;
1641
1642 /* The next setlocale likely will zap this, so create a copy */
1643 save_locale = savepv(save_locale);
1644
1645 setlocale(LC_MESSAGES, "C");
1646
1647 /* This points to the static space in Strerror, with all its
1648 * limitations */
1649 errstr = Strerror(errnum);
1650
1651 setlocale(LC_MESSAGES, save_locale);
1652 Safefree(save_locale);
1653 return errstr;
1654 }
1655 }
1656#endif
1657
1658 return Strerror(errnum);
1659}
1660
66610fdd 1661/*
747c467a
KW
1662
1663=head1 Locale-related functions and macros
1664
1665=for apidoc sync_locale
1666
1667Changing the program's locale should be avoided by XS code. Nevertheless,
1668certain non-Perl libraries called from XS, such as C<Gtk> do so. When this
1669happens, Perl needs to be told that the locale has changed. Use this function
1670to do so, before returning to Perl.
1671
1672=cut
1673*/
1674
1675void
1676Perl_sync_locale(pTHX)
1677{
1678
1679#ifdef USE_LOCALE_CTYPE
1680 new_ctype(setlocale(LC_CTYPE, NULL));
1681#endif /* USE_LOCALE_CTYPE */
1682
1683#ifdef USE_LOCALE_COLLATE
1684 new_collate(setlocale(LC_COLLATE, NULL));
1685#endif
1686
1687#ifdef USE_LOCALE_NUMERIC
1688 set_numeric_local(); /* Switch from "C" to underlying LC_NUMERIC */
1689 new_numeric(setlocale(LC_NUMERIC, NULL));
1690#endif /* USE_LOCALE_NUMERIC */
1691
1692}
1693
1694
1695
1696/*
66610fdd
RGS
1697 * Local variables:
1698 * c-indentation-style: bsd
1699 * c-basic-offset: 4
14d04a33 1700 * indent-tabs-mode: nil
66610fdd
RGS
1701 * End:
1702 *
14d04a33 1703 * ex: set ts=8 sts=4 sw=4 et:
37442d52 1704 */