This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
locale.c: Create extended internal Perl_langinfo()
[perl5.git] / locale.c
... / ...
CommitLineData
1/* locale.c
2 *
3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
4 * 2002, 2003, 2005, 2006, 2007, 2008 by Larry Wall and others
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/*
12 * A Elbereth Gilthoniel,
13 * silivren penna míriel
14 * o menel aglar elenath!
15 * Na-chaered palan-díriel
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"]
21 */
22
23/* utility functions for handling locale-specific stuff like what
24 * character represents the decimal point.
25 *
26 * All C programs have an underlying locale. Perl code generally doesn't pay
27 * any attention to it except within the scope of a 'use locale'. For most
28 * categories, it accomplishes this by just using different operations if it is
29 * in such scope than if not. However, various libc functions called by Perl
30 * are affected by the LC_NUMERIC category, so there are macros in perl.h that
31 * are used to toggle between the current locale and the C locale depending on
32 * the desired behavior of those functions at the moment. And, LC_MESSAGES is
33 * switched to the C locale for outputting the message unless within the scope
34 * of 'use locale'.
35 */
36
37#include "EXTERN.h"
38#define PERL_IN_LOCALE_C
39#include "perl_langinfo.h"
40#include "perl.h"
41
42#include "reentr.h"
43
44/* If the environment says to, we can output debugging information during
45 * initialization. This is done before option parsing, and before any thread
46 * creation, so can be a file-level static */
47#ifdef DEBUGGING
48# ifdef PERL_GLOBAL_STRUCT
49 /* no global syms allowed */
50# define debug_initialization 0
51# define DEBUG_INITIALIZATION_set(v)
52# else
53static bool debug_initialization = FALSE;
54# define DEBUG_INITIALIZATION_set(v) (debug_initialization = v)
55# endif
56#endif
57
58#ifdef USE_LOCALE
59
60/*
61 * Standardize the locale name from a string returned by 'setlocale', possibly
62 * modifying that string.
63 *
64 * The typical return value of setlocale() is either
65 * (1) "xx_YY" if the first argument of setlocale() is not LC_ALL
66 * (2) "xa_YY xb_YY ..." if the first argument of setlocale() is LC_ALL
67 * (the space-separated values represent the various sublocales,
68 * in some unspecified order). This is not handled by this function.
69 *
70 * In some platforms it has a form like "LC_SOMETHING=Lang_Country.866\n",
71 * which is harmful for further use of the string in setlocale(). This
72 * function removes the trailing new line and everything up through the '='
73 *
74 */
75STATIC char *
76S_stdize_locale(pTHX_ char *locs)
77{
78 const char * const s = strchr(locs, '=');
79 bool okay = TRUE;
80
81 PERL_ARGS_ASSERT_STDIZE_LOCALE;
82
83 if (s) {
84 const char * const t = strchr(s, '.');
85 okay = FALSE;
86 if (t) {
87 const char * const u = strchr(t, '\n');
88 if (u && (u[1] == 0)) {
89 const STRLEN len = u - s;
90 Move(s + 1, locs, len, char);
91 locs[len] = 0;
92 okay = TRUE;
93 }
94 }
95 }
96
97 if (!okay)
98 Perl_croak(aTHX_ "Can't fix broken locale name \"%s\"", locs);
99
100 return locs;
101}
102
103#endif
104
105STATIC void
106S_set_numeric_radix(pTHX)
107{
108
109#ifdef USE_LOCALE_NUMERIC
110# ifdef HAS_LOCALECONV
111 const struct lconv* const lc = localeconv();
112
113 if (lc && lc->decimal_point) {
114 if (lc->decimal_point[0] == '.' && lc->decimal_point[1] == 0) {
115 SvREFCNT_dec(PL_numeric_radix_sv);
116 PL_numeric_radix_sv = NULL;
117 }
118 else {
119 if (PL_numeric_radix_sv)
120 sv_setpv(PL_numeric_radix_sv, lc->decimal_point);
121 else
122 PL_numeric_radix_sv = newSVpv(lc->decimal_point, 0);
123 if (! is_utf8_invariant_string((U8 *) lc->decimal_point, 0)
124 && is_utf8_string((U8 *) lc->decimal_point, 0)
125 && _is_cur_LC_category_utf8(LC_NUMERIC))
126 {
127 SvUTF8_on(PL_numeric_radix_sv);
128 }
129 }
130 }
131 else
132 PL_numeric_radix_sv = NULL;
133
134# ifdef DEBUGGING
135
136 if (DEBUG_L_TEST || debug_initialization) {
137 PerlIO_printf(Perl_debug_log, "Locale radix is '%s', ?UTF-8=%d\n",
138 (PL_numeric_radix_sv)
139 ? SvPVX(PL_numeric_radix_sv)
140 : "NULL",
141 (PL_numeric_radix_sv)
142 ? cBOOL(SvUTF8(PL_numeric_radix_sv))
143 : 0);
144 }
145
146# endif
147# endif /* HAS_LOCALECONV */
148#endif /* USE_LOCALE_NUMERIC */
149
150}
151
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 */
162#define isNAME_C_OR_POSIX(name) \
163 ( (name) != NULL \
164 && (( *(name) == 'C' && (*(name + 1)) == '\0') \
165 || strEQ((name), "POSIX")))
166
167void
168Perl_new_numeric(pTHX_ const char *newnum)
169{
170
171#ifndef USE_LOCALE_NUMERIC
172
173 PERL_UNUSED_ARG(newnum);
174
175#else
176
177 /* Called after all libc setlocale() calls affecting LC_NUMERIC, to tell
178 * core Perl this and that 'newnum' is the name of the new locale.
179 * It installs this locale as the current underlying default.
180 *
181 * The default locale and the C locale can be toggled between by use of the
182 * set_numeric_local() and set_numeric_standard() functions, which should
183 * probably not be called directly, but only via macros like
184 * SET_NUMERIC_STANDARD() in perl.h.
185 *
186 * The toggling is necessary mainly so that a non-dot radix decimal point
187 * character can be output, while allowing internal calculations to use a
188 * dot.
189 *
190 * This sets several interpreter-level variables:
191 * PL_numeric_name The underlying locale's name: a copy of 'newnum'
192 * PL_numeric_local A boolean indicating if the toggled state is such
193 * that the current locale is the program's underlying
194 * locale
195 * PL_numeric_standard An int indicating if the toggled state is such
196 * that the current locale is the C locale. If non-zero,
197 * it is in C; if > 1, it means it may not be toggled away
198 * from C.
199 * Note that both of the last two variables can be true at the same time,
200 * if the underlying locale is C. (Toggling is a no-op under these
201 * circumstances.)
202 *
203 * Any code changing the locale (outside this file) should use
204 * POSIX::setlocale, which calls this function. Therefore this function
205 * should be called directly only from this file and from
206 * POSIX::setlocale() */
207
208 char *save_newnum;
209
210 if (! newnum) {
211 Safefree(PL_numeric_name);
212 PL_numeric_name = NULL;
213 PL_numeric_standard = TRUE;
214 PL_numeric_local = TRUE;
215 return;
216 }
217
218 save_newnum = stdize_locale(savepv(newnum));
219
220 PL_numeric_standard = isNAME_C_OR_POSIX(save_newnum);
221 PL_numeric_local = TRUE;
222
223 if (! PL_numeric_name || strNE(PL_numeric_name, save_newnum)) {
224 Safefree(PL_numeric_name);
225 PL_numeric_name = save_newnum;
226 }
227 else {
228 Safefree(save_newnum);
229 }
230
231 /* Keep LC_NUMERIC in the C locale. This is for XS modules, so they don't
232 * have to worry about the radix being a non-dot. (Core operations that
233 * need the underlying locale change to it temporarily). */
234 set_numeric_standard();
235
236#endif /* USE_LOCALE_NUMERIC */
237
238}
239
240void
241Perl_set_numeric_standard(pTHX)
242{
243
244#ifdef USE_LOCALE_NUMERIC
245
246 /* Toggle the LC_NUMERIC locale to C. Most code should use the macros like
247 * SET_NUMERIC_STANDARD() in perl.h instead of calling this directly. The
248 * macro avoids calling this routine if toggling isn't necessary according
249 * to our records (which could be wrong if some XS code has changed the
250 * locale behind our back) */
251
252 setlocale(LC_NUMERIC, "C");
253 PL_numeric_standard = TRUE;
254 PL_numeric_local = isNAME_C_OR_POSIX(PL_numeric_name);
255 set_numeric_radix();
256
257# ifdef DEBUGGING
258
259 if (DEBUG_L_TEST || debug_initialization) {
260 PerlIO_printf(Perl_debug_log,
261 "Underlying LC_NUMERIC locale now is C\n");
262 }
263
264# endif
265#endif /* USE_LOCALE_NUMERIC */
266
267}
268
269void
270Perl_set_numeric_local(pTHX)
271{
272
273#ifdef USE_LOCALE_NUMERIC
274
275 /* Toggle the LC_NUMERIC locale to the current underlying default. Most
276 * code should use the macros like SET_NUMERIC_UNDERLYING() in perl.h
277 * instead of calling this directly. The macro avoids calling this routine
278 * if toggling isn't necessary according to our records (which could be
279 * wrong if some XS code has changed the locale behind our back) */
280
281 setlocale(LC_NUMERIC, PL_numeric_name);
282 PL_numeric_standard = isNAME_C_OR_POSIX(PL_numeric_name);
283 PL_numeric_local = TRUE;
284 set_numeric_radix();
285
286# ifdef DEBUGGING
287
288 if (DEBUG_L_TEST || debug_initialization) {
289 PerlIO_printf(Perl_debug_log,
290 "Underlying LC_NUMERIC locale now is %s\n",
291 PL_numeric_name);
292 }
293
294# endif
295#endif /* USE_LOCALE_NUMERIC */
296
297}
298
299/*
300 * Set up for a new ctype locale.
301 */
302STATIC void
303S_new_ctype(pTHX_ const char *newctype)
304{
305
306#ifndef USE_LOCALE_CTYPE
307
308 PERL_ARGS_ASSERT_NEW_CTYPE;
309 PERL_UNUSED_ARG(newctype);
310 PERL_UNUSED_CONTEXT;
311
312#else
313
314 /* Called after all libc setlocale() calls affecting LC_CTYPE, to tell
315 * core Perl this and that 'newctype' is the name of the new locale.
316 *
317 * This function sets up the folding arrays for all 256 bytes, assuming
318 * that tofold() is tolc() since fold case is not a concept in POSIX,
319 *
320 * Any code changing the locale (outside this file) should use
321 * POSIX::setlocale, which calls this function. Therefore this function
322 * should be called directly only from this file and from
323 * POSIX::setlocale() */
324
325 dVAR;
326 UV i;
327
328 PERL_ARGS_ASSERT_NEW_CTYPE;
329
330 /* We will replace any bad locale warning with 1) nothing if the new one is
331 * ok; or 2) a new warning for the bad new locale */
332 if (PL_warn_locale) {
333 SvREFCNT_dec_NN(PL_warn_locale);
334 PL_warn_locale = NULL;
335 }
336
337 PL_in_utf8_CTYPE_locale = _is_cur_LC_category_utf8(LC_CTYPE);
338
339 /* A UTF-8 locale gets standard rules. But note that code still has to
340 * handle this specially because of the three problematic code points */
341 if (PL_in_utf8_CTYPE_locale) {
342 Copy(PL_fold_latin1, PL_fold_locale, 256, U8);
343 }
344 else {
345 /* Assume enough space for every character being bad. 4 spaces each
346 * for the 94 printable characters that are output like "'x' "; and 5
347 * spaces each for "'\\' ", "'\t' ", and "'\n' "; plus a terminating
348 * NUL */
349 char bad_chars_list[ (94 * 4) + (3 * 5) + 1 ];
350
351 /* Don't check for problems if we are suppressing the warnings */
352 bool check_for_problems = ckWARN_d(WARN_LOCALE)
353 || UNLIKELY(DEBUG_L_TEST);
354 bool multi_byte_locale = FALSE; /* Assume is a single-byte locale
355 to start */
356 unsigned int bad_count = 0; /* Count of bad characters */
357
358 for (i = 0; i < 256; i++) {
359 if (isUPPER_LC((U8) i))
360 PL_fold_locale[i] = (U8) toLOWER_LC((U8) i);
361 else if (isLOWER_LC((U8) i))
362 PL_fold_locale[i] = (U8) toUPPER_LC((U8) i);
363 else
364 PL_fold_locale[i] = (U8) i;
365
366 /* If checking for locale problems, see if the native ASCII-range
367 * printables plus \n and \t are in their expected categories in
368 * the new locale. If not, this could mean big trouble, upending
369 * Perl's and most programs' assumptions, like having a
370 * metacharacter with special meaning become a \w. Fortunately,
371 * it's very rare to find locales that aren't supersets of ASCII
372 * nowadays. It isn't a problem for most controls to be changed
373 * into something else; we check only \n and \t, though perhaps \r
374 * could be an issue as well. */
375 if ( check_for_problems
376 && (isGRAPH_A(i) || isBLANK_A(i) || i == '\n'))
377 {
378 if (( isALPHANUMERIC_A(i) && ! isALPHANUMERIC_LC(i))
379 || (isPUNCT_A(i) && ! isPUNCT_LC(i))
380 || (isBLANK_A(i) && ! isBLANK_LC(i))
381 || (i == '\n' && ! isCNTRL_LC(i)))
382 {
383 if (bad_count) { /* Separate multiple entries with a
384 blank */
385 bad_chars_list[bad_count++] = ' ';
386 }
387 bad_chars_list[bad_count++] = '\'';
388 if (isPRINT_A(i)) {
389 bad_chars_list[bad_count++] = (char) i;
390 }
391 else {
392 bad_chars_list[bad_count++] = '\\';
393 if (i == '\n') {
394 bad_chars_list[bad_count++] = 'n';
395 }
396 else {
397 assert(i == '\t');
398 bad_chars_list[bad_count++] = 't';
399 }
400 }
401 bad_chars_list[bad_count++] = '\'';
402 bad_chars_list[bad_count] = '\0';
403 }
404 }
405 }
406
407# ifdef MB_CUR_MAX
408
409 /* We only handle single-byte locales (outside of UTF-8 ones; so if
410 * this locale requires more than one byte, there are going to be
411 * problems. */
412 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
413 "%s:%d: check_for_problems=%d, MB_CUR_MAX=%d\n",
414 __FILE__, __LINE__, check_for_problems, (int) MB_CUR_MAX));
415
416 if (check_for_problems && MB_CUR_MAX > 1
417
418 /* Some platforms return MB_CUR_MAX > 1 for even the "C"
419 * locale. Just assume that the implementation for them (plus
420 * for POSIX) is correct and the > 1 value is spurious. (Since
421 * these are specially handled to never be considered UTF-8
422 * locales, as long as this is the only problem, everything
423 * should work fine */
424 && strNE(newctype, "C") && strNE(newctype, "POSIX"))
425 {
426 multi_byte_locale = TRUE;
427 }
428
429# endif
430
431 if (bad_count || multi_byte_locale) {
432 PL_warn_locale = Perl_newSVpvf(aTHX_
433 "Locale '%s' may not work well.%s%s%s\n",
434 newctype,
435 (multi_byte_locale)
436 ? " Some characters in it are not recognized by"
437 " Perl."
438 : "",
439 (bad_count)
440 ? "\nThe following characters (and maybe others)"
441 " may not have the same meaning as the Perl"
442 " program expects:\n"
443 : "",
444 (bad_count)
445 ? bad_chars_list
446 : ""
447 );
448 /* If we are actually in the scope of the locale or are debugging,
449 * output the message now. If not in that scope, we save the
450 * message to be output at the first operation using this locale,
451 * if that actually happens. Most programs don't use locales, so
452 * they are immune to bad ones. */
453 if (IN_LC(LC_CTYPE) || UNLIKELY(DEBUG_L_TEST)) {
454
455 /* We have to save 'newctype' because the setlocale() just
456 * below may destroy it. The next setlocale() further down
457 * should restore it properly so that the intermediate change
458 * here is transparent to this function's caller */
459 const char * const badlocale = savepv(newctype);
460
461 setlocale(LC_CTYPE, "C");
462
463 /* The '0' below suppresses a bogus gcc compiler warning */
464 Perl_warner(aTHX_ packWARN(WARN_LOCALE), SvPVX(PL_warn_locale), 0);
465
466 setlocale(LC_CTYPE, badlocale);
467 Safefree(badlocale);
468
469 if (IN_LC(LC_CTYPE)) {
470 SvREFCNT_dec_NN(PL_warn_locale);
471 PL_warn_locale = NULL;
472 }
473 }
474 }
475 }
476
477#endif /* USE_LOCALE_CTYPE */
478
479}
480
481void
482Perl__warn_problematic_locale()
483{
484
485#ifdef USE_LOCALE_CTYPE
486
487 dTHX;
488
489 /* Internal-to-core function that outputs the message in PL_warn_locale,
490 * and then NULLS it. Should be called only through the macro
491 * _CHECK_AND_WARN_PROBLEMATIC_LOCALE */
492
493 if (PL_warn_locale) {
494 /*GCC_DIAG_IGNORE(-Wformat-security); Didn't work */
495 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
496 SvPVX(PL_warn_locale),
497 0 /* dummy to avoid compiler warning */ );
498 /* GCC_DIAG_RESTORE; */
499 SvREFCNT_dec_NN(PL_warn_locale);
500 PL_warn_locale = NULL;
501 }
502
503#endif
504
505}
506
507STATIC void
508S_new_collate(pTHX_ const char *newcoll)
509{
510
511#ifndef USE_LOCALE_COLLATE
512
513 PERL_UNUSED_ARG(newcoll);
514 PERL_UNUSED_CONTEXT;
515
516#else
517
518 /* Called after all libc setlocale() calls affecting LC_COLLATE, to tell
519 * core Perl this and that 'newcoll' is the name of the new locale.
520 *
521 * The design of locale collation is that every locale change is given an
522 * index 'PL_collation_ix'. The first time a string particpates in an
523 * operation that requires collation while locale collation is active, it
524 * is given PERL_MAGIC_collxfrm magic (via sv_collxfrm_flags()). That
525 * magic includes the collation index, and the transformation of the string
526 * by strxfrm(), q.v. That transformation is used when doing comparisons,
527 * instead of the string itself. If a string changes, the magic is
528 * cleared. The next time the locale changes, the index is incremented,
529 * and so we know during a comparison that the transformation is not
530 * necessarily still valid, and so is recomputed. Note that if the locale
531 * changes enough times, the index could wrap (a U32), and it is possible
532 * that a transformation would improperly be considered valid, leading to
533 * an unlikely bug */
534
535 if (! newcoll) {
536 if (PL_collation_name) {
537 ++PL_collation_ix;
538 Safefree(PL_collation_name);
539 PL_collation_name = NULL;
540 }
541 PL_collation_standard = TRUE;
542 is_standard_collation:
543 PL_collxfrm_base = 0;
544 PL_collxfrm_mult = 2;
545 PL_in_utf8_COLLATE_locale = FALSE;
546 PL_strxfrm_NUL_replacement = '\0';
547 PL_strxfrm_max_cp = 0;
548 return;
549 }
550
551 /* If this is not the same locale as currently, set the new one up */
552 if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
553 ++PL_collation_ix;
554 Safefree(PL_collation_name);
555 PL_collation_name = stdize_locale(savepv(newcoll));
556 PL_collation_standard = isNAME_C_OR_POSIX(newcoll);
557 if (PL_collation_standard) {
558 goto is_standard_collation;
559 }
560
561 PL_in_utf8_COLLATE_locale = _is_cur_LC_category_utf8(LC_COLLATE);
562 PL_strxfrm_NUL_replacement = '\0';
563 PL_strxfrm_max_cp = 0;
564
565 /* A locale collation definition includes primary, secondary, tertiary,
566 * etc. weights for each character. To sort, the primary weights are
567 * used, and only if they compare equal, then the secondary weights are
568 * used, and only if they compare equal, then the tertiary, etc.
569 *
570 * strxfrm() works by taking the input string, say ABC, and creating an
571 * output transformed string consisting of first the primary weights,
572 * A¹B¹C¹ followed by the secondary ones, A²B²C²; and then the
573 * tertiary, etc, yielding A¹B¹C¹ A²B²C² A³B³C³ .... Some characters
574 * may not have weights at every level. In our example, let's say B
575 * doesn't have a tertiary weight, and A doesn't have a secondary
576 * weight. The constructed string is then going to be
577 * A¹B¹C¹ B²C² A³C³ ....
578 * This has the desired effect that strcmp() will look at the secondary
579 * or tertiary weights only if the strings compare equal at all higher
580 * priority weights. The spaces shown here, like in
581 * "A¹B¹C¹ A²B²C² "
582 * are not just for readability. In the general case, these must
583 * actually be bytes, which we will call here 'separator weights'; and
584 * they must be smaller than any other weight value, but since these
585 * are C strings, only the terminating one can be a NUL (some
586 * implementations may include a non-NUL separator weight just before
587 * the NUL). Implementations tend to reserve 01 for the separator
588 * weights. They are needed so that a shorter string's secondary
589 * weights won't be misconstrued as primary weights of a longer string,
590 * etc. By making them smaller than any other weight, the shorter
591 * string will sort first. (Actually, if all secondary weights are
592 * smaller than all primary ones, there is no need for a separator
593 * weight between those two levels, etc.)
594 *
595 * The length of the transformed string is roughly a linear function of
596 * the input string. It's not exactly linear because some characters
597 * don't have weights at all levels. When we call strxfrm() we have to
598 * allocate some memory to hold the transformed string. The
599 * calculations below try to find coefficients 'm' and 'b' for this
600 * locale so that m*x + b equals how much space we need, given the size
601 * of the input string in 'x'. If we calculate too small, we increase
602 * the size as needed, and call strxfrm() again, but it is better to
603 * get it right the first time to avoid wasted expensive string
604 * transformations. */
605
606 {
607 /* We use the string below to find how long the tranformation of it
608 * is. Almost all locales are supersets of ASCII, or at least the
609 * ASCII letters. We use all of them, half upper half lower,
610 * because if we used fewer, we might hit just the ones that are
611 * outliers in a particular locale. Most of the strings being
612 * collated will contain a preponderance of letters, and even if
613 * they are above-ASCII, they are likely to have the same number of
614 * weight levels as the ASCII ones. It turns out that digits tend
615 * to have fewer levels, and some punctuation has more, but those
616 * are relatively sparse in text, and khw believes this gives a
617 * reasonable result, but it could be changed if experience so
618 * dictates. */
619 const char longer[] = "ABCDEFGHIJKLMnopqrstuvwxyz";
620 char * x_longer; /* Transformed 'longer' */
621 Size_t x_len_longer; /* Length of 'x_longer' */
622
623 char * x_shorter; /* We also transform a substring of 'longer' */
624 Size_t x_len_shorter;
625
626 /* _mem_collxfrm() is used get the transformation (though here we
627 * are interested only in its length). It is used because it has
628 * the intelligence to handle all cases, but to work, it needs some
629 * values of 'm' and 'b' to get it started. For the purposes of
630 * this calculation we use a very conservative estimate of 'm' and
631 * 'b'. This assumes a weight can be multiple bytes, enough to
632 * hold any UV on the platform, and there are 5 levels, 4 weight
633 * bytes, and a trailing NUL. */
634 PL_collxfrm_base = 5;
635 PL_collxfrm_mult = 5 * sizeof(UV);
636
637 /* Find out how long the transformation really is */
638 x_longer = _mem_collxfrm(longer,
639 sizeof(longer) - 1,
640 &x_len_longer,
641
642 /* We avoid converting to UTF-8 in the
643 * called function by telling it the
644 * string is in UTF-8 if the locale is a
645 * UTF-8 one. Since the string passed
646 * here is invariant under UTF-8, we can
647 * claim it's UTF-8 even though it isn't.
648 * */
649 PL_in_utf8_COLLATE_locale);
650 Safefree(x_longer);
651
652 /* Find out how long the transformation of a substring of 'longer'
653 * is. Together the lengths of these transformations are
654 * sufficient to calculate 'm' and 'b'. The substring is all of
655 * 'longer' except the first character. This minimizes the chances
656 * of being swayed by outliers */
657 x_shorter = _mem_collxfrm(longer + 1,
658 sizeof(longer) - 2,
659 &x_len_shorter,
660 PL_in_utf8_COLLATE_locale);
661 Safefree(x_shorter);
662
663 /* If the results are nonsensical for this simple test, the whole
664 * locale definition is suspect. Mark it so that locale collation
665 * is not active at all for it. XXX Should we warn? */
666 if ( x_len_shorter == 0
667 || x_len_longer == 0
668 || x_len_shorter >= x_len_longer)
669 {
670 PL_collxfrm_mult = 0;
671 PL_collxfrm_base = 0;
672 }
673 else {
674 SSize_t base; /* Temporary */
675
676 /* We have both: m * strlen(longer) + b = x_len_longer
677 * m * strlen(shorter) + b = x_len_shorter;
678 * subtracting yields:
679 * m * (strlen(longer) - strlen(shorter))
680 * = x_len_longer - x_len_shorter
681 * But we have set things up so that 'shorter' is 1 byte smaller
682 * than 'longer'. Hence:
683 * m = x_len_longer - x_len_shorter
684 *
685 * But if something went wrong, make sure the multiplier is at
686 * least 1.
687 */
688 if (x_len_longer > x_len_shorter) {
689 PL_collxfrm_mult = (STRLEN) x_len_longer - x_len_shorter;
690 }
691 else {
692 PL_collxfrm_mult = 1;
693 }
694
695 /* mx + b = len
696 * so: b = len - mx
697 * but in case something has gone wrong, make sure it is
698 * non-negative */
699 base = x_len_longer - PL_collxfrm_mult * (sizeof(longer) - 1);
700 if (base < 0) {
701 base = 0;
702 }
703
704 /* Add 1 for the trailing NUL */
705 PL_collxfrm_base = base + 1;
706 }
707
708# ifdef DEBUGGING
709
710 if (DEBUG_L_TEST || debug_initialization) {
711 PerlIO_printf(Perl_debug_log,
712 "%s:%d: ?UTF-8 locale=%d; x_len_shorter=%zu, "
713 "x_len_longer=%zu,"
714 " collate multipler=%zu, collate base=%zu\n",
715 __FILE__, __LINE__,
716 PL_in_utf8_COLLATE_locale,
717 x_len_shorter, x_len_longer,
718 PL_collxfrm_mult, PL_collxfrm_base);
719 }
720# endif
721
722 }
723 }
724
725#endif /* USE_LOCALE_COLLATE */
726
727}
728
729#ifndef WIN32 /* No wrapper except on Windows */
730
731# define my_setlocale(a,b) setlocale(a,b)
732
733#else /* WIN32 */
734
735STATIC char *
736S_my_setlocale(pTHX_ int category, const char* locale)
737{
738 /* This, for Windows, emulates POSIX setlocale() behavior. There is no
739 * difference between the two unless the input locale is "", which normally
740 * means on Windows to get the machine default, which is set via the
741 * computer's "Regional and Language Options" (or its current equivalent).
742 * In POSIX, it instead means to find the locale from the user's
743 * environment. This routine changes the Windows behavior to first look in
744 * the environment, and, if anything is found, use that instead of going to
745 * the machine default. If there is no environment override, the machine
746 * default is used, by calling the real setlocale() with "".
747 *
748 * The POSIX behavior is to use the LC_ALL variable if set; otherwise to
749 * use the particular category's variable if set; otherwise to use the LANG
750 * variable. */
751
752 bool override_LC_ALL = FALSE;
753 char * result;
754
755 if (locale && strEQ(locale, "")) {
756
757# ifdef LC_ALL
758
759 locale = PerlEnv_getenv("LC_ALL");
760 if (! locale) {
761
762# endif
763 switch (category) {
764
765# ifdef LC_ALL
766 case LC_ALL:
767 override_LC_ALL = TRUE;
768 break; /* We already know its variable isn't set */
769
770# endif
771# ifdef USE_LOCALE_TIME
772
773 case LC_TIME:
774 locale = PerlEnv_getenv("LC_TIME");
775 break;
776
777# endif
778# ifdef USE_LOCALE_CTYPE
779
780 case LC_CTYPE:
781 locale = PerlEnv_getenv("LC_CTYPE");
782 break;
783
784# endif
785# ifdef USE_LOCALE_COLLATE
786
787 case LC_COLLATE:
788 locale = PerlEnv_getenv("LC_COLLATE");
789 break;
790
791# endif
792# ifdef USE_LOCALE_MONETARY
793
794 case LC_MONETARY:
795 locale = PerlEnv_getenv("LC_MONETARY");
796 break;
797
798# endif
799# ifdef USE_LOCALE_NUMERIC
800
801 case LC_NUMERIC:
802 locale = PerlEnv_getenv("LC_NUMERIC");
803 break;
804
805# endif
806# ifdef USE_LOCALE_MESSAGES
807
808 case LC_MESSAGES:
809 locale = PerlEnv_getenv("LC_MESSAGES");
810 break;
811
812# endif
813
814 default:
815 /* This is a category, like PAPER_SIZE that we don't
816 * know about; and so can't provide a wrapper. */
817 break;
818 }
819 if (! locale) {
820 locale = PerlEnv_getenv("LANG");
821 if (! locale) {
822 locale = "";
823 }
824 }
825
826# ifdef LC_ALL
827
828 }
829
830# endif
831
832 }
833
834 result = setlocale(category, locale);
835 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n", __FILE__, __LINE__,
836 setlocale_debug_string(category, locale, result)));
837
838 if (! override_LC_ALL) {
839 return result;
840 }
841
842 /* Here the input category was LC_ALL, and we have set it to what is in the
843 * LANG variable or the system default if there is no LANG. But these have
844 * lower priority than the other LC_foo variables, so override it for each
845 * one that is set. (If they are set to "", it means to use the same thing
846 * we just set LC_ALL to, so can skip) */
847
848# ifdef USE_LOCALE_TIME
849
850 result = PerlEnv_getenv("LC_TIME");
851 if (result && strNE(result, "")) {
852 setlocale(LC_TIME, result);
853 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
854 __FILE__, __LINE__,
855 setlocale_debug_string(LC_TIME, result, "not captured")));
856 }
857
858# endif
859# ifdef USE_LOCALE_CTYPE
860
861 result = PerlEnv_getenv("LC_CTYPE");
862 if (result && strNE(result, "")) {
863 setlocale(LC_CTYPE, result);
864 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
865 __FILE__, __LINE__,
866 setlocale_debug_string(LC_CTYPE, result, "not captured")));
867 }
868
869# endif
870# ifdef USE_LOCALE_COLLATE
871
872 result = PerlEnv_getenv("LC_COLLATE");
873 if (result && strNE(result, "")) {
874 setlocale(LC_COLLATE, result);
875 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
876 __FILE__, __LINE__,
877 setlocale_debug_string(LC_COLLATE, result, "not captured")));
878 }
879
880# endif
881# ifdef USE_LOCALE_MONETARY
882
883 result = PerlEnv_getenv("LC_MONETARY");
884 if (result && strNE(result, "")) {
885 setlocale(LC_MONETARY, result);
886 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
887 __FILE__, __LINE__,
888 setlocale_debug_string(LC_MONETARY, result, "not captured")));
889 }
890
891# endif
892# ifdef USE_LOCALE_NUMERIC
893
894 result = PerlEnv_getenv("LC_NUMERIC");
895 if (result && strNE(result, "")) {
896 setlocale(LC_NUMERIC, result);
897 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
898 __FILE__, __LINE__,
899 setlocale_debug_string(LC_NUMERIC, result, "not captured")));
900 }
901
902# endif
903# ifdef USE_LOCALE_MESSAGES
904
905 result = PerlEnv_getenv("LC_MESSAGES");
906 if (result && strNE(result, "")) {
907 setlocale(LC_MESSAGES, result);
908 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
909 __FILE__, __LINE__,
910 setlocale_debug_string(LC_MESSAGES, result, "not captured")));
911 }
912
913# endif
914
915 result = setlocale(LC_ALL, NULL);
916 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
917 __FILE__, __LINE__,
918 setlocale_debug_string(LC_ALL, NULL, result)));
919
920 return result;
921}
922
923#endif
924
925char *
926Perl_setlocale(int category, const char * locale)
927{
928 /* This wraps POSIX::setlocale() */
929
930 char * retval;
931 dTHX;
932
933#ifdef USE_LOCALE_NUMERIC
934
935 /* A NULL locale means only query what the current one is. We
936 * have the LC_NUMERIC name saved, because we are normally switched
937 * into the C locale for it. Switch back so an LC_ALL query will yield
938 * the correct results; all other categories don't require special
939 * handling */
940 if (locale == NULL) {
941 if (category == LC_NUMERIC) {
942 return savepv(PL_numeric_name);
943 }
944
945# ifdef LC_ALL
946
947 else if (category == LC_ALL) {
948 SET_NUMERIC_UNDERLYING();
949 }
950
951# endif
952
953 }
954
955#endif
956
957 retval = my_setlocale(category, locale);
958
959 DEBUG_L(PerlIO_printf(Perl_debug_log,
960 "%s:%d: %s\n", __FILE__, __LINE__,
961 setlocale_debug_string(category, locale, retval)));
962 if (! retval) {
963 /* Should never happen that a query would return an error, but be
964 * sure and reset to C locale */
965 if (locale == 0) {
966 SET_NUMERIC_STANDARD();
967 }
968
969 return NULL;
970 }
971
972 /* Save retval since subsequent setlocale() calls may overwrite it. */
973 retval = savepv(retval);
974
975 /* If locale == NULL, we are just querying the state, but may have switched
976 * to NUMERIC_UNDERLYING. Switch back before returning. */
977 if (locale == NULL) {
978 SET_NUMERIC_STANDARD();
979 return retval;
980 }
981 else { /* Now that have switched locales, we have to update our records to
982 correspond */
983
984#ifdef USE_LOCALE_CTYPE
985
986 if ( category == LC_CTYPE
987
988# ifdef LC_ALL
989
990 || category == LC_ALL
991
992# endif
993
994 )
995 {
996 char *newctype;
997
998# ifdef LC_ALL
999
1000 if (category == LC_ALL) {
1001 newctype = setlocale(LC_CTYPE, NULL);
1002 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
1003 "%s:%d: %s\n", __FILE__, __LINE__,
1004 setlocale_debug_string(LC_CTYPE, NULL, newctype)));
1005 }
1006 else
1007
1008# endif
1009
1010 newctype = retval;
1011 new_ctype(newctype);
1012 }
1013
1014#endif /* USE_LOCALE_CTYPE */
1015#ifdef USE_LOCALE_COLLATE
1016
1017 if ( category == LC_COLLATE
1018
1019# ifdef LC_ALL
1020
1021 || category == LC_ALL
1022
1023# endif
1024
1025 )
1026 {
1027 char *newcoll;
1028
1029# ifdef LC_ALL
1030
1031 if (category == LC_ALL) {
1032 newcoll = setlocale(LC_COLLATE, NULL);
1033 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
1034 "%s:%d: %s\n", __FILE__, __LINE__,
1035 setlocale_debug_string(LC_COLLATE, NULL, newcoll)));
1036 }
1037 else
1038
1039# endif
1040
1041 newcoll = retval;
1042 new_collate(newcoll);
1043 }
1044
1045#endif /* USE_LOCALE_COLLATE */
1046#ifdef USE_LOCALE_NUMERIC
1047
1048 if ( category == LC_NUMERIC
1049
1050# ifdef LC_ALL
1051
1052 || category == LC_ALL
1053
1054# endif
1055
1056 )
1057 {
1058 char *newnum;
1059
1060# ifdef LC_ALL
1061
1062 if (category == LC_ALL) {
1063 newnum = setlocale(LC_NUMERIC, NULL);
1064 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
1065 "%s:%d: %s\n", __FILE__, __LINE__,
1066 setlocale_debug_string(LC_NUMERIC, NULL, newnum)));
1067 }
1068 else
1069
1070# endif
1071
1072 newnum = retval;
1073 new_numeric(newnum);
1074 }
1075
1076#endif /* USE_LOCALE_NUMERIC */
1077
1078 }
1079
1080 return retval;
1081
1082
1083}
1084
1085PERL_STATIC_INLINE const char *
1086S_save_to_buffer(const char * string, char **buf, Size_t *buf_size, const Size_t offset)
1087{
1088 /* Copy the NUL-terminated 'string' to 'buf' + 'offset'. 'buf' has size 'buf_size',
1089 * growing it if necessary */
1090
1091 const Size_t string_size = strlen(string) + offset + 1;
1092
1093 PERL_ARGS_ASSERT_SAVE_TO_BUFFER;
1094
1095 if (*buf_size == 0) {
1096 Newx(*buf, string_size, char);
1097 *buf_size = string_size;
1098 }
1099 else if (string_size > *buf_size) {
1100 Renew(*buf, string_size, char);
1101 *buf_size = string_size;
1102 }
1103
1104 Copy(string, *buf + offset, string_size - offset, char);
1105 return *buf;
1106}
1107
1108/*
1109
1110=head1 Locale-related functions and macros
1111
1112=for apidoc Perl_langinfo
1113
1114This is an (almost ª) drop-in replacement for the system C<L<nl_langinfo(3)>>,
1115taking the same C<item> parameter values, and returning the same information.
1116But it is more thread-safe than regular C<nl_langinfo()>, and hides the quirks
1117of Perl's locale handling from your code, and can be used on systems that lack
1118a native C<nl_langinfo>.
1119
1120Expanding on these:
1121
1122=over
1123
1124=item *
1125
1126It delivers the correct results for the C<RADIXCHAR> and C<THOUSESEP> items,
1127without you having to write extra code. The reason for the extra code would be
1128because these are from the C<LC_NUMERIC> locale category, which is normally
1129kept set to the C locale by Perl, no matter what the underlying locale is
1130supposed to be, and so to get the expected results, you have to temporarily
1131toggle into the underlying locale, and later toggle back. (You could use
1132plain C<nl_langinfo> and C<L</STORE_LC_NUMERIC_FORCE_TO_UNDERLYING>> for this
1133but then you wouldn't get the other advantages of C<Perl_langinfo()>; not
1134keeping C<LC_NUMERIC> in the C locale would break a lot of CPAN, which is
1135expecting the radix (decimal point) character to be a dot.)
1136
1137=item *
1138
1139Depending on C<item>, it works on systems that don't have C<nl_langinfo>, hence
1140makes your code more portable. Of the fifty-some possible items specified by
1141the POSIX 2008 standard,
1142L<http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/langinfo.h.html>,
1143only two are completely unimplemented. It uses various techniques to recover
1144the other items, including calling C<L<localeconv(3)>>, and C<L<strftime(3)>>,
1145both of which are specified in C89, so should be always be available. Later
1146C<strftime()> versions have additional capabilities; C<""> is returned for
1147those not available on your system.
1148
1149The details for those items which may differ from what this emulation returns
1150and what a native C<nl_langinfo()> would return are:
1151
1152=over
1153
1154=item C<CODESET>
1155
1156=item C<ERA>
1157
1158Unimplemented, so returns C<"">.
1159
1160=item C<YESEXPR>
1161
1162=item C<NOEXPR>
1163
1164Only the values for English are returned. Earlier POSIX standards also
1165specified C<YESSTR> and C<NOSTR>, but these have been removed from POSIX 2008,
1166and aren't supported by C<Perl_langinfo>.
1167
1168=item C<D_FMT>
1169
1170Always evaluates to C<%x>, the locale's appropriate date representation.
1171
1172=item C<T_FMT>
1173
1174Always evaluates to C<%X>, the locale's appropriate time representation.
1175
1176=item C<D_T_FMT>
1177
1178Always evaluates to C<%c>, the locale's appropriate date and time
1179representation.
1180
1181=item C<CRNCYSTR>
1182
1183The return may be incorrect for those rare locales where the currency symbol
1184replaces the radix character.
1185Send email to L<mailto:perlbug@perl.org> if you have examples of it needing
1186to work differently.
1187
1188=item C<ALT_DIGITS>
1189
1190Currently this gives the same results as Linux does.
1191Send email to L<mailto:perlbug@perl.org> if you have examples of it needing
1192to work differently.
1193
1194=item C<ERA_D_FMT>
1195
1196=item C<ERA_T_FMT>
1197
1198=item C<ERA_D_T_FMT>
1199
1200=item C<T_FMT_AMPM>
1201
1202These are derived by using C<strftime()>, and not all versions of that function
1203know about them. C<""> is returned for these on such systems.
1204
1205=back
1206
1207When using C<Perl_langinfo> on systems that don't have a native
1208C<nl_langinfo()>, you must
1209
1210 #include "perl_langinfo.h"
1211
1212before the C<perl.h> C<#include>. You can replace your C<langinfo.h>
1213C<#include> with this one. (Doing it this way keeps out the symbols that plain
1214C<langinfo.h> imports into the namespace for code that doesn't need it.)
1215
1216You also should not use the bare C<langinfo.h> item names, but should preface
1217them with C<PERL_>, so use C<PERL_RADIXCHAR> instead of plain C<RADIXCHAR>.
1218The C<PERL_I<foo>> versions will also work for this function on systems that do
1219have a native C<nl_langinfo>.
1220
1221=item *
1222
1223It is thread-friendly, returning its result in a buffer that won't be
1224overwritten by another thread, so you don't have to code for that possibility.
1225The buffer can be overwritten by the next call to C<nl_langinfo> or
1226C<Perl_langinfo> in the same thread.
1227
1228=item *
1229
1230ª It returns S<C<const char *>>, whereas plain C<nl_langinfo()> returns S<C<char
1231*>>, but you are (only by documentation) forbidden to write into the buffer.
1232By declaring this C<const>, the compiler enforces this restriction. The extra
1233C<const> is why this isn't an unequivocal drop-in replacement for
1234C<nl_langinfo>.
1235
1236=back
1237
1238The original impetus for C<Perl_langinfo()> was so that code that needs to
1239find out the current currency symbol, floating point radix character, or digit
1240grouping separator can use, on all systems, the simpler and more
1241thread-friendly C<nl_langinfo> API instead of C<L<localeconv(3)>> which is a
1242pain to make thread-friendly. For other fields returned by C<localeconv>, it
1243is better to use the methods given in L<perlcall> to call
1244L<C<POSIX::localeconv()>|POSIX/localeconv>, which is thread-friendly.
1245
1246=cut
1247
1248*/
1249
1250const char *
1251#ifdef HAS_NL_LANGINFO
1252Perl_langinfo(const nl_item item)
1253#else
1254Perl_langinfo(const int item)
1255#endif
1256{
1257 return my_nl_langinfo(item, TRUE);
1258}
1259
1260const char *
1261#ifdef HAS_NL_LANGINFO
1262S_my_nl_langinfo(const nl_item item, bool toggle)
1263#else
1264S_my_nl_langinfo(const int item, bool toggle)
1265#endif
1266{
1267 dTHX;
1268
1269#if defined(HAS_NL_LANGINFO) /* nl_langinfo() is available. */
1270#if ! defined(HAS_POSIX_2008_LOCALE)
1271
1272 /* Here, use plain nl_langinfo(), switching to the underlying LC_NUMERIC
1273 * for those items dependent on it. This must be copied to a buffer before
1274 * switching back, as some systems destroy the buffer when setlocale() is
1275 * called */
1276
1277 LOCALE_LOCK;
1278
1279 if (toggle) {
1280 if (item == PERL_RADIXCHAR || item == PERL_THOUSEP) {
1281 setlocale(LC_NUMERIC, PL_numeric_name);
1282 }
1283 else {
1284 toggle = FALSE;
1285 }
1286 }
1287
1288 save_to_buffer(nl_langinfo(item), &PL_langinfo_buf, &PL_langinfo_bufsize, 0);
1289
1290 if (toggle) {
1291 setlocale(LC_NUMERIC, "C");
1292 }
1293
1294 LOCALE_UNLOCK;
1295
1296 return PL_langinfo_buf;
1297
1298# else /* Use nl_langinfo_l(), avoiding both a mutex and changing the locale */
1299
1300 bool do_free = FALSE;
1301 locale_t cur = uselocale((locale_t) 0);
1302
1303 if (cur == LC_GLOBAL_LOCALE) {
1304 cur = duplocale(LC_GLOBAL_LOCALE);
1305 do_free = TRUE;
1306 }
1307
1308 if ( toggle
1309 && (item == PERL_RADIXCHAR || item == PERL_THOUSEP))
1310 {
1311 cur = newlocale(LC_NUMERIC_MASK, PL_numeric_name, cur);
1312 do_free = TRUE;
1313 }
1314
1315 save_to_buffer(nl_langinfo_l(item, cur),
1316 &PL_langinfo_buf, &PL_langinfo_bufsize, 0);
1317 if (do_free) {
1318 freelocale(cur);
1319 }
1320
1321 return PL_langinfo_buf;
1322
1323# endif
1324#else /* Below, emulate nl_langinfo as best we can */
1325# ifdef HAS_LOCALECONV
1326
1327 const struct lconv* lc;
1328
1329# endif
1330# ifdef HAS_STRFTIME
1331
1332 struct tm tm;
1333 bool return_format = FALSE; /* Return the %format, not the value */
1334 const char * format;
1335
1336# endif
1337
1338 /* We copy the results to a per-thread buffer, even if not multi-threaded.
1339 * This is in part to simplify this code, and partly because we need a
1340 * buffer anyway for strftime(), and partly because a call of localeconv()
1341 * could otherwise wipe out the buffer, and the programmer would not be
1342 * expecting this, as this is a nl_langinfo() substitute after all, so s/he
1343 * might be thinking their localeconv() is safe until another localeconv()
1344 * call. */
1345
1346 switch (item) {
1347 Size_t len;
1348 const char * retval;
1349
1350 /* These 2 are unimplemented */
1351 case PERL_CODESET:
1352 case PERL_ERA: /* For use with strftime() %E modifier */
1353
1354 default:
1355 return "";
1356
1357 /* We use only an English set, since we don't know any more */
1358 case PERL_YESEXPR: return "^[+1yY]";
1359 case PERL_NOEXPR: return "^[-0nN]";
1360
1361# ifdef HAS_LOCALECONV
1362
1363 case PERL_CRNCYSTR:
1364
1365 LOCALE_LOCK;
1366
1367 lc = localeconv();
1368 if (! lc || ! lc->currency_symbol || strEQ("", lc->currency_symbol))
1369 {
1370 LOCALE_UNLOCK;
1371 return "";
1372 }
1373
1374 /* Leave the first spot empty to be filled in below */
1375 save_to_buffer(lc->currency_symbol, &PL_langinfo_buf,
1376 &PL_langinfo_bufsize, 1);
1377 if (lc->mon_decimal_point && strEQ(lc->mon_decimal_point, ""))
1378 { /* khw couldn't figure out how the localedef specifications
1379 would show that the $ should replace the radix; this is
1380 just a guess as to how it might work.*/
1381 *PL_langinfo_buf = '.';
1382 }
1383 else if (lc->p_cs_precedes) {
1384 *PL_langinfo_buf = '-';
1385 }
1386 else {
1387 *PL_langinfo_buf = '+';
1388 }
1389
1390 LOCALE_UNLOCK;
1391 break;
1392
1393 case PERL_RADIXCHAR:
1394 case PERL_THOUSEP:
1395
1396 LOCALE_LOCK;
1397
1398 if (toggle) {
1399 setlocale(LC_NUMERIC, PL_numeric_name);
1400 }
1401
1402 lc = localeconv();
1403 if (! lc) {
1404 retval = "";
1405 }
1406 else switch (item) {
1407 case PERL_RADIXCHAR:
1408 if (! lc->decimal_point) {
1409 retval = "";
1410 }
1411 else {
1412 retval = lc->decimal_point;
1413 }
1414 break;
1415
1416 case PERL_THOUSEP:
1417 if (! lc->thousands_sep || strEQ("", lc->thousands_sep)) {
1418 retval = "";
1419 }
1420 else {
1421 retval = lc->thousands_sep;
1422 }
1423 break;
1424
1425 default:
1426 LOCALE_UNLOCK;
1427 Perl_croak(aTHX_ "panic: %s: %d: switch case: %d problem",
1428 __FILE__, __LINE__, item);
1429 }
1430
1431 save_to_buffer(retval, &PL_langinfo_buf, &PL_langinfo_bufsize, 0);
1432
1433 if (toggle) {
1434 setlocale(LC_NUMERIC, "C");
1435 }
1436
1437 LOCALE_UNLOCK;
1438
1439 break;
1440
1441# endif
1442# ifdef HAS_STRFTIME
1443
1444 /* These are defined by C89, so we assume that strftime supports them,
1445 * and so are returned unconditionally; they may not be what the locale
1446 * actually says, but should give good enough results for someone using
1447 * them as formats (as opposed to trying to parse them to figure out
1448 * what the locale says). The other format items are actually tested to
1449 * verify they work on the platform */
1450 case PERL_D_FMT: return "%x";
1451 case PERL_T_FMT: return "%X";
1452 case PERL_D_T_FMT: return "%c";
1453
1454 /* These formats are only available in later strfmtime's */
1455 case PERL_ERA_D_FMT: case PERL_ERA_T_FMT: case PERL_ERA_D_T_FMT:
1456 case PERL_T_FMT_AMPM:
1457
1458 /* The rest can be gotten from most versions of strftime(). */
1459 case PERL_ABDAY_1: case PERL_ABDAY_2: case PERL_ABDAY_3:
1460 case PERL_ABDAY_4: case PERL_ABDAY_5: case PERL_ABDAY_6:
1461 case PERL_ABDAY_7:
1462 case PERL_ALT_DIGITS:
1463 case PERL_AM_STR: case PERL_PM_STR:
1464 case PERL_ABMON_1: case PERL_ABMON_2: case PERL_ABMON_3:
1465 case PERL_ABMON_4: case PERL_ABMON_5: case PERL_ABMON_6:
1466 case PERL_ABMON_7: case PERL_ABMON_8: case PERL_ABMON_9:
1467 case PERL_ABMON_10: case PERL_ABMON_11: case PERL_ABMON_12:
1468 case PERL_DAY_1: case PERL_DAY_2: case PERL_DAY_3: case PERL_DAY_4:
1469 case PERL_DAY_5: case PERL_DAY_6: case PERL_DAY_7:
1470 case PERL_MON_1: case PERL_MON_2: case PERL_MON_3: case PERL_MON_4:
1471 case PERL_MON_5: case PERL_MON_6: case PERL_MON_7: case PERL_MON_8:
1472 case PERL_MON_9: case PERL_MON_10: case PERL_MON_11: case PERL_MON_12:
1473
1474 LOCALE_LOCK;
1475
1476 init_tm(&tm); /* Precaution against core dumps */
1477 tm.tm_sec = 30;
1478 tm.tm_min = 30;
1479 tm.tm_hour = 6;
1480 tm.tm_year = 2017 - 1900;
1481 tm.tm_wday = 0;
1482 tm.tm_mon = 0;
1483 switch (item) {
1484 default:
1485 LOCALE_UNLOCK;
1486 Perl_croak(aTHX_ "panic: %s: %d: switch case: %d problem",
1487 __FILE__, __LINE__, item);
1488 NOT_REACHED; /* NOTREACHED */
1489
1490 case PERL_PM_STR: tm.tm_hour = 18;
1491 case PERL_AM_STR:
1492 format = "%p";
1493 break;
1494
1495 case PERL_ABDAY_7: tm.tm_wday++;
1496 case PERL_ABDAY_6: tm.tm_wday++;
1497 case PERL_ABDAY_5: tm.tm_wday++;
1498 case PERL_ABDAY_4: tm.tm_wday++;
1499 case PERL_ABDAY_3: tm.tm_wday++;
1500 case PERL_ABDAY_2: tm.tm_wday++;
1501 case PERL_ABDAY_1:
1502 format = "%a";
1503 break;
1504
1505 case PERL_DAY_7: tm.tm_wday++;
1506 case PERL_DAY_6: tm.tm_wday++;
1507 case PERL_DAY_5: tm.tm_wday++;
1508 case PERL_DAY_4: tm.tm_wday++;
1509 case PERL_DAY_3: tm.tm_wday++;
1510 case PERL_DAY_2: tm.tm_wday++;
1511 case PERL_DAY_1:
1512 format = "%A";
1513 break;
1514
1515 case PERL_ABMON_12: tm.tm_mon++;
1516 case PERL_ABMON_11: tm.tm_mon++;
1517 case PERL_ABMON_10: tm.tm_mon++;
1518 case PERL_ABMON_9: tm.tm_mon++;
1519 case PERL_ABMON_8: tm.tm_mon++;
1520 case PERL_ABMON_7: tm.tm_mon++;
1521 case PERL_ABMON_6: tm.tm_mon++;
1522 case PERL_ABMON_5: tm.tm_mon++;
1523 case PERL_ABMON_4: tm.tm_mon++;
1524 case PERL_ABMON_3: tm.tm_mon++;
1525 case PERL_ABMON_2: tm.tm_mon++;
1526 case PERL_ABMON_1:
1527 format = "%b";
1528 break;
1529
1530 case PERL_MON_12: tm.tm_mon++;
1531 case PERL_MON_11: tm.tm_mon++;
1532 case PERL_MON_10: tm.tm_mon++;
1533 case PERL_MON_9: tm.tm_mon++;
1534 case PERL_MON_8: tm.tm_mon++;
1535 case PERL_MON_7: tm.tm_mon++;
1536 case PERL_MON_6: tm.tm_mon++;
1537 case PERL_MON_5: tm.tm_mon++;
1538 case PERL_MON_4: tm.tm_mon++;
1539 case PERL_MON_3: tm.tm_mon++;
1540 case PERL_MON_2: tm.tm_mon++;
1541 case PERL_MON_1:
1542 format = "%B";
1543 break;
1544
1545 case PERL_T_FMT_AMPM:
1546 format = "%r";
1547 return_format = TRUE;
1548 break;
1549
1550 case PERL_ERA_D_FMT:
1551 format = "%Ex";
1552 return_format = TRUE;
1553 break;
1554
1555 case PERL_ERA_T_FMT:
1556 format = "%EX";
1557 return_format = TRUE;
1558 break;
1559
1560 case PERL_ERA_D_T_FMT:
1561 format = "%Ec";
1562 return_format = TRUE;
1563 break;
1564
1565 case PERL_ALT_DIGITS:
1566 tm.tm_wday = 0;
1567 format = "%Ow"; /* Find the alternate digit for 0 */
1568 break;
1569 }
1570
1571 /* We can't use my_strftime() because it doesn't look at tm_wday */
1572 while (0 == strftime(PL_langinfo_buf, PL_langinfo_bufsize,
1573 format, &tm))
1574 {
1575 /* A zero return means one of:
1576 * a) there wasn't enough space in PL_langinfo_buf
1577 * b) the format, like a plain %p, returns empty
1578 * c) it was an illegal format, though some implementations of
1579 * strftime will just return the illegal format as a plain
1580 * character sequence.
1581 *
1582 * To quickly test for case 'b)', try again but precede the
1583 * format with a plain character. If that result is still
1584 * empty, the problem is either 'a)' or 'c)' */
1585
1586 Size_t format_size = strlen(format) + 1;
1587 Size_t mod_size = format_size + 1;
1588 char * mod_format;
1589 char * temp_result;
1590
1591 Newx(mod_format, mod_size, char);
1592 Newx(temp_result, PL_langinfo_bufsize, char);
1593 *mod_format = '\a';
1594 my_strlcpy(mod_format + 1, format, mod_size);
1595 len = strftime(temp_result,
1596 PL_langinfo_bufsize,
1597 mod_format, &tm);
1598 Safefree(mod_format);
1599 Safefree(temp_result);
1600
1601 /* If 'len' is non-zero, it means that we had a case like %p
1602 * which means the current locale doesn't use a.m. or p.m., and
1603 * that is valid */
1604 if (len == 0) {
1605
1606 /* Here, still didn't work. If we get well beyond a
1607 * reasonable size, bail out to prevent an infinite loop. */
1608
1609 if (PL_langinfo_bufsize > 100 * format_size) {
1610 *PL_langinfo_buf = '\0';
1611 }
1612 else { /* Double the buffer size to retry; Add 1 in case
1613 original was 0, so we aren't stuck at 0. */
1614 PL_langinfo_bufsize *= 2;
1615 PL_langinfo_bufsize++;
1616 Renew(PL_langinfo_buf, PL_langinfo_bufsize, char);
1617 continue;
1618 }
1619 }
1620
1621 break;
1622 }
1623
1624 /* Here, we got a result.
1625 *
1626 * If the item is 'ALT_DIGITS', PL_langinfo_buf contains the
1627 * alternate format for wday 0. If the value is the same as the
1628 * normal 0, there isn't an alternate, so clear the buffer. */
1629 if ( item == PERL_ALT_DIGITS
1630 && strEQ(PL_langinfo_buf, "0"))
1631 {
1632 *PL_langinfo_buf = '\0';
1633 }
1634
1635 /* ALT_DIGITS is problematic. Experiments on it showed that
1636 * strftime() did not always work properly when going from alt-9 to
1637 * alt-10. Only a few locales have this item defined, and in all
1638 * of them on Linux that khw was able to find, nl_langinfo() merely
1639 * returned the alt-0 character, possibly doubled. Most Unicode
1640 * digits are in blocks of 10 consecutive code points, so that is
1641 * sufficient information for those scripts, as we can infer alt-1,
1642 * alt-2, .... But for a Japanese locale, a CJK ideographic 0 is
1643 * returned, and the CJK digits are not in code point order, so you
1644 * can't really infer anything. The localedef for this locale did
1645 * specify the succeeding digits, so that strftime() works properly
1646 * on them, without needing to infer anything. But the
1647 * nl_langinfo() return did not give sufficient information for the
1648 * caller to understand what's going on. So until there is
1649 * evidence that it should work differently, this returns the alt-0
1650 * string for ALT_DIGITS.
1651 *
1652 * wday was chosen because its range is all a single digit. Things
1653 * like tm_sec have two digits as the minimum: '00' */
1654
1655 LOCALE_UNLOCK;
1656
1657 /* If to return the format, not the value, overwrite the buffer
1658 * with it. But some strftime()s will keep the original format if
1659 * illegal, so change those to "" */
1660 if (return_format) {
1661 if (strEQ(PL_langinfo_buf, format)) {
1662 *PL_langinfo_buf = '\0';
1663 }
1664 else {
1665 save_to_buffer(format, &PL_langinfo_buf,
1666 &PL_langinfo_bufsize, 0);
1667 }
1668 }
1669
1670 break;
1671
1672# endif
1673
1674 }
1675
1676 return PL_langinfo_buf;
1677
1678#endif
1679
1680}
1681
1682/*
1683 * Initialize locale awareness.
1684 */
1685int
1686Perl_init_i18nl10n(pTHX_ int printwarn)
1687{
1688 /* printwarn is
1689 *
1690 * 0 if not to output warning when setup locale is bad
1691 * 1 if to output warning based on value of PERL_BADLANG
1692 * >1 if to output regardless of PERL_BADLANG
1693 *
1694 * returns
1695 * 1 = set ok or not applicable,
1696 * 0 = fallback to a locale of lower priority
1697 * -1 = fallback to all locales failed, not even to the C locale
1698 *
1699 * Under -DDEBUGGING, if the environment variable PERL_DEBUG_LOCALE_INIT is
1700 * set, debugging information is output.
1701 *
1702 * This looks more complicated than it is, mainly due to the #ifdefs.
1703 *
1704 * We try to set LC_ALL to the value determined by the environment. If
1705 * there is no LC_ALL on this platform, we try the individual categories we
1706 * know about. If this works, we are done.
1707 *
1708 * But if it doesn't work, we have to do something else. We search the
1709 * environment variables ourselves instead of relying on the system to do
1710 * it. We look at, in order, LC_ALL, LANG, a system default locale (if we
1711 * think there is one), and the ultimate fallback "C". This is all done in
1712 * the same loop as above to avoid duplicating code, but it makes things
1713 * more complex. The 'trial_locales' array is initialized with just one
1714 * element; it causes the behavior described in the paragraph above this to
1715 * happen. If that fails, we add elements to 'trial_locales', and do extra
1716 * loop iterations to cause the behavior described in this paragraph.
1717 *
1718 * On Ultrix, the locale MUST come from the environment, so there is
1719 * preliminary code to set it. I (khw) am not sure that it is necessary,
1720 * and that this couldn't be folded into the loop, but barring any real
1721 * platforms to test on, it's staying as-is
1722 *
1723 * A slight complication is that in embedded Perls, the locale may already
1724 * be set-up, and we don't want to get it from the normal environment
1725 * variables. This is handled by having a special environment variable
1726 * indicate we're in this situation. We simply set setlocale's 2nd
1727 * parameter to be a NULL instead of "". That indicates to setlocale that
1728 * it is not to change anything, but to return the current value,
1729 * effectively initializing perl's db to what the locale already is.
1730 *
1731 * We play the same trick with NULL if a LC_ALL succeeds. We call
1732 * setlocale() on the individual categores with NULL to get their existing
1733 * values for our db, instead of trying to change them.
1734 * */
1735
1736 int ok = 1;
1737
1738#ifndef USE_LOCALE
1739
1740 PERL_UNUSED_ARG(printwarn);
1741
1742#else /* USE_LOCALE */
1743# ifdef USE_LOCALE_CTYPE
1744
1745 char *curctype = NULL;
1746
1747# endif /* USE_LOCALE_CTYPE */
1748# ifdef USE_LOCALE_COLLATE
1749
1750 char *curcoll = NULL;
1751
1752# endif /* USE_LOCALE_COLLATE */
1753# ifdef USE_LOCALE_NUMERIC
1754
1755 char *curnum = NULL;
1756
1757# endif /* USE_LOCALE_NUMERIC */
1758# ifdef __GLIBC__
1759
1760 const char * const language = savepv(PerlEnv_getenv("LANGUAGE"));
1761
1762# endif
1763
1764 /* NULL uses the existing already set up locale */
1765 const char * const setlocale_init = (PerlEnv_getenv("PERL_SKIP_LOCALE_INIT"))
1766 ? NULL
1767 : "";
1768 const char* trial_locales[5]; /* 5 = 1 each for "", LC_ALL, LANG, "", C */
1769 unsigned int trial_locales_count;
1770 const char * const lc_all = savepv(PerlEnv_getenv("LC_ALL"));
1771 const char * const lang = savepv(PerlEnv_getenv("LANG"));
1772 bool setlocale_failure = FALSE;
1773 unsigned int i;
1774
1775 /* A later getenv() could zap this, so only use here */
1776 const char * const bad_lang_use_once = PerlEnv_getenv("PERL_BADLANG");
1777
1778 const bool locwarn = (printwarn > 1
1779 || (printwarn
1780 && (! bad_lang_use_once
1781 || (
1782 /* disallow with "" or "0" */
1783 *bad_lang_use_once
1784 && strNE("0", bad_lang_use_once)))));
1785 bool done = FALSE;
1786 char * sl_result; /* return from setlocale() */
1787 char * locale_param;
1788
1789# ifdef WIN32
1790
1791 /* In some systems you can find out the system default locale
1792 * and use that as the fallback locale. */
1793# define SYSTEM_DEFAULT_LOCALE
1794# endif
1795# ifdef SYSTEM_DEFAULT_LOCALE
1796
1797 const char *system_default_locale = NULL;
1798
1799# endif
1800# ifdef DEBUGGING
1801
1802 DEBUG_INITIALIZATION_set(cBOOL(PerlEnv_getenv("PERL_DEBUG_LOCALE_INIT")));
1803
1804# define DEBUG_LOCALE_INIT(category, locale, result) \
1805 STMT_START { \
1806 if (debug_initialization) { \
1807 PerlIO_printf(Perl_debug_log, \
1808 "%s:%d: %s\n", \
1809 __FILE__, __LINE__, \
1810 setlocale_debug_string(category, \
1811 locale, \
1812 result)); \
1813 } \
1814 } STMT_END
1815
1816# else
1817# define DEBUG_LOCALE_INIT(a,b,c)
1818# endif
1819
1820# ifndef LOCALE_ENVIRON_REQUIRED
1821
1822 PERL_UNUSED_VAR(done);
1823 PERL_UNUSED_VAR(locale_param);
1824
1825# else
1826
1827 /*
1828 * Ultrix setlocale(..., "") fails if there are no environment
1829 * variables from which to get a locale name.
1830 */
1831
1832# ifdef LC_ALL
1833
1834 if (lang) {
1835 sl_result = my_setlocale(LC_ALL, setlocale_init);
1836 DEBUG_LOCALE_INIT(LC_ALL, setlocale_init, sl_result);
1837 if (sl_result)
1838 done = TRUE;
1839 else
1840 setlocale_failure = TRUE;
1841 }
1842 if (! setlocale_failure) {
1843
1844# ifdef USE_LOCALE_CTYPE
1845
1846 locale_param = (! done && (lang || PerlEnv_getenv("LC_CTYPE")))
1847 ? setlocale_init
1848 : NULL;
1849 curctype = my_setlocale(LC_CTYPE, locale_param);
1850 DEBUG_LOCALE_INIT(LC_CTYPE, locale_param, sl_result);
1851 if (! curctype)
1852 setlocale_failure = TRUE;
1853 else
1854 curctype = savepv(curctype);
1855
1856# endif /* USE_LOCALE_CTYPE */
1857# ifdef USE_LOCALE_COLLATE
1858
1859 locale_param = (! done && (lang || PerlEnv_getenv("LC_COLLATE")))
1860 ? setlocale_init
1861 : NULL;
1862 curcoll = my_setlocale(LC_COLLATE, locale_param);
1863 DEBUG_LOCALE_INIT(LC_COLLATE, locale_param, sl_result);
1864 if (! curcoll)
1865 setlocale_failure = TRUE;
1866 else
1867 curcoll = savepv(curcoll);
1868
1869# endif /* USE_LOCALE_COLLATE */
1870# ifdef USE_LOCALE_NUMERIC
1871
1872 locale_param = (! done && (lang || PerlEnv_getenv("LC_NUMERIC")))
1873 ? setlocale_init
1874 : NULL;
1875 curnum = my_setlocale(LC_NUMERIC, locale_param);
1876 DEBUG_LOCALE_INIT(LC_NUMERIC, locale_param, sl_result);
1877 if (! curnum)
1878 setlocale_failure = TRUE;
1879 else
1880 curnum = savepv(curnum);
1881
1882# endif /* USE_LOCALE_NUMERIC */
1883# ifdef USE_LOCALE_MESSAGES
1884
1885 locale_param = (! done && (lang || PerlEnv_getenv("LC_MESSAGES")))
1886 ? setlocale_init
1887 : NULL;
1888 sl_result = my_setlocale(LC_MESSAGES, locale_param);
1889 DEBUG_LOCALE_INIT(LC_MESSAGES, locale_param, sl_result);
1890 if (! sl_result) {
1891 setlocale_failure = TRUE;
1892 }
1893
1894# endif /* USE_LOCALE_MESSAGES */
1895# ifdef USE_LOCALE_MONETARY
1896
1897 locale_param = (! done && (lang || PerlEnv_getenv("LC_MONETARY")))
1898 ? setlocale_init
1899 : NULL;
1900 sl_result = my_setlocale(LC_MONETARY, locale_param);
1901 DEBUG_LOCALE_INIT(LC_MONETARY, locale_param, sl_result);
1902 if (! sl_result) {
1903 setlocale_failure = TRUE;
1904 }
1905
1906# endif /* USE_LOCALE_MONETARY */
1907
1908 }
1909
1910# endif /* LC_ALL */
1911# endif /* !LOCALE_ENVIRON_REQUIRED */
1912
1913 /* We try each locale in the list until we get one that works, or exhaust
1914 * the list. Normally the loop is executed just once. But if setting the
1915 * locale fails, inside the loop we add fallback trials to the array and so
1916 * will execute the loop multiple times */
1917 trial_locales[0] = setlocale_init;
1918 trial_locales_count = 1;
1919
1920 for (i= 0; i < trial_locales_count; i++) {
1921 const char * trial_locale = trial_locales[i];
1922
1923 if (i > 0) {
1924
1925 /* XXX This is to preserve old behavior for LOCALE_ENVIRON_REQUIRED
1926 * when i==0, but I (khw) don't think that behavior makes much
1927 * sense */
1928 setlocale_failure = FALSE;
1929
1930# ifdef SYSTEM_DEFAULT_LOCALE
1931# ifdef WIN32
1932
1933 /* On Windows machines, an entry of "" after the 0th means to use
1934 * the system default locale, which we now proceed to get. */
1935 if (strEQ(trial_locale, "")) {
1936 unsigned int j;
1937
1938 /* Note that this may change the locale, but we are going to do
1939 * that anyway just below */
1940 system_default_locale = setlocale(LC_ALL, "");
1941 DEBUG_LOCALE_INIT(LC_ALL, "", system_default_locale);
1942
1943 /* Skip if invalid or if it's already on the list of locales to
1944 * try */
1945 if (! system_default_locale) {
1946 goto next_iteration;
1947 }
1948 for (j = 0; j < trial_locales_count; j++) {
1949 if (strEQ(system_default_locale, trial_locales[j])) {
1950 goto next_iteration;
1951 }
1952 }
1953
1954 trial_locale = system_default_locale;
1955 }
1956# endif /* WIN32 */
1957# endif /* SYSTEM_DEFAULT_LOCALE */
1958 }
1959
1960# ifdef LC_ALL
1961
1962 sl_result = my_setlocale(LC_ALL, trial_locale);
1963 DEBUG_LOCALE_INIT(LC_ALL, trial_locale, sl_result);
1964 if (! sl_result) {
1965 setlocale_failure = TRUE;
1966 }
1967 else {
1968 /* Since LC_ALL succeeded, it should have changed all the other
1969 * categories it can to its value; so we massage things so that the
1970 * setlocales below just return their category's current values.
1971 * This adequately handles the case in NetBSD where LC_COLLATE may
1972 * not be defined for a locale, and setting it individually will
1973 * fail, whereas setting LC_ALL succeeds, leaving LC_COLLATE set to
1974 * the POSIX locale. */
1975 trial_locale = NULL;
1976 }
1977
1978# endif /* LC_ALL */
1979
1980 if (!setlocale_failure) {
1981
1982# ifdef USE_LOCALE_CTYPE
1983
1984 Safefree(curctype);
1985 curctype = my_setlocale(LC_CTYPE, trial_locale);
1986 DEBUG_LOCALE_INIT(LC_CTYPE, trial_locale, curctype);
1987 if (! curctype)
1988 setlocale_failure = TRUE;
1989 else
1990 curctype = savepv(curctype);
1991
1992# endif /* USE_LOCALE_CTYPE */
1993# ifdef USE_LOCALE_COLLATE
1994
1995 Safefree(curcoll);
1996 curcoll = my_setlocale(LC_COLLATE, trial_locale);
1997 DEBUG_LOCALE_INIT(LC_COLLATE, trial_locale, curcoll);
1998 if (! curcoll)
1999 setlocale_failure = TRUE;
2000 else
2001 curcoll = savepv(curcoll);
2002
2003# endif /* USE_LOCALE_COLLATE */
2004# ifdef USE_LOCALE_NUMERIC
2005
2006 Safefree(curnum);
2007 curnum = my_setlocale(LC_NUMERIC, trial_locale);
2008 DEBUG_LOCALE_INIT(LC_NUMERIC, trial_locale, curnum);
2009 if (! curnum)
2010 setlocale_failure = TRUE;
2011 else
2012 curnum = savepv(curnum);
2013
2014# endif /* USE_LOCALE_NUMERIC */
2015# ifdef USE_LOCALE_MESSAGES
2016
2017 sl_result = my_setlocale(LC_MESSAGES, trial_locale);
2018 DEBUG_LOCALE_INIT(LC_MESSAGES, trial_locale, sl_result);
2019 if (! (sl_result))
2020 setlocale_failure = TRUE;
2021
2022# endif /* USE_LOCALE_MESSAGES */
2023# ifdef USE_LOCALE_MONETARY
2024
2025 sl_result = my_setlocale(LC_MONETARY, trial_locale);
2026 DEBUG_LOCALE_INIT(LC_MONETARY, trial_locale, sl_result);
2027 if (! (sl_result))
2028 setlocale_failure = TRUE;
2029
2030# endif /* USE_LOCALE_MONETARY */
2031
2032 if (! setlocale_failure) { /* Success */
2033 break;
2034 }
2035 }
2036
2037 /* Here, something failed; will need to try a fallback. */
2038 ok = 0;
2039
2040 if (i == 0) {
2041 unsigned int j;
2042
2043 if (locwarn) { /* Output failure info only on the first one */
2044
2045# ifdef LC_ALL
2046
2047 PerlIO_printf(Perl_error_log,
2048 "perl: warning: Setting locale failed.\n");
2049
2050# else /* !LC_ALL */
2051
2052 PerlIO_printf(Perl_error_log,
2053 "perl: warning: Setting locale failed for the categories:\n\t");
2054
2055# ifdef USE_LOCALE_CTYPE
2056
2057 if (! curctype)
2058 PerlIO_printf(Perl_error_log, "LC_CTYPE ");
2059
2060# endif /* USE_LOCALE_CTYPE */
2061# ifdef USE_LOCALE_COLLATE
2062 if (! curcoll)
2063 PerlIO_printf(Perl_error_log, "LC_COLLATE ");
2064
2065# endif /* USE_LOCALE_COLLATE */
2066# ifdef USE_LOCALE_NUMERIC
2067
2068 if (! curnum)
2069 PerlIO_printf(Perl_error_log, "LC_NUMERIC ");
2070
2071# endif /* USE_LOCALE_NUMERIC */
2072
2073 PerlIO_printf(Perl_error_log, "and possibly others\n");
2074
2075# endif /* LC_ALL */
2076
2077 PerlIO_printf(Perl_error_log,
2078 "perl: warning: Please check that your locale settings:\n");
2079
2080# ifdef __GLIBC__
2081
2082 PerlIO_printf(Perl_error_log,
2083 "\tLANGUAGE = %c%s%c,\n",
2084 language ? '"' : '(',
2085 language ? language : "unset",
2086 language ? '"' : ')');
2087# endif
2088
2089 PerlIO_printf(Perl_error_log,
2090 "\tLC_ALL = %c%s%c,\n",
2091 lc_all ? '"' : '(',
2092 lc_all ? lc_all : "unset",
2093 lc_all ? '"' : ')');
2094
2095# if defined(USE_ENVIRON_ARRAY)
2096
2097 {
2098 char **e;
2099
2100 /* Look through the environment for any variables of the
2101 * form qr/ ^ LC_ [A-Z]+ = /x, except LC_ALL which was
2102 * already handled above. These are assumed to be locale
2103 * settings. Output them and their values. */
2104 for (e = environ; *e; e++) {
2105 const STRLEN prefix_len = sizeof("LC_") - 1;
2106 STRLEN uppers_len;
2107
2108 if ( strBEGINs(*e, "LC_")
2109 && ! strBEGINs(*e, "LC_ALL=")
2110 && (uppers_len = strspn(*e + prefix_len,
2111 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
2112 && ((*e)[prefix_len + uppers_len] == '='))
2113 {
2114 PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
2115 (int) (prefix_len + uppers_len), *e,
2116 *e + prefix_len + uppers_len + 1);
2117 }
2118 }
2119 }
2120
2121# else
2122
2123 PerlIO_printf(Perl_error_log,
2124 "\t(possibly more locale environment variables)\n");
2125
2126# endif
2127
2128 PerlIO_printf(Perl_error_log,
2129 "\tLANG = %c%s%c\n",
2130 lang ? '"' : '(',
2131 lang ? lang : "unset",
2132 lang ? '"' : ')');
2133
2134 PerlIO_printf(Perl_error_log,
2135 " are supported and installed on your system.\n");
2136 }
2137
2138 /* Calculate what fallback locales to try. We have avoided this
2139 * until we have to, because failure is quite unlikely. This will
2140 * usually change the upper bound of the loop we are in.
2141 *
2142 * Since the system's default way of setting the locale has not
2143 * found one that works, We use Perl's defined ordering: LC_ALL,
2144 * LANG, and the C locale. We don't try the same locale twice, so
2145 * don't add to the list if already there. (On POSIX systems, the
2146 * LC_ALL element will likely be a repeat of the 0th element "",
2147 * but there's no harm done by doing it explicitly.
2148 *
2149 * Note that this tries the LC_ALL environment variable even on
2150 * systems which have no LC_ALL locale setting. This may or may
2151 * not have been originally intentional, but there's no real need
2152 * to change the behavior. */
2153 if (lc_all) {
2154 for (j = 0; j < trial_locales_count; j++) {
2155 if (strEQ(lc_all, trial_locales[j])) {
2156 goto done_lc_all;
2157 }
2158 }
2159 trial_locales[trial_locales_count++] = lc_all;
2160 }
2161 done_lc_all:
2162
2163 if (lang) {
2164 for (j = 0; j < trial_locales_count; j++) {
2165 if (strEQ(lang, trial_locales[j])) {
2166 goto done_lang;
2167 }
2168 }
2169 trial_locales[trial_locales_count++] = lang;
2170 }
2171 done_lang:
2172
2173# if defined(WIN32) && defined(LC_ALL)
2174
2175 /* For Windows, we also try the system default locale before "C".
2176 * (If there exists a Windows without LC_ALL we skip this because
2177 * it gets too complicated. For those, the "C" is the next
2178 * fallback possibility). The "" is the same as the 0th element of
2179 * the array, but the code at the loop above knows to treat it
2180 * differently when not the 0th */
2181 trial_locales[trial_locales_count++] = "";
2182
2183# endif
2184
2185 for (j = 0; j < trial_locales_count; j++) {
2186 if (strEQ("C", trial_locales[j])) {
2187 goto done_C;
2188 }
2189 }
2190 trial_locales[trial_locales_count++] = "C";
2191
2192 done_C: ;
2193 } /* end of first time through the loop */
2194
2195# ifdef WIN32
2196
2197 next_iteration: ;
2198
2199# endif
2200
2201 } /* end of looping through the trial locales */
2202
2203 if (ok < 1) { /* If we tried to fallback */
2204 const char* msg;
2205 if (! setlocale_failure) { /* fallback succeeded */
2206 msg = "Falling back to";
2207 }
2208 else { /* fallback failed */
2209
2210 /* We dropped off the end of the loop, so have to decrement i to
2211 * get back to the value the last time through */
2212 i--;
2213
2214 ok = -1;
2215 msg = "Failed to fall back to";
2216
2217 /* To continue, we should use whatever values we've got */
2218
2219# ifdef USE_LOCALE_CTYPE
2220
2221 Safefree(curctype);
2222 curctype = savepv(setlocale(LC_CTYPE, NULL));
2223 DEBUG_LOCALE_INIT(LC_CTYPE, NULL, curctype);
2224
2225# endif /* USE_LOCALE_CTYPE */
2226# ifdef USE_LOCALE_COLLATE
2227
2228 Safefree(curcoll);
2229 curcoll = savepv(setlocale(LC_COLLATE, NULL));
2230 DEBUG_LOCALE_INIT(LC_COLLATE, NULL, curcoll);
2231
2232# endif /* USE_LOCALE_COLLATE */
2233# ifdef USE_LOCALE_NUMERIC
2234
2235 Safefree(curnum);
2236 curnum = savepv(setlocale(LC_NUMERIC, NULL));
2237 DEBUG_LOCALE_INIT(LC_NUMERIC, NULL, curnum);
2238
2239# endif /* USE_LOCALE_NUMERIC */
2240
2241 }
2242
2243 if (locwarn) {
2244 const char * description;
2245 const char * name = "";
2246 if (strEQ(trial_locales[i], "C")) {
2247 description = "the standard locale";
2248 name = "C";
2249 }
2250
2251# ifdef SYSTEM_DEFAULT_LOCALE
2252
2253 else if (strEQ(trial_locales[i], "")) {
2254 description = "the system default locale";
2255 if (system_default_locale) {
2256 name = system_default_locale;
2257 }
2258 }
2259
2260# endif /* SYSTEM_DEFAULT_LOCALE */
2261
2262 else {
2263 description = "a fallback locale";
2264 name = trial_locales[i];
2265 }
2266 if (name && strNE(name, "")) {
2267 PerlIO_printf(Perl_error_log,
2268 "perl: warning: %s %s (\"%s\").\n", msg, description, name);
2269 }
2270 else {
2271 PerlIO_printf(Perl_error_log,
2272 "perl: warning: %s %s.\n", msg, description);
2273 }
2274 }
2275 } /* End of tried to fallback */
2276
2277# ifdef USE_LOCALE_CTYPE
2278
2279 new_ctype(curctype);
2280
2281# endif /* USE_LOCALE_CTYPE */
2282# ifdef USE_LOCALE_COLLATE
2283
2284 new_collate(curcoll);
2285
2286# endif /* USE_LOCALE_COLLATE */
2287# ifdef USE_LOCALE_NUMERIC
2288
2289 new_numeric(curnum);
2290
2291# endif /* USE_LOCALE_NUMERIC */
2292# if defined(USE_PERLIO) && defined(USE_LOCALE_CTYPE)
2293
2294 /* Set PL_utf8locale to TRUE if using PerlIO _and_ the current LC_CTYPE
2295 * locale is UTF-8. If PL_utf8locale and PL_unicode (set by -C or by
2296 * $ENV{PERL_UNICODE}) are true, perl.c:S_parse_body() will turn on the
2297 * PerlIO :utf8 layer on STDIN, STDOUT, STDERR, _and_ the default open
2298 * discipline. */
2299 PL_utf8locale = _is_cur_LC_category_utf8(LC_CTYPE);
2300
2301 /* Set PL_unicode to $ENV{PERL_UNICODE} if using PerlIO.
2302 This is an alternative to using the -C command line switch
2303 (the -C if present will override this). */
2304 {
2305 const char *p = PerlEnv_getenv("PERL_UNICODE");
2306 PL_unicode = p ? parse_unicode_opts(&p) : 0;
2307 if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
2308 PL_utf8cache = -1;
2309 }
2310
2311# endif
2312# ifdef USE_LOCALE_CTYPE
2313
2314 Safefree(curctype);
2315
2316# endif /* USE_LOCALE_CTYPE */
2317# ifdef USE_LOCALE_COLLATE
2318
2319 Safefree(curcoll);
2320
2321# endif /* USE_LOCALE_COLLATE */
2322# ifdef USE_LOCALE_NUMERIC
2323
2324 Safefree(curnum);
2325
2326# endif /* USE_LOCALE_NUMERIC */
2327
2328# ifdef __GLIBC__
2329
2330 Safefree(language);
2331
2332# endif
2333
2334 Safefree(lc_all);
2335 Safefree(lang);
2336
2337#endif /* USE_LOCALE */
2338#ifdef DEBUGGING
2339
2340 /* So won't continue to output stuff */
2341 DEBUG_INITIALIZATION_set(FALSE);
2342
2343#endif
2344
2345 return ok;
2346}
2347
2348#ifdef USE_LOCALE_COLLATE
2349
2350char *
2351Perl__mem_collxfrm(pTHX_ const char *input_string,
2352 STRLEN len, /* Length of 'input_string' */
2353 STRLEN *xlen, /* Set to length of returned string
2354 (not including the collation index
2355 prefix) */
2356 bool utf8 /* Is the input in UTF-8? */
2357 )
2358{
2359
2360 /* _mem_collxfrm() is a bit like strxfrm() but with two important
2361 * differences. First, it handles embedded NULs. Second, it allocates a bit
2362 * more memory than needed for the transformed data itself. The real
2363 * transformed data begins at offset COLLXFRM_HDR_LEN. *xlen is set to
2364 * the length of that, and doesn't include the collation index size.
2365 * Please see sv_collxfrm() to see how this is used. */
2366
2367#define COLLXFRM_HDR_LEN sizeof(PL_collation_ix)
2368
2369 char * s = (char *) input_string;
2370 STRLEN s_strlen = strlen(input_string);
2371 char *xbuf = NULL;
2372 STRLEN xAlloc; /* xalloc is a reserved word in VC */
2373 STRLEN length_in_chars;
2374 bool first_time = TRUE; /* Cleared after first loop iteration */
2375
2376 PERL_ARGS_ASSERT__MEM_COLLXFRM;
2377
2378 /* Must be NUL-terminated */
2379 assert(*(input_string + len) == '\0');
2380
2381 /* If this locale has defective collation, skip */
2382 if (PL_collxfrm_base == 0 && PL_collxfrm_mult == 0) {
2383 DEBUG_L(PerlIO_printf(Perl_debug_log,
2384 "_mem_collxfrm: locale's collation is defective\n"));
2385 goto bad;
2386 }
2387
2388 /* Replace any embedded NULs with the control that sorts before any others.
2389 * This will give as good as possible results on strings that don't
2390 * otherwise contain that character, but otherwise there may be
2391 * less-than-perfect results with that character and NUL. This is
2392 * unavoidable unless we replace strxfrm with our own implementation. */
2393 if (UNLIKELY(s_strlen < len)) { /* Only execute if there is an embedded
2394 NUL */
2395 char * e = s + len;
2396 char * sans_nuls;
2397 STRLEN sans_nuls_len;
2398 int try_non_controls;
2399 char this_replacement_char[] = "?\0"; /* Room for a two-byte string,
2400 making sure 2nd byte is NUL.
2401 */
2402 STRLEN this_replacement_len;
2403
2404 /* If we don't know what non-NUL control character sorts lowest for
2405 * this locale, find it */
2406 if (PL_strxfrm_NUL_replacement == '\0') {
2407 int j;
2408 char * cur_min_x = NULL; /* The min_char's xfrm, (except it also
2409 includes the collation index
2410 prefixed. */
2411
2412 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "Looking to replace NUL\n"));
2413
2414 /* Unlikely, but it may be that no control will work to replace
2415 * NUL, in which case we instead look for any character. Controls
2416 * are preferred because collation order is, in general, context
2417 * sensitive, with adjoining characters affecting the order, and
2418 * controls are less likely to have such interactions, allowing the
2419 * NUL-replacement to stand on its own. (Another way to look at it
2420 * is to imagine what would happen if the NUL were replaced by a
2421 * combining character; it wouldn't work out all that well.) */
2422 for (try_non_controls = 0;
2423 try_non_controls < 2;
2424 try_non_controls++)
2425 {
2426 /* Look through all legal code points (NUL isn't) */
2427 for (j = 1; j < 256; j++) {
2428 char * x; /* j's xfrm plus collation index */
2429 STRLEN x_len; /* length of 'x' */
2430 STRLEN trial_len = 1;
2431 char cur_source[] = { '\0', '\0' };
2432
2433 /* Skip non-controls the first time through the loop. The
2434 * controls in a UTF-8 locale are the L1 ones */
2435 if (! try_non_controls && (PL_in_utf8_COLLATE_locale)
2436 ? ! isCNTRL_L1(j)
2437 : ! isCNTRL_LC(j))
2438 {
2439 continue;
2440 }
2441
2442 /* Create a 1-char string of the current code point */
2443 cur_source[0] = (char) j;
2444
2445 /* Then transform it */
2446 x = _mem_collxfrm(cur_source, trial_len, &x_len,
2447 0 /* The string is not in UTF-8 */);
2448
2449 /* Ignore any character that didn't successfully transform.
2450 * */
2451 if (! x) {
2452 continue;
2453 }
2454
2455 /* If this character's transformation is lower than
2456 * the current lowest, this one becomes the lowest */
2457 if ( cur_min_x == NULL
2458 || strLT(x + COLLXFRM_HDR_LEN,
2459 cur_min_x + COLLXFRM_HDR_LEN))
2460 {
2461 PL_strxfrm_NUL_replacement = j;
2462 cur_min_x = x;
2463 }
2464 else {
2465 Safefree(x);
2466 }
2467 } /* end of loop through all 255 characters */
2468
2469 /* Stop looking if found */
2470 if (cur_min_x) {
2471 break;
2472 }
2473
2474 /* Unlikely, but possible, if there aren't any controls that
2475 * work in the locale, repeat the loop, looking for any
2476 * character that works */
2477 DEBUG_L(PerlIO_printf(Perl_debug_log,
2478 "_mem_collxfrm: No control worked. Trying non-controls\n"));
2479 } /* End of loop to try first the controls, then any char */
2480
2481 if (! cur_min_x) {
2482 DEBUG_L(PerlIO_printf(Perl_debug_log,
2483 "_mem_collxfrm: Couldn't find any character to replace"
2484 " embedded NULs in locale %s with", PL_collation_name));
2485 goto bad;
2486 }
2487
2488 DEBUG_L(PerlIO_printf(Perl_debug_log,
2489 "_mem_collxfrm: Replacing embedded NULs in locale %s with "
2490 "0x%02X\n", PL_collation_name, PL_strxfrm_NUL_replacement));
2491
2492 Safefree(cur_min_x);
2493 } /* End of determining the character that is to replace NULs */
2494
2495 /* If the replacement is variant under UTF-8, it must match the
2496 * UTF8-ness as the original */
2497 if ( ! UVCHR_IS_INVARIANT(PL_strxfrm_NUL_replacement) && utf8) {
2498 this_replacement_char[0] =
2499 UTF8_EIGHT_BIT_HI(PL_strxfrm_NUL_replacement);
2500 this_replacement_char[1] =
2501 UTF8_EIGHT_BIT_LO(PL_strxfrm_NUL_replacement);
2502 this_replacement_len = 2;
2503 }
2504 else {
2505 this_replacement_char[0] = PL_strxfrm_NUL_replacement;
2506 /* this_replacement_char[1] = '\0' was done at initialization */
2507 this_replacement_len = 1;
2508 }
2509
2510 /* The worst case length for the replaced string would be if every
2511 * character in it is NUL. Multiply that by the length of each
2512 * replacement, and allow for a trailing NUL */
2513 sans_nuls_len = (len * this_replacement_len) + 1;
2514 Newx(sans_nuls, sans_nuls_len, char);
2515 *sans_nuls = '\0';
2516
2517 /* Replace each NUL with the lowest collating control. Loop until have
2518 * exhausted all the NULs */
2519 while (s + s_strlen < e) {
2520 my_strlcat(sans_nuls, s, sans_nuls_len);
2521
2522 /* Do the actual replacement */
2523 my_strlcat(sans_nuls, this_replacement_char, sans_nuls_len);
2524
2525 /* Move past the input NUL */
2526 s += s_strlen + 1;
2527 s_strlen = strlen(s);
2528 }
2529
2530 /* And add anything that trails the final NUL */
2531 my_strlcat(sans_nuls, s, sans_nuls_len);
2532
2533 /* Switch so below we transform this modified string */
2534 s = sans_nuls;
2535 len = strlen(s);
2536 } /* End of replacing NULs */
2537
2538 /* Make sure the UTF8ness of the string and locale match */
2539 if (utf8 != PL_in_utf8_COLLATE_locale) {
2540 const char * const t = s; /* Temporary so we can later find where the
2541 input was */
2542
2543 /* Here they don't match. Change the string's to be what the locale is
2544 * expecting */
2545
2546 if (! utf8) { /* locale is UTF-8, but input isn't; upgrade the input */
2547 s = (char *) bytes_to_utf8((const U8 *) s, &len);
2548 utf8 = TRUE;
2549 }
2550 else { /* locale is not UTF-8; but input is; downgrade the input */
2551
2552 s = (char *) bytes_from_utf8((const U8 *) s, &len, &utf8);
2553
2554 /* If the downgrade was successful we are done, but if the input
2555 * contains things that require UTF-8 to represent, have to do
2556 * damage control ... */
2557 if (UNLIKELY(utf8)) {
2558
2559 /* What we do is construct a non-UTF-8 string with
2560 * 1) the characters representable by a single byte converted
2561 * to be so (if necessary);
2562 * 2) and the rest converted to collate the same as the
2563 * highest collating representable character. That makes
2564 * them collate at the end. This is similar to how we
2565 * handle embedded NULs, but we use the highest collating
2566 * code point instead of the smallest. Like the NUL case,
2567 * this isn't perfect, but is the best we can reasonably
2568 * do. Every above-255 code point will sort the same as
2569 * the highest-sorting 0-255 code point. If that code
2570 * point can combine in a sequence with some other code
2571 * points for weight calculations, us changing something to
2572 * be it can adversely affect the results. But in most
2573 * cases, it should work reasonably. And note that this is
2574 * really an illegal situation: using code points above 255
2575 * on a locale where only 0-255 are valid. If two strings
2576 * sort entirely equal, then the sort order for the
2577 * above-255 code points will be in code point order. */
2578
2579 utf8 = FALSE;
2580
2581 /* If we haven't calculated the code point with the maximum
2582 * collating order for this locale, do so now */
2583 if (! PL_strxfrm_max_cp) {
2584 int j;
2585
2586 /* The current transformed string that collates the
2587 * highest (except it also includes the prefixed collation
2588 * index. */
2589 char * cur_max_x = NULL;
2590
2591 /* Look through all legal code points (NUL isn't) */
2592 for (j = 1; j < 256; j++) {
2593 char * x;
2594 STRLEN x_len;
2595 char cur_source[] = { '\0', '\0' };
2596
2597 /* Create a 1-char string of the current code point */
2598 cur_source[0] = (char) j;
2599
2600 /* Then transform it */
2601 x = _mem_collxfrm(cur_source, 1, &x_len, FALSE);
2602
2603 /* If something went wrong (which it shouldn't), just
2604 * ignore this code point */
2605 if (! x) {
2606 continue;
2607 }
2608
2609 /* If this character's transformation is higher than
2610 * the current highest, this one becomes the highest */
2611 if ( cur_max_x == NULL
2612 || strGT(x + COLLXFRM_HDR_LEN,
2613 cur_max_x + COLLXFRM_HDR_LEN))
2614 {
2615 PL_strxfrm_max_cp = j;
2616 cur_max_x = x;
2617 }
2618 else {
2619 Safefree(x);
2620 }
2621 }
2622
2623 if (! cur_max_x) {
2624 DEBUG_L(PerlIO_printf(Perl_debug_log,
2625 "_mem_collxfrm: Couldn't find any character to"
2626 " replace above-Latin1 chars in locale %s with",
2627 PL_collation_name));
2628 goto bad;
2629 }
2630
2631 DEBUG_L(PerlIO_printf(Perl_debug_log,
2632 "_mem_collxfrm: highest 1-byte collating character"
2633 " in locale %s is 0x%02X\n",
2634 PL_collation_name,
2635 PL_strxfrm_max_cp));
2636
2637 Safefree(cur_max_x);
2638 }
2639
2640 /* Here we know which legal code point collates the highest.
2641 * We are ready to construct the non-UTF-8 string. The length
2642 * will be at least 1 byte smaller than the input string
2643 * (because we changed at least one 2-byte character into a
2644 * single byte), but that is eaten up by the trailing NUL */
2645 Newx(s, len, char);
2646
2647 {
2648 STRLEN i;
2649 STRLEN d= 0;
2650 char * e = (char *) t + len;
2651
2652 for (i = 0; i < len; i+= UTF8SKIP(t + i)) {
2653 U8 cur_char = t[i];
2654 if (UTF8_IS_INVARIANT(cur_char)) {
2655 s[d++] = cur_char;
2656 }
2657 else if (UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(t + i, e)) {
2658 s[d++] = EIGHT_BIT_UTF8_TO_NATIVE(cur_char, t[i+1]);
2659 }
2660 else { /* Replace illegal cp with highest collating
2661 one */
2662 s[d++] = PL_strxfrm_max_cp;
2663 }
2664 }
2665 s[d++] = '\0';
2666 Renew(s, d, char); /* Free up unused space */
2667 }
2668 }
2669 }
2670
2671 /* Here, we have constructed a modified version of the input. It could
2672 * be that we already had a modified copy before we did this version.
2673 * If so, that copy is no longer needed */
2674 if (t != input_string) {
2675 Safefree(t);
2676 }
2677 }
2678
2679 length_in_chars = (utf8)
2680 ? utf8_length((U8 *) s, (U8 *) s + len)
2681 : len;
2682
2683 /* The first element in the output is the collation id, used by
2684 * sv_collxfrm(); then comes the space for the transformed string. The
2685 * equation should give us a good estimate as to how much is needed */
2686 xAlloc = COLLXFRM_HDR_LEN
2687 + PL_collxfrm_base
2688 + (PL_collxfrm_mult * length_in_chars);
2689 Newx(xbuf, xAlloc, char);
2690 if (UNLIKELY(! xbuf)) {
2691 DEBUG_L(PerlIO_printf(Perl_debug_log,
2692 "_mem_collxfrm: Couldn't malloc %zu bytes\n", xAlloc));
2693 goto bad;
2694 }
2695
2696 /* Store the collation id */
2697 *(U32*)xbuf = PL_collation_ix;
2698
2699 /* Then the transformation of the input. We loop until successful, or we
2700 * give up */
2701 for (;;) {
2702
2703 *xlen = strxfrm(xbuf + COLLXFRM_HDR_LEN, s, xAlloc - COLLXFRM_HDR_LEN);
2704
2705 /* If the transformed string occupies less space than we told strxfrm()
2706 * was available, it means it successfully transformed the whole
2707 * string. */
2708 if (*xlen < xAlloc - COLLXFRM_HDR_LEN) {
2709
2710 /* Some systems include a trailing NUL in the returned length.
2711 * Ignore it, using a loop in case multiple trailing NULs are
2712 * returned. */
2713 while ( (*xlen) > 0
2714 && *(xbuf + COLLXFRM_HDR_LEN + (*xlen) - 1) == '\0')
2715 {
2716 (*xlen)--;
2717 }
2718
2719 /* If the first try didn't get it, it means our prediction was low.
2720 * Modify the coefficients so that we predict a larger value in any
2721 * future transformations */
2722 if (! first_time) {
2723 STRLEN needed = *xlen + 1; /* +1 For trailing NUL */
2724 STRLEN computed_guess = PL_collxfrm_base
2725 + (PL_collxfrm_mult * length_in_chars);
2726
2727 /* On zero-length input, just keep current slope instead of
2728 * dividing by 0 */
2729 const STRLEN new_m = (length_in_chars != 0)
2730 ? needed / length_in_chars
2731 : PL_collxfrm_mult;
2732
2733 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2734 "%s: %d: initial size of %zu bytes for a length "
2735 "%zu string was insufficient, %zu needed\n",
2736 __FILE__, __LINE__,
2737 computed_guess, length_in_chars, needed));
2738
2739 /* If slope increased, use it, but discard this result for
2740 * length 1 strings, as we can't be sure that it's a real slope
2741 * change */
2742 if (length_in_chars > 1 && new_m > PL_collxfrm_mult) {
2743
2744# ifdef DEBUGGING
2745
2746 STRLEN old_m = PL_collxfrm_mult;
2747 STRLEN old_b = PL_collxfrm_base;
2748
2749# endif
2750
2751 PL_collxfrm_mult = new_m;
2752 PL_collxfrm_base = 1; /* +1 For trailing NUL */
2753 computed_guess = PL_collxfrm_base
2754 + (PL_collxfrm_mult * length_in_chars);
2755 if (computed_guess < needed) {
2756 PL_collxfrm_base += needed - computed_guess;
2757 }
2758
2759 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2760 "%s: %d: slope is now %zu; was %zu, base "
2761 "is now %zu; was %zu\n",
2762 __FILE__, __LINE__,
2763 PL_collxfrm_mult, old_m,
2764 PL_collxfrm_base, old_b));
2765 }
2766 else { /* Slope didn't change, but 'b' did */
2767 const STRLEN new_b = needed
2768 - computed_guess
2769 + PL_collxfrm_base;
2770 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2771 "%s: %d: base is now %zu; was %zu\n",
2772 __FILE__, __LINE__,
2773 new_b, PL_collxfrm_base));
2774 PL_collxfrm_base = new_b;
2775 }
2776 }
2777
2778 break;
2779 }
2780
2781 if (UNLIKELY(*xlen >= PERL_INT_MAX)) {
2782 DEBUG_L(PerlIO_printf(Perl_debug_log,
2783 "_mem_collxfrm: Needed %zu bytes, max permissible is %u\n",
2784 *xlen, PERL_INT_MAX));
2785 goto bad;
2786 }
2787
2788 /* A well-behaved strxfrm() returns exactly how much space it needs
2789 * (usually not including the trailing NUL) when it fails due to not
2790 * enough space being provided. Assume that this is the case unless
2791 * it's been proven otherwise */
2792 if (LIKELY(PL_strxfrm_is_behaved) && first_time) {
2793 xAlloc = *xlen + COLLXFRM_HDR_LEN + 1;
2794 }
2795 else { /* Here, either:
2796 * 1) The strxfrm() has previously shown bad behavior; or
2797 * 2) It isn't the first time through the loop, which means
2798 * that the strxfrm() is now showing bad behavior, because
2799 * we gave it what it said was needed in the previous
2800 * iteration, and it came back saying it needed still more.
2801 * (Many versions of cygwin fit this. When the buffer size
2802 * isn't sufficient, they return the input size instead of
2803 * how much is needed.)
2804 * Increase the buffer size by a fixed percentage and try again.
2805 * */
2806 xAlloc += (xAlloc / 4) + 1;
2807 PL_strxfrm_is_behaved = FALSE;
2808
2809# ifdef DEBUGGING
2810
2811 if (DEBUG_Lv_TEST || debug_initialization) {
2812 PerlIO_printf(Perl_debug_log,
2813 "_mem_collxfrm required more space than previously calculated"
2814 " for locale %s, trying again with new guess=%d+%zu\n",
2815 PL_collation_name, (int) COLLXFRM_HDR_LEN,
2816 xAlloc - COLLXFRM_HDR_LEN);
2817 }
2818
2819# endif
2820
2821 }
2822
2823 Renew(xbuf, xAlloc, char);
2824 if (UNLIKELY(! xbuf)) {
2825 DEBUG_L(PerlIO_printf(Perl_debug_log,
2826 "_mem_collxfrm: Couldn't realloc %zu bytes\n", xAlloc));
2827 goto bad;
2828 }
2829
2830 first_time = FALSE;
2831 }
2832
2833
2834# ifdef DEBUGGING
2835
2836 if (DEBUG_Lv_TEST || debug_initialization) {
2837
2838 print_collxfrm_input_and_return(s, s + len, xlen, utf8);
2839 PerlIO_printf(Perl_debug_log, "Its xfrm is:");
2840 PerlIO_printf(Perl_debug_log, "%s\n",
2841 _byte_dump_string((U8 *) xbuf + COLLXFRM_HDR_LEN,
2842 *xlen, 1));
2843 }
2844
2845# endif
2846
2847 /* Free up unneeded space; retain ehough for trailing NUL */
2848 Renew(xbuf, COLLXFRM_HDR_LEN + *xlen + 1, char);
2849
2850 if (s != input_string) {
2851 Safefree(s);
2852 }
2853
2854 return xbuf;
2855
2856 bad:
2857 Safefree(xbuf);
2858 if (s != input_string) {
2859 Safefree(s);
2860 }
2861 *xlen = 0;
2862
2863# ifdef DEBUGGING
2864
2865 if (DEBUG_Lv_TEST || debug_initialization) {
2866 print_collxfrm_input_and_return(s, s + len, NULL, utf8);
2867 }
2868
2869# endif
2870
2871 return NULL;
2872}
2873
2874# ifdef DEBUGGING
2875
2876STATIC void
2877S_print_collxfrm_input_and_return(pTHX_
2878 const char * const s,
2879 const char * const e,
2880 const STRLEN * const xlen,
2881 const bool is_utf8)
2882{
2883
2884 PERL_ARGS_ASSERT_PRINT_COLLXFRM_INPUT_AND_RETURN;
2885
2886 PerlIO_printf(Perl_debug_log, "_mem_collxfrm[%" UVuf "]: returning ",
2887 (UV)PL_collation_ix);
2888 if (xlen) {
2889 PerlIO_printf(Perl_debug_log, "%zu", *xlen);
2890 }
2891 else {
2892 PerlIO_printf(Perl_debug_log, "NULL");
2893 }
2894 PerlIO_printf(Perl_debug_log, " for locale '%s', string='",
2895 PL_collation_name);
2896 print_bytes_for_locale(s, e, is_utf8);
2897
2898 PerlIO_printf(Perl_debug_log, "'\n");
2899}
2900
2901STATIC void
2902S_print_bytes_for_locale(pTHX_
2903 const char * const s,
2904 const char * const e,
2905 const bool is_utf8)
2906{
2907 const char * t = s;
2908 bool prev_was_printable = TRUE;
2909 bool first_time = TRUE;
2910
2911 PERL_ARGS_ASSERT_PRINT_BYTES_FOR_LOCALE;
2912
2913 while (t < e) {
2914 UV cp = (is_utf8)
2915 ? utf8_to_uvchr_buf((U8 *) t, e, NULL)
2916 : * (U8 *) t;
2917 if (isPRINT(cp)) {
2918 if (! prev_was_printable) {
2919 PerlIO_printf(Perl_debug_log, " ");
2920 }
2921 PerlIO_printf(Perl_debug_log, "%c", (U8) cp);
2922 prev_was_printable = TRUE;
2923 }
2924 else {
2925 if (! first_time) {
2926 PerlIO_printf(Perl_debug_log, " ");
2927 }
2928 PerlIO_printf(Perl_debug_log, "%02" UVXf, cp);
2929 prev_was_printable = FALSE;
2930 }
2931 t += (is_utf8) ? UTF8SKIP(t) : 1;
2932 first_time = FALSE;
2933 }
2934}
2935
2936# endif /* #ifdef DEBUGGING */
2937#endif /* USE_LOCALE_COLLATE */
2938
2939#ifdef USE_LOCALE
2940
2941bool
2942Perl__is_cur_LC_category_utf8(pTHX_ int category)
2943{
2944 /* Returns TRUE if the current locale for 'category' is UTF-8; FALSE
2945 * otherwise. 'category' may not be LC_ALL. If the platform doesn't have
2946 * nl_langinfo(), nor MB_CUR_MAX, this employs a heuristic, which hence
2947 * could give the wrong result. The result will very likely be correct for
2948 * languages that have commonly used non-ASCII characters, but for notably
2949 * English, it comes down to if the locale's name ends in something like
2950 * "UTF-8". It errs on the side of not being a UTF-8 locale. */
2951
2952 char *save_input_locale = NULL;
2953 STRLEN final_pos;
2954
2955# ifdef LC_ALL
2956
2957 assert(category != LC_ALL);
2958
2959# endif
2960
2961 /* First dispose of the trivial cases */
2962 save_input_locale = setlocale(category, NULL);
2963 if (! save_input_locale) {
2964 DEBUG_L(PerlIO_printf(Perl_debug_log,
2965 "Could not find current locale for category %d\n",
2966 category));
2967 return FALSE; /* XXX maybe should croak */
2968 }
2969 save_input_locale = stdize_locale(savepv(save_input_locale));
2970 if (isNAME_C_OR_POSIX(save_input_locale)) {
2971 DEBUG_L(PerlIO_printf(Perl_debug_log,
2972 "Current locale for category %d is %s\n",
2973 category, save_input_locale));
2974 Safefree(save_input_locale);
2975 return FALSE;
2976 }
2977
2978# if defined(USE_LOCALE_CTYPE) \
2979 && (defined(MB_CUR_MAX) || (defined(HAS_NL_LANGINFO) && defined(CODESET)))
2980
2981 { /* Next try nl_langinfo or MB_CUR_MAX if available */
2982
2983 char *save_ctype_locale = NULL;
2984 bool is_utf8;
2985
2986 if (category != LC_CTYPE) { /* These work only on LC_CTYPE */
2987
2988 /* Get the current LC_CTYPE locale */
2989 save_ctype_locale = setlocale(LC_CTYPE, NULL);
2990 if (! save_ctype_locale) {
2991 DEBUG_L(PerlIO_printf(Perl_debug_log,
2992 "Could not find current locale for LC_CTYPE\n"));
2993 goto cant_use_nllanginfo;
2994 }
2995 save_ctype_locale = stdize_locale(savepv(save_ctype_locale));
2996
2997 /* If LC_CTYPE and the desired category use the same locale, this
2998 * means that finding the value for LC_CTYPE is the same as finding
2999 * the value for the desired category. Otherwise, switch LC_CTYPE
3000 * to the desired category's locale */
3001 if (strEQ(save_ctype_locale, save_input_locale)) {
3002 Safefree(save_ctype_locale);
3003 save_ctype_locale = NULL;
3004 }
3005 else if (! setlocale(LC_CTYPE, save_input_locale)) {
3006 DEBUG_L(PerlIO_printf(Perl_debug_log,
3007 "Could not change LC_CTYPE locale to %s\n",
3008 save_input_locale));
3009 Safefree(save_ctype_locale);
3010 goto cant_use_nllanginfo;
3011 }
3012 }
3013
3014 DEBUG_L(PerlIO_printf(Perl_debug_log, "Current LC_CTYPE locale=%s\n",
3015 save_input_locale));
3016
3017 /* Here the current LC_CTYPE is set to the locale of the category whose
3018 * information is desired. This means that nl_langinfo() and MB_CUR_MAX
3019 * should give the correct results */
3020
3021# if defined(HAS_NL_LANGINFO) && defined(CODESET)
3022
3023 {
3024 char *codeset = nl_langinfo(CODESET);
3025 if (codeset && strNE(codeset, "")) {
3026 codeset = savepv(codeset);
3027
3028 /* If we switched LC_CTYPE, switch back */
3029 if (save_ctype_locale) {
3030 setlocale(LC_CTYPE, save_ctype_locale);
3031 Safefree(save_ctype_locale);
3032 }
3033
3034 is_utf8 = foldEQ(codeset, STR_WITH_LEN("UTF-8"))
3035 || foldEQ(codeset, STR_WITH_LEN("UTF8"));
3036
3037 DEBUG_L(PerlIO_printf(Perl_debug_log,
3038 "\tnllanginfo returned CODESET '%s'; ?UTF8 locale=%d\n",
3039 codeset, is_utf8));
3040 Safefree(codeset);
3041 Safefree(save_input_locale);
3042 return is_utf8;
3043 }
3044 }
3045
3046# endif
3047# ifdef MB_CUR_MAX
3048
3049 /* Here, either we don't have nl_langinfo, or it didn't return a
3050 * codeset. Try MB_CUR_MAX */
3051
3052 /* Standard UTF-8 needs at least 4 bytes to represent the maximum
3053 * Unicode code point. Since UTF-8 is the only non-single byte
3054 * encoding we handle, we just say any such encoding is UTF-8, and if
3055 * turns out to be wrong, other things will fail */
3056 is_utf8 = MB_CUR_MAX >= 4;
3057
3058 DEBUG_L(PerlIO_printf(Perl_debug_log,
3059 "\tMB_CUR_MAX=%d; ?UTF8 locale=%d\n",
3060 (int) MB_CUR_MAX, is_utf8));
3061
3062 Safefree(save_input_locale);
3063
3064# ifdef HAS_MBTOWC
3065
3066 /* ... But, most system that have MB_CUR_MAX will also have mbtowc(),
3067 * since they are both in the C99 standard. We can feed a known byte
3068 * string to the latter function, and check that it gives the expected
3069 * result */
3070 if (is_utf8) {
3071 wchar_t wc;
3072 PERL_UNUSED_RESULT(mbtowc(&wc, NULL, 0));/* Reset any shift state */
3073 errno = 0;
3074 if ((size_t)mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8))
3075 != strlen(HYPHEN_UTF8)
3076 || wc != (wchar_t) 0x2010)
3077 {
3078 is_utf8 = FALSE;
3079 DEBUG_L(PerlIO_printf(Perl_debug_log, "\thyphen=U+%x\n", (unsigned int)wc));
3080 DEBUG_L(PerlIO_printf(Perl_debug_log,
3081 "\treturn from mbtowc=%d; errno=%d; ?UTF8 locale=0\n",
3082 mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8)), errno));
3083 }
3084 }
3085
3086# endif
3087
3088 /* If we switched LC_CTYPE, switch back */
3089 if (save_ctype_locale) {
3090 setlocale(LC_CTYPE, save_ctype_locale);
3091 Safefree(save_ctype_locale);
3092 }
3093
3094 return is_utf8;
3095
3096# endif
3097
3098 }
3099
3100 cant_use_nllanginfo:
3101
3102# else /* nl_langinfo should work if available, so don't bother compiling this
3103 fallback code. The final fallback of looking at the name is
3104 compiled, and will be executed if nl_langinfo fails */
3105
3106 /* nl_langinfo not available or failed somehow. Next try looking at the
3107 * currency symbol to see if it disambiguates things. Often that will be
3108 * in the native script, and if the symbol isn't in UTF-8, we know that the
3109 * locale isn't. If it is non-ASCII UTF-8, we infer that the locale is
3110 * too, as the odds of a non-UTF8 string being valid UTF-8 are quite small
3111 * */
3112
3113# ifdef HAS_LOCALECONV
3114# ifdef USE_LOCALE_MONETARY
3115
3116 {
3117 char *save_monetary_locale = NULL;
3118 bool only_ascii = FALSE;
3119 bool is_utf8 = FALSE;
3120 struct lconv* lc;
3121
3122 /* Like above for LC_CTYPE, we first set LC_MONETARY to the locale of
3123 * the desired category, if it isn't that locale already */
3124
3125 if (category != LC_MONETARY) {
3126
3127 save_monetary_locale = setlocale(LC_MONETARY, NULL);
3128 if (! save_monetary_locale) {
3129 DEBUG_L(PerlIO_printf(Perl_debug_log,
3130 "Could not find current locale for LC_MONETARY\n"));
3131 goto cant_use_monetary;
3132 }
3133 save_monetary_locale = stdize_locale(savepv(save_monetary_locale));
3134
3135 if (strEQ(save_monetary_locale, save_input_locale)) {
3136 Safefree(save_monetary_locale);
3137 save_monetary_locale = NULL;
3138 }
3139 else if (! setlocale(LC_MONETARY, save_input_locale)) {
3140 DEBUG_L(PerlIO_printf(Perl_debug_log,
3141 "Could not change LC_MONETARY locale to %s\n",
3142 save_input_locale));
3143 Safefree(save_monetary_locale);
3144 goto cant_use_monetary;
3145 }
3146 }
3147
3148 /* Here the current LC_MONETARY is set to the locale of the category
3149 * whose information is desired. */
3150
3151 lc = localeconv();
3152 if (! lc
3153 || ! lc->currency_symbol
3154 || is_utf8_invariant_string((U8 *) lc->currency_symbol, 0))
3155 {
3156 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));
3157 only_ascii = TRUE;
3158 }
3159 else {
3160 is_utf8 = is_utf8_string((U8 *) lc->currency_symbol, 0);
3161 }
3162
3163 /* If we changed it, restore LC_MONETARY to its original locale */
3164 if (save_monetary_locale) {
3165 setlocale(LC_MONETARY, save_monetary_locale);
3166 Safefree(save_monetary_locale);
3167 }
3168
3169 if (! only_ascii) {
3170
3171 /* It isn't a UTF-8 locale if the symbol is not legal UTF-8;
3172 * otherwise assume the locale is UTF-8 if and only if the symbol
3173 * is non-ascii UTF-8. */
3174 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?Currency symbol for %s is UTF-8=%d\n",
3175 save_input_locale, is_utf8));
3176 Safefree(save_input_locale);
3177 return is_utf8;
3178 }
3179 }
3180 cant_use_monetary:
3181
3182# endif /* USE_LOCALE_MONETARY */
3183# endif /* HAS_LOCALECONV */
3184
3185# if defined(HAS_STRFTIME) && defined(USE_LOCALE_TIME)
3186
3187/* Still haven't found a non-ASCII string to disambiguate UTF-8 or not. Try
3188 * the names of the months and weekdays, timezone, and am/pm indicator */
3189 {
3190 char *save_time_locale = NULL;
3191 int hour = 10;
3192 bool is_dst = FALSE;
3193 int dom = 1;
3194 int month = 0;
3195 int i;
3196 char * formatted_time;
3197
3198
3199 /* Like above for LC_MONETARY, we set LC_TIME to the locale of the
3200 * desired category, if it isn't that locale already */
3201
3202 if (category != LC_TIME) {
3203
3204 save_time_locale = setlocale(LC_TIME, NULL);
3205 if (! save_time_locale) {
3206 DEBUG_L(PerlIO_printf(Perl_debug_log,
3207 "Could not find current locale for LC_TIME\n"));
3208 goto cant_use_time;
3209 }
3210 save_time_locale = stdize_locale(savepv(save_time_locale));
3211
3212 if (strEQ(save_time_locale, save_input_locale)) {
3213 Safefree(save_time_locale);
3214 save_time_locale = NULL;
3215 }
3216 else if (! setlocale(LC_TIME, save_input_locale)) {
3217 DEBUG_L(PerlIO_printf(Perl_debug_log,
3218 "Could not change LC_TIME locale to %s\n",
3219 save_input_locale));
3220 Safefree(save_time_locale);
3221 goto cant_use_time;
3222 }
3223 }
3224
3225 /* Here the current LC_TIME is set to the locale of the category
3226 * whose information is desired. Look at all the days of the week and
3227 * month names, and the timezone and am/pm indicator for UTF-8 variant
3228 * characters. The first such a one found will tell us if the locale
3229 * is UTF-8 or not */
3230
3231 for (i = 0; i < 7 + 12; i++) { /* 7 days; 12 months */
3232 formatted_time = my_strftime("%A %B %Z %p",
3233 0, 0, hour, dom, month, 2012 - 1900, 0, 0, is_dst);
3234 if ( ! formatted_time
3235 || is_utf8_invariant_string((U8 *) formatted_time, 0))
3236 {
3237
3238 /* Here, we didn't find a non-ASCII. Try the next time through
3239 * with the complemented dst and am/pm, and try with the next
3240 * weekday. After we have gotten all weekdays, try the next
3241 * month */
3242 is_dst = ! is_dst;
3243 hour = (hour + 12) % 24;
3244 dom++;
3245 if (i > 6) {
3246 month++;
3247 }
3248 continue;
3249 }
3250
3251 /* Here, we have a non-ASCII. Return TRUE is it is valid UTF8;
3252 * false otherwise. But first, restore LC_TIME to its original
3253 * locale if we changed it */
3254 if (save_time_locale) {
3255 setlocale(LC_TIME, save_time_locale);
3256 Safefree(save_time_locale);
3257 }
3258
3259 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?time-related strings for %s are UTF-8=%d\n",
3260 save_input_locale,
3261 is_utf8_string((U8 *) formatted_time, 0)));
3262 Safefree(save_input_locale);
3263 return is_utf8_string((U8 *) formatted_time, 0);
3264 }
3265
3266 /* Falling off the end of the loop indicates all the names were just
3267 * ASCII. Go on to the next test. If we changed it, restore LC_TIME
3268 * to its original locale */
3269 if (save_time_locale) {
3270 setlocale(LC_TIME, save_time_locale);
3271 Safefree(save_time_locale);
3272 }
3273 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));
3274 }
3275 cant_use_time:
3276
3277# endif
3278
3279# if 0 && defined(USE_LOCALE_MESSAGES) && defined(HAS_SYS_ERRLIST)
3280
3281/* This code is ifdefd out because it was found to not be necessary in testing
3282 * on our dromedary test machine, which has over 700 locales. There, this
3283 * added no value to looking at the currency symbol and the time strings. I
3284 * left it in so as to avoid rewriting it if real-world experience indicates
3285 * that dromedary is an outlier. Essentially, instead of returning abpve if we
3286 * haven't found illegal utf8, we continue on and examine all the strerror()
3287 * messages on the platform for utf8ness. If all are ASCII, we still don't
3288 * know the answer; but otherwise we have a pretty good indication of the
3289 * utf8ness. The reason this doesn't help much is that the messages may not
3290 * have been translated into the locale. The currency symbol and time strings
3291 * are much more likely to have been translated. */
3292 {
3293 int e;
3294 bool is_utf8 = FALSE;
3295 bool non_ascii = FALSE;
3296 char *save_messages_locale = NULL;
3297 const char * errmsg = NULL;
3298
3299 /* Like above, we set LC_MESSAGES to the locale of the desired
3300 * category, if it isn't that locale already */
3301
3302 if (category != LC_MESSAGES) {
3303
3304 save_messages_locale = setlocale(LC_MESSAGES, NULL);
3305 if (! save_messages_locale) {
3306 DEBUG_L(PerlIO_printf(Perl_debug_log,
3307 "Could not find current locale for LC_MESSAGES\n"));
3308 goto cant_use_messages;
3309 }
3310 save_messages_locale = stdize_locale(savepv(save_messages_locale));
3311
3312 if (strEQ(save_messages_locale, save_input_locale)) {
3313 Safefree(save_messages_locale);
3314 save_messages_locale = NULL;
3315 }
3316 else if (! setlocale(LC_MESSAGES, save_input_locale)) {
3317 DEBUG_L(PerlIO_printf(Perl_debug_log,
3318 "Could not change LC_MESSAGES locale to %s\n",
3319 save_input_locale));
3320 Safefree(save_messages_locale);
3321 goto cant_use_messages;
3322 }
3323 }
3324
3325 /* Here the current LC_MESSAGES is set to the locale of the category
3326 * whose information is desired. Look through all the messages. We
3327 * can't use Strerror() here because it may expand to code that
3328 * segfaults in miniperl */
3329
3330 for (e = 0; e <= sys_nerr; e++) {
3331 errno = 0;
3332 errmsg = sys_errlist[e];
3333 if (errno || !errmsg) {
3334 break;
3335 }
3336 errmsg = savepv(errmsg);
3337 if (! is_utf8_invariant_string((U8 *) errmsg, 0)) {
3338 non_ascii = TRUE;
3339 is_utf8 = is_utf8_string((U8 *) errmsg, 0);
3340 break;
3341 }
3342 }
3343 Safefree(errmsg);
3344
3345 /* And, if we changed it, restore LC_MESSAGES to its original locale */
3346 if (save_messages_locale) {
3347 setlocale(LC_MESSAGES, save_messages_locale);
3348 Safefree(save_messages_locale);
3349 }
3350
3351 if (non_ascii) {
3352
3353 /* Any non-UTF-8 message means not a UTF-8 locale; if all are valid,
3354 * any non-ascii means it is one; otherwise we assume it isn't */
3355 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?error messages for %s are UTF-8=%d\n",
3356 save_input_locale,
3357 is_utf8));
3358 Safefree(save_input_locale);
3359 return is_utf8;
3360 }
3361
3362 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));
3363 }
3364 cant_use_messages:
3365
3366# endif
3367# endif /* the code that is compiled when no nl_langinfo */
3368
3369# ifndef EBCDIC /* On os390, even if the name ends with "UTF-8', it isn't a
3370 UTF-8 locale */
3371
3372 /* As a last resort, look at the locale name to see if it matches
3373 * qr/UTF -? * 8 /ix, or some other common locale names. This "name", the
3374 * return of setlocale(), is actually defined to be opaque, so we can't
3375 * really rely on the absence of various substrings in the name to indicate
3376 * its UTF-8ness, but if it has UTF8 in the name, it is extremely likely to
3377 * be a UTF-8 locale. Similarly for the other common names */
3378
3379 final_pos = strlen(save_input_locale) - 1;
3380 if (final_pos >= 3) {
3381 char *name = save_input_locale;
3382
3383 /* Find next 'U' or 'u' and look from there */
3384 while ((name += strcspn(name, "Uu") + 1)
3385 <= save_input_locale + final_pos - 2)
3386 {
3387 if ( !isALPHA_FOLD_NE(*name, 't')
3388 || isALPHA_FOLD_NE(*(name + 1), 'f'))
3389 {
3390 continue;
3391 }
3392 name += 2;
3393 if (*(name) == '-') {
3394 if ((name > save_input_locale + final_pos - 1)) {
3395 break;
3396 }
3397 name++;
3398 }
3399 if (*(name) == '8') {
3400 DEBUG_L(PerlIO_printf(Perl_debug_log,
3401 "Locale %s ends with UTF-8 in name\n",
3402 save_input_locale));
3403 Safefree(save_input_locale);
3404 return TRUE;
3405 }
3406 }
3407 DEBUG_L(PerlIO_printf(Perl_debug_log,
3408 "Locale %s doesn't end with UTF-8 in name\n",
3409 save_input_locale));
3410 }
3411
3412# endif
3413# ifdef WIN32
3414
3415 /* http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756.aspx */
3416 if (memENDs(save_input_locale, final_pos, "65001")) {
3417 DEBUG_L(PerlIO_printf(Perl_debug_log,
3418 "Locale %s ends with 65001 in name, is UTF-8 locale\n",
3419 save_input_locale));
3420 Safefree(save_input_locale);
3421 return TRUE;
3422 }
3423
3424# endif
3425
3426 /* Other common encodings are the ISO 8859 series, which aren't UTF-8. But
3427 * since we are about to return FALSE anyway, there is no point in doing
3428 * this extra work */
3429
3430# if 0
3431 if (instr(save_input_locale, "8859")) {
3432 DEBUG_L(PerlIO_printf(Perl_debug_log,
3433 "Locale %s has 8859 in name, not UTF-8 locale\n",
3434 save_input_locale));
3435 Safefree(save_input_locale);
3436 return FALSE;
3437 }
3438# endif
3439
3440 DEBUG_L(PerlIO_printf(Perl_debug_log,
3441 "Assuming locale %s is not a UTF-8 locale\n",
3442 save_input_locale));
3443 Safefree(save_input_locale);
3444 return FALSE;
3445}
3446
3447#endif
3448
3449
3450bool
3451Perl__is_in_locale_category(pTHX_ const bool compiling, const int category)
3452{
3453 dVAR;
3454 /* Internal function which returns if we are in the scope of a pragma that
3455 * enables the locale category 'category'. 'compiling' should indicate if
3456 * this is during the compilation phase (TRUE) or not (FALSE). */
3457
3458 const COP * const cop = (compiling) ? &PL_compiling : PL_curcop;
3459
3460 SV *categories = cop_hints_fetch_pvs(cop, "locale", 0);
3461 if (! categories || categories == &PL_sv_placeholder) {
3462 return FALSE;
3463 }
3464
3465 /* The pseudo-category 'not_characters' is -1, so just add 1 to each to get
3466 * a valid unsigned */
3467 assert(category >= -1);
3468 return cBOOL(SvUV(categories) & (1U << (category + 1)));
3469}
3470
3471char *
3472Perl_my_strerror(pTHX_ const int errnum)
3473{
3474 /* Returns a mortalized copy of the text of the error message associated
3475 * with 'errnum'. It uses the current locale's text unless the platform
3476 * doesn't have the LC_MESSAGES category or we are not being called from
3477 * within the scope of 'use locale'. In the former case, it uses whatever
3478 * strerror returns; in the latter case it uses the text from the C locale.
3479 *
3480 * The function just calls strerror(), but temporarily switches, if needed,
3481 * to the C locale */
3482
3483 char *errstr;
3484 dVAR;
3485
3486#ifndef USE_LOCALE_MESSAGES
3487
3488 /* If platform doesn't have messages category, we don't do any switching to
3489 * the C locale; we just use whatever strerror() returns */
3490
3491 errstr = savepv(Strerror(errnum));
3492
3493#else /* Has locale messages */
3494
3495 const bool within_locale_scope = IN_LC(LC_MESSAGES);
3496
3497# if defined(HAS_POSIX_2008_LOCALE) && defined(HAS_STRERROR_L)
3498
3499 /* This function is trivial if we have strerror_l() */
3500
3501 if (within_locale_scope) {
3502 errstr = strerror(errnum);
3503 }
3504 else {
3505 errstr = strerror_l(errnum, PL_C_locale_obj);
3506 }
3507
3508 errstr = savepv(errstr);
3509
3510# else /* Doesn't have strerror_l(). */
3511
3512# ifdef USE_POSIX_2008_LOCALE
3513
3514 locale_t save_locale = NULL;
3515
3516# else
3517
3518 char * save_locale = NULL;
3519 bool locale_is_C = FALSE;
3520
3521 /* We have a critical section to prevent another thread from changing the
3522 * locale out from under us (or zapping the buffer returned from
3523 * setlocale() ) */
3524 LOCALE_LOCK;
3525
3526# endif
3527
3528 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3529 "my_strerror called with errnum %d\n", errnum));
3530 if (! within_locale_scope) {
3531 errno = 0;
3532
3533# ifdef USE_POSIX_2008_LOCALE /* Use the thread-safe locale functions */
3534
3535 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3536 "Not within locale scope, about to call"
3537 " uselocale(0x%p)\n", PL_C_locale_obj));
3538 save_locale = uselocale(PL_C_locale_obj);
3539 if (! save_locale) {
3540 DEBUG_L(PerlIO_printf(Perl_debug_log,
3541 "uselocale failed, errno=%d\n", errno));
3542 }
3543 else {
3544 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3545 "uselocale returned 0x%p\n", save_locale));
3546 }
3547
3548# else /* Not thread-safe build */
3549
3550 save_locale = setlocale(LC_MESSAGES, NULL);
3551 if (! save_locale) {
3552 DEBUG_L(PerlIO_printf(Perl_debug_log,
3553 "setlocale failed, errno=%d\n", errno));
3554 }
3555 else {
3556 locale_is_C = isNAME_C_OR_POSIX(save_locale);
3557
3558 /* Switch to the C locale if not already in it */
3559 if (! locale_is_C) {
3560
3561 /* The setlocale() just below likely will zap 'save_locale', so
3562 * create a copy. */
3563 save_locale = savepv(save_locale);
3564 setlocale(LC_MESSAGES, "C");
3565 }
3566 }
3567
3568# endif
3569
3570 } /* end of ! within_locale_scope */
3571 else {
3572 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s: %d: WITHIN locale scope\n",
3573 __FILE__, __LINE__));
3574 }
3575
3576 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3577 "Any locale change has been done; about to call Strerror\n"));
3578 errstr = savepv(Strerror(errnum));
3579
3580 if (! within_locale_scope) {
3581 errno = 0;
3582
3583# ifdef USE_POSIX_2008_LOCALE
3584
3585 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3586 "%s: %d: not within locale scope, restoring the locale\n",
3587 __FILE__, __LINE__));
3588 if (save_locale && ! uselocale(save_locale)) {
3589 DEBUG_L(PerlIO_printf(Perl_debug_log,
3590 "uselocale restore failed, errno=%d\n", errno));
3591 }
3592 }
3593
3594# else
3595
3596 if (save_locale && ! locale_is_C) {
3597 if (! setlocale(LC_MESSAGES, save_locale)) {
3598 DEBUG_L(PerlIO_printf(Perl_debug_log,
3599 "setlocale restore failed, errno=%d\n", errno));
3600 }
3601 Safefree(save_locale);
3602 }
3603 }
3604
3605 LOCALE_UNLOCK;
3606
3607# endif
3608# endif /* End of doesn't have strerror_l */
3609#endif /* End of does have locale messages */
3610
3611#ifdef DEBUGGING
3612
3613 if (DEBUG_Lv_TEST) {
3614 PerlIO_printf(Perl_debug_log, "Strerror returned; saving a copy: '");
3615 print_bytes_for_locale(errstr, errstr + strlen(errstr), 0);
3616 PerlIO_printf(Perl_debug_log, "'\n");
3617 }
3618
3619#endif
3620
3621 SAVEFREEPV(errstr);
3622 return errstr;
3623}
3624
3625/*
3626
3627=for apidoc sync_locale
3628
3629Changing the program's locale should be avoided by XS code. Nevertheless,
3630certain non-Perl libraries called from XS, such as C<Gtk> do so. When this
3631happens, Perl needs to be told that the locale has changed. Use this function
3632to do so, before returning to Perl.
3633
3634=cut
3635*/
3636
3637void
3638Perl_sync_locale(pTHX)
3639{
3640
3641#ifdef USE_LOCALE_CTYPE
3642
3643 new_ctype(setlocale(LC_CTYPE, NULL));
3644
3645#endif /* USE_LOCALE_CTYPE */
3646#ifdef USE_LOCALE_COLLATE
3647
3648 new_collate(setlocale(LC_COLLATE, NULL));
3649
3650#endif
3651#ifdef USE_LOCALE_NUMERIC
3652
3653 set_numeric_local(); /* Switch from "C" to underlying LC_NUMERIC */
3654 new_numeric(setlocale(LC_NUMERIC, NULL));
3655
3656#endif /* USE_LOCALE_NUMERIC */
3657
3658}
3659
3660#if defined(DEBUGGING) && defined(USE_LOCALE)
3661
3662STATIC char *
3663S_setlocale_debug_string(const int category, /* category number,
3664 like LC_ALL */
3665 const char* const locale, /* locale name */
3666
3667 /* return value from setlocale() when attempting to
3668 * set 'category' to 'locale' */
3669 const char* const retval)
3670{
3671 /* Returns a pointer to a NUL-terminated string in static storage with
3672 * added text about the info passed in. This is not thread safe and will
3673 * be overwritten by the next call, so this should be used just to
3674 * formulate a string to immediately print or savepv() on. */
3675
3676 /* initialise to a non-null value to keep it out of BSS and so keep
3677 * -DPERL_GLOBAL_STRUCT_PRIVATE happy */
3678 static char ret[128] = "If you can read this, thank your buggy C"
3679 " library strlcpy(), and change your hints file"
3680 " to undef it";
3681 my_strlcpy(ret, "setlocale(", sizeof(ret));
3682
3683 switch (category) {
3684 default:
3685 my_snprintf(ret, sizeof(ret), "%s? %d", ret, category);
3686 break;
3687
3688# ifdef LC_ALL
3689
3690 case LC_ALL:
3691 my_strlcat(ret, "LC_ALL", sizeof(ret));
3692 break;
3693
3694# endif
3695# ifdef LC_CTYPE
3696
3697 case LC_CTYPE:
3698 my_strlcat(ret, "LC_CTYPE", sizeof(ret));
3699 break;
3700
3701# endif
3702# ifdef LC_NUMERIC
3703
3704 case LC_NUMERIC:
3705 my_strlcat(ret, "LC_NUMERIC", sizeof(ret));
3706 break;
3707
3708# endif
3709# ifdef LC_COLLATE
3710
3711 case LC_COLLATE:
3712 my_strlcat(ret, "LC_COLLATE", sizeof(ret));
3713 break;
3714
3715# endif
3716# ifdef LC_TIME
3717
3718 case LC_TIME:
3719 my_strlcat(ret, "LC_TIME", sizeof(ret));
3720 break;
3721
3722# endif
3723# ifdef LC_MONETARY
3724
3725 case LC_MONETARY:
3726 my_strlcat(ret, "LC_MONETARY", sizeof(ret));
3727 break;
3728
3729# endif
3730# ifdef LC_MESSAGES
3731
3732 case LC_MESSAGES:
3733 my_strlcat(ret, "LC_MESSAGES", sizeof(ret));
3734 break;
3735
3736# endif
3737
3738 }
3739
3740 my_strlcat(ret, ", ", sizeof(ret));
3741
3742 if (locale) {
3743 my_strlcat(ret, "\"", sizeof(ret));
3744 my_strlcat(ret, locale, sizeof(ret));
3745 my_strlcat(ret, "\"", sizeof(ret));
3746 }
3747 else {
3748 my_strlcat(ret, "NULL", sizeof(ret));
3749 }
3750
3751 my_strlcat(ret, ") returned ", sizeof(ret));
3752
3753 if (retval) {
3754 my_strlcat(ret, "\"", sizeof(ret));
3755 my_strlcat(ret, retval, sizeof(ret));
3756 my_strlcat(ret, "\"", sizeof(ret));
3757 }
3758 else {
3759 my_strlcat(ret, "NULL", sizeof(ret));
3760 }
3761
3762 assert(strlen(ret) < sizeof(ret));
3763
3764 return ret;
3765}
3766
3767#endif
3768
3769
3770/*
3771 * ex: set ts=8 sts=4 sw=4 et:
3772 */