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