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