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