This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Perl_try_amagic_un/bin re-indent
[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  * This code now has multi-thread-safe locale handling on systems that support
37  * that.  This is completely transparent to most XS code.  On earlier systems,
38  * it would be possible to emulate thread-safe locales, but this likely would
39  * involve a lot of locale switching, and would require XS code changes.
40  * Macros could be written so that the code wouldn't have to know which type of
41  * system is being used.  It's unlikely that we would ever do that, since most
42  * modern systems support thread-safe locales, but there was code written to
43  * this end, and is retained, #ifdef'd out.
44  */
45
46 #include "EXTERN.h"
47 #define PERL_IN_LOCALE_C
48 #include "perl_langinfo.h"
49 #include "perl.h"
50
51 #include "reentr.h"
52
53 #ifdef I_WCHAR
54 #  include <wchar.h>
55 #endif
56
57 /* If the environment says to, we can output debugging information during
58  * initialization.  This is done before option parsing, and before any thread
59  * creation, so can be a file-level static */
60 #if ! defined(DEBUGGING) || defined(PERL_GLOBAL_STRUCT)
61 #  define debug_initialization 0
62 #  define DEBUG_INITIALIZATION_set(v)
63 #else
64 static bool debug_initialization = FALSE;
65 #  define DEBUG_INITIALIZATION_set(v) (debug_initialization = v)
66 #endif
67
68
69 /* Returns the Unix errno portion; ignoring any others.  This is a macro here
70  * instead of putting it into perl.h, because unclear to khw what should be
71  * done generally. */
72 #define GET_ERRNO   saved_errno
73
74 /* strlen() of a literal string constant.  We might want this more general,
75  * but using it in just this file for now.  A problem with more generality is
76  * the compiler warnings about comparing unlike signs */
77 #define STRLENs(s)  (sizeof("" s "") - 1)
78
79 /* Is the C string input 'name' "C" or "POSIX"?  If so, and 'name' is the
80  * return of setlocale(), then this is extremely likely to be the C or POSIX
81  * locale.  However, the output of setlocale() is documented to be opaque, but
82  * the odds are extremely small that it would return these two strings for some
83  * other locale.  Note that VMS in these two locales includes many non-ASCII
84  * characters as controls and punctuation (below are hex bytes):
85  *   cntrl:  84-97 9B-9F
86  *   punct:  A1-A3 A5 A7-AB B0-B3 B5-B7 B9-BD BF-CF D1-DD DF-EF F1-FD
87  * Oddly, none there are listed as alphas, though some represent alphabetics
88  * http://www.nntp.perl.org/group/perl.perl5.porters/2013/02/msg198753.html */
89 #define isNAME_C_OR_POSIX(name)                                              \
90                              (   (name) != NULL                              \
91                               && (( *(name) == 'C' && (*(name + 1)) == '\0') \
92                                    || strEQ((name), "POSIX")))
93
94 #ifdef USE_LOCALE
95
96 /* This code keeps a LRU cache of the UTF-8ness of the locales it has so-far
97  * looked up.  This is in the form of a C string:  */
98
99 #define UTF8NESS_SEP     "\v"
100 #define UTF8NESS_PREFIX  "\f"
101
102 /* So, the string looks like:
103  *
104  *      \vC\a0\vPOSIX\a0\vam_ET\a0\vaf_ZA.utf8\a1\ven_US.UTF-8\a1\0
105  *
106  * where the digit 0 after the \a indicates that the locale starting just
107  * after the preceding \v is not UTF-8, and the digit 1 mean it is. */
108
109 STATIC_ASSERT_DECL(STRLENs(UTF8NESS_SEP) == 1);
110 STATIC_ASSERT_DECL(STRLENs(UTF8NESS_PREFIX) == 1);
111
112 #define C_and_POSIX_utf8ness    UTF8NESS_SEP "C"     UTF8NESS_PREFIX "0"    \
113                                 UTF8NESS_SEP "POSIX" UTF8NESS_PREFIX "0"
114
115 /* The cache is initialized to C_and_POSIX_utf8ness at start up.  These are
116  * kept there always.  The remining portion of the cache is LRU, with the
117  * oldest looked-up locale at the tail end */
118
119 STATIC char *
120 S_stdize_locale(pTHX_ char *locs)
121 {
122     /* Standardize the locale name from a string returned by 'setlocale',
123      * possibly modifying that string.
124      *
125      * The typical return value of setlocale() is either
126      * (1) "xx_YY" if the first argument of setlocale() is not LC_ALL
127      * (2) "xa_YY xb_YY ..." if the first argument of setlocale() is LC_ALL
128      *     (the space-separated values represent the various sublocales,
129      *      in some unspecified order).  This is not handled by this function.
130      *
131      * In some platforms it has a form like "LC_SOMETHING=Lang_Country.866\n",
132      * which is harmful for further use of the string in setlocale().  This
133      * function removes the trailing new line and everything up through the '='
134      * */
135
136     const char * const s = strchr(locs, '=');
137     bool okay = TRUE;
138
139     PERL_ARGS_ASSERT_STDIZE_LOCALE;
140
141     if (s) {
142         const char * const t = strchr(s, '.');
143         okay = FALSE;
144         if (t) {
145             const char * const u = strchr(t, '\n');
146             if (u && (u[1] == 0)) {
147                 const STRLEN len = u - s;
148                 Move(s + 1, locs, len, char);
149                 locs[len] = 0;
150                 okay = TRUE;
151             }
152         }
153     }
154
155     if (!okay)
156         Perl_croak(aTHX_ "Can't fix broken locale name \"%s\"", locs);
157
158     return locs;
159 }
160
161 /* Two parallel arrays; first the locale categories Perl uses on this system;
162  * the second array is their names.  These arrays are in mostly arbitrary
163  * order. */
164
165 const int categories[] = {
166
167 #    ifdef USE_LOCALE_NUMERIC
168                              LC_NUMERIC,
169 #    endif
170 #    ifdef USE_LOCALE_CTYPE
171                              LC_CTYPE,
172 #    endif
173 #    ifdef USE_LOCALE_COLLATE
174                              LC_COLLATE,
175 #    endif
176 #    ifdef USE_LOCALE_TIME
177                              LC_TIME,
178 #    endif
179 #    ifdef USE_LOCALE_MESSAGES
180                              LC_MESSAGES,
181 #    endif
182 #    ifdef USE_LOCALE_MONETARY
183                              LC_MONETARY,
184 #    endif
185 #    ifdef USE_LOCALE_ADDRESS
186                              LC_ADDRESS,
187 #    endif
188 #    ifdef USE_LOCALE_IDENTIFICATION
189                              LC_IDENTIFICATION,
190 #    endif
191 #    ifdef USE_LOCALE_MEASUREMENT
192                              LC_MEASUREMENT,
193 #    endif
194 #    ifdef USE_LOCALE_PAPER
195                              LC_PAPER,
196 #    endif
197 #    ifdef USE_LOCALE_TELEPHONE
198                              LC_TELEPHONE,
199 #    endif
200 #    ifdef LC_ALL
201                              LC_ALL,
202 #    endif
203                             -1  /* Placeholder because C doesn't allow a
204                                    trailing comma, and it would get complicated
205                                    with all the #ifdef's */
206 };
207
208 /* The top-most real element is LC_ALL */
209
210 const char * category_names[] = {
211
212 #    ifdef USE_LOCALE_NUMERIC
213                                  "LC_NUMERIC",
214 #    endif
215 #    ifdef USE_LOCALE_CTYPE
216                                  "LC_CTYPE",
217 #    endif
218 #    ifdef USE_LOCALE_COLLATE
219                                  "LC_COLLATE",
220 #    endif
221 #    ifdef USE_LOCALE_TIME
222                                  "LC_TIME",
223 #    endif
224 #    ifdef USE_LOCALE_MESSAGES
225                                  "LC_MESSAGES",
226 #    endif
227 #    ifdef USE_LOCALE_MONETARY
228                                  "LC_MONETARY",
229 #    endif
230 #    ifdef USE_LOCALE_ADDRESS
231                                  "LC_ADDRESS",
232 #    endif
233 #    ifdef USE_LOCALE_IDENTIFICATION
234                                  "LC_IDENTIFICATION",
235 #    endif
236 #    ifdef USE_LOCALE_MEASUREMENT
237                                  "LC_MEASUREMENT",
238 #    endif
239 #    ifdef USE_LOCALE_PAPER
240                                  "LC_PAPER",
241 #    endif
242 #    ifdef USE_LOCALE_TELEPHONE
243                                  "LC_TELEPHONE",
244 #    endif
245 #    ifdef LC_ALL
246                                  "LC_ALL",
247 #    endif
248                                  NULL  /* Placeholder */
249                             };
250
251 #  ifdef LC_ALL
252
253     /* On systems with LC_ALL, it is kept in the highest index position.  (-2
254      * to account for the final unused placeholder element.) */
255 #    define NOMINAL_LC_ALL_INDEX (C_ARRAY_LENGTH(categories) - 2)
256
257 #  else
258
259     /* On systems without LC_ALL, we pretend it is there, one beyond the real
260      * top element, hence in the unused placeholder element. */
261 #    define NOMINAL_LC_ALL_INDEX (C_ARRAY_LENGTH(categories) - 1)
262
263 #  endif
264
265 /* Pretending there is an LC_ALL element just above allows us to avoid most
266  * special cases.  Most loops through these arrays in the code below are
267  * written like 'for (i = 0; i < NOMINAL_LC_ALL_INDEX; i++)'.  They will work
268  * on either type of system.  But the code must be written to not access the
269  * element at 'LC_ALL_INDEX' except on platforms that have it.  This can be
270  * checked for at compile time by using the #define LC_ALL_INDEX which is only
271  * defined if we do have LC_ALL. */
272
273 STATIC const char *
274 S_category_name(const int category)
275 {
276     unsigned int i;
277
278 #ifdef LC_ALL
279
280     if (category == LC_ALL) {
281         return "LC_ALL";
282     }
283
284 #endif
285
286     for (i = 0; i < NOMINAL_LC_ALL_INDEX; i++) {
287         if (category == categories[i]) {
288             return category_names[i];
289         }
290     }
291
292     {
293         const char suffix[] = " (unknown)";
294         int temp = category;
295         Size_t length = sizeof(suffix) + 1;
296         char * unknown;
297         dTHX;
298
299         if (temp < 0) {
300             length++;
301             temp = - temp;
302         }
303
304         /* Calculate the number of digits */
305         while (temp >= 10) {
306             temp /= 10;
307             length++;
308         }
309
310         Newx(unknown, length, char);
311         my_snprintf(unknown, length, "%d%s", category, suffix);
312         SAVEFREEPV(unknown);
313         return unknown;
314     }
315 }
316
317 /* Now create LC_foo_INDEX #defines for just those categories on this system */
318 #  ifdef USE_LOCALE_NUMERIC
319 #    define LC_NUMERIC_INDEX            0
320 #    define _DUMMY_NUMERIC              LC_NUMERIC_INDEX
321 #  else
322 #    define _DUMMY_NUMERIC              -1
323 #  endif
324 #  ifdef USE_LOCALE_CTYPE
325 #    define LC_CTYPE_INDEX              _DUMMY_NUMERIC + 1
326 #    define _DUMMY_CTYPE                LC_CTYPE_INDEX
327 #  else
328 #    define _DUMMY_CTYPE                _DUMMY_NUMERIC
329 #  endif
330 #  ifdef USE_LOCALE_COLLATE
331 #    define LC_COLLATE_INDEX            _DUMMY_CTYPE + 1
332 #    define _DUMMY_COLLATE              LC_COLLATE_INDEX
333 #  else
334 #    define _DUMMY_COLLATE              _DUMMY_CTYPE
335 #  endif
336 #  ifdef USE_LOCALE_TIME
337 #    define LC_TIME_INDEX               _DUMMY_COLLATE + 1
338 #    define _DUMMY_TIME                 LC_TIME_INDEX
339 #  else
340 #    define _DUMMY_TIME                 _DUMMY_COLLATE
341 #  endif
342 #  ifdef USE_LOCALE_MESSAGES
343 #    define LC_MESSAGES_INDEX           _DUMMY_TIME + 1
344 #    define _DUMMY_MESSAGES             LC_MESSAGES_INDEX
345 #  else
346 #    define _DUMMY_MESSAGES             _DUMMY_TIME
347 #  endif
348 #  ifdef USE_LOCALE_MONETARY
349 #    define LC_MONETARY_INDEX           _DUMMY_MESSAGES + 1
350 #    define _DUMMY_MONETARY             LC_MONETARY_INDEX
351 #  else
352 #    define _DUMMY_MONETARY             _DUMMY_MESSAGES
353 #  endif
354 #  ifdef USE_LOCALE_ADDRESS
355 #    define LC_ADDRESS_INDEX            _DUMMY_MONETARY + 1
356 #    define _DUMMY_ADDRESS              LC_ADDRESS_INDEX
357 #  else
358 #    define _DUMMY_ADDRESS              _DUMMY_MONETARY
359 #  endif
360 #  ifdef USE_LOCALE_IDENTIFICATION
361 #    define LC_IDENTIFICATION_INDEX     _DUMMY_ADDRESS + 1
362 #    define _DUMMY_IDENTIFICATION       LC_IDENTIFICATION_INDEX
363 #  else
364 #    define _DUMMY_IDENTIFICATION       _DUMMY_ADDRESS
365 #  endif
366 #  ifdef USE_LOCALE_MEASUREMENT
367 #    define LC_MEASUREMENT_INDEX        _DUMMY_IDENTIFICATION + 1
368 #    define _DUMMY_MEASUREMENT          LC_MEASUREMENT_INDEX
369 #  else
370 #    define _DUMMY_MEASUREMENT          _DUMMY_IDENTIFICATION
371 #  endif
372 #  ifdef USE_LOCALE_PAPER
373 #    define LC_PAPER_INDEX              _DUMMY_MEASUREMENT + 1
374 #    define _DUMMY_PAPER                LC_PAPER_INDEX
375 #  else
376 #    define _DUMMY_PAPER                _DUMMY_MEASUREMENT
377 #  endif
378 #  ifdef USE_LOCALE_TELEPHONE
379 #    define LC_TELEPHONE_INDEX          _DUMMY_PAPER + 1
380 #    define _DUMMY_TELEPHONE            LC_TELEPHONE_INDEX
381 #  else
382 #    define _DUMMY_TELEPHONE            _DUMMY_PAPER
383 #  endif
384 #  ifdef LC_ALL
385 #    define LC_ALL_INDEX                _DUMMY_TELEPHONE + 1
386 #  endif
387 #endif /* ifdef USE_LOCALE */
388
389 /* Windows requres a customized base-level setlocale() */
390 #ifdef WIN32
391 #  define my_setlocale(cat, locale) win32_setlocale(cat, locale)
392 #else
393 #  define my_setlocale(cat, locale) setlocale(cat, locale)
394 #endif
395
396 #ifndef USE_POSIX_2008_LOCALE
397
398 /* "do_setlocale_c" is intended to be called when the category is a constant
399  * known at compile time; "do_setlocale_r", not known until run time  */
400 #  define do_setlocale_c(cat, locale) my_setlocale(cat, locale)
401 #  define do_setlocale_r(cat, locale) my_setlocale(cat, locale)
402
403 #else   /* Below uses POSIX 2008 */
404
405 /* We emulate setlocale with our own function.  LC_foo is not valid for the
406  * POSIX 2008 functions.  Instead LC_foo_MASK is used, which we use an array
407  * lookup to convert to.  At compile time we have defined LC_foo_INDEX as the
408  * proper offset into the array 'category_masks[]'.  At runtime, we have to
409  * search through the array (as the actual numbers may not be small contiguous
410  * positive integers which would lend themselves to array lookup). */
411 #  define do_setlocale_c(cat, locale)                                       \
412                         emulate_setlocale(cat, locale, cat ## _INDEX, TRUE)
413 #  define do_setlocale_r(cat, locale) emulate_setlocale(cat, locale, 0, FALSE)
414
415 /* A third array, parallel to the ones above to map from category to its
416  * equivalent mask */
417 const int category_masks[] = {
418 #  ifdef USE_LOCALE_NUMERIC
419                                 LC_NUMERIC_MASK,
420 #  endif
421 #  ifdef USE_LOCALE_CTYPE
422                                 LC_CTYPE_MASK,
423 #  endif
424 #  ifdef USE_LOCALE_COLLATE
425                                 LC_COLLATE_MASK,
426 #  endif
427 #  ifdef USE_LOCALE_TIME
428                                 LC_TIME_MASK,
429 #  endif
430 #  ifdef USE_LOCALE_MESSAGES
431                                 LC_MESSAGES_MASK,
432 #  endif
433 #  ifdef USE_LOCALE_MONETARY
434                                 LC_MONETARY_MASK,
435 #  endif
436 #  ifdef USE_LOCALE_ADDRESS
437                                 LC_ADDRESS_MASK,
438 #  endif
439 #  ifdef USE_LOCALE_IDENTIFICATION
440                                 LC_IDENTIFICATION_MASK,
441 #  endif
442 #  ifdef USE_LOCALE_MEASUREMENT
443                                 LC_MEASUREMENT_MASK,
444 #  endif
445 #  ifdef USE_LOCALE_PAPER
446                                 LC_PAPER_MASK,
447 #  endif
448 #  ifdef USE_LOCALE_TELEPHONE
449                                 LC_TELEPHONE_MASK,
450 #  endif
451                                 /* LC_ALL can't be turned off by a Configure
452                                  * option, and in Posix 2008, should always be
453                                  * here, so compile it in unconditionally.
454                                  * This could catch some glitches at compile
455                                  * time */
456                                 LC_ALL_MASK
457                             };
458
459 STATIC const char *
460 S_emulate_setlocale(const int category,
461                     const char * locale,
462                     unsigned int index,
463                     const bool is_index_valid
464                    )
465 {
466     /* This function effectively performs a setlocale() on just the current
467      * thread; thus it is thread-safe.  It does this by using the POSIX 2008
468      * locale functions to emulate the behavior of setlocale().  Similar to
469      * regular setlocale(), the return from this function points to memory that
470      * can be overwritten by other system calls, so needs to be copied
471      * immediately if you need to retain it.  The difference here is that
472      * system calls besides another setlocale() can overwrite it.
473      *
474      * By doing this, most locale-sensitive functions become thread-safe.  The
475      * exceptions are mostly those that return a pointer to static memory.
476      *
477      * This function takes the same parameters, 'category' and 'locale', that
478      * the regular setlocale() function does, but it also takes two additional
479      * ones.  This is because the 2008 functions don't use a category; instead
480      * they use a corresponding mask.  Because this function operates in both
481      * worlds, it may need one or the other or both.  This function can
482      * calculate the mask from the input category, but to avoid this
483      * calculation, if the caller knows at compile time what the mask is, it
484      * can pass it, setting 'is_index_valid' to TRUE; otherwise the mask
485      * parameter is ignored.
486      *
487      * POSIX 2008, for some sick reason, chose not to provide a method to find
488      * the category name of a locale.  Some vendors have created a
489      * querylocale() function to do just that.  This function is a lot simpler
490      * to implement on systems that have this.  Otherwise, we have to keep
491      * track of what the locale has been set to, so that we can return its
492      * name to emulate setlocale().  It's also possible for C code in some
493      * library to change the locale without us knowing it, though as of
494      * September 2017, there are no occurrences in CPAN of uselocale().  Some
495      * libraries do use setlocale(), but that changes the global locale, and
496      * threads using per-thread locales will just ignore those changes.
497      * Another problem is that without querylocale(), we have to guess at what
498      * was meant by setting a locale of "".  We handle this by not actually
499      * ever setting to "" (unless querylocale exists), but to emulate what we
500      * think should happen for "".
501      */
502
503     int mask;
504     locale_t old_obj;
505     locale_t new_obj;
506     dTHX;
507
508 #  ifdef DEBUGGING
509
510     if (DEBUG_Lv_TEST || debug_initialization) {
511         PerlIO_printf(Perl_debug_log, "%s:%d: emulate_setlocale input=%d (%s), \"%s\", %d, %d\n", __FILE__, __LINE__, category, category_name(category), locale, index, is_index_valid);
512     }
513
514 #  endif
515
516     /* If the input mask might be incorrect, calculate the correct one */
517     if (! is_index_valid) {
518         unsigned int i;
519
520 #  ifdef DEBUGGING
521
522         if (DEBUG_Lv_TEST || debug_initialization) {
523             PerlIO_printf(Perl_debug_log, "%s:%d: finding index of category %d (%s)\n", __FILE__, __LINE__, category, category_name(category));
524         }
525
526 #  endif
527
528         for (i = 0; i <= LC_ALL_INDEX; i++) {
529             if (category == categories[i]) {
530                 index = i;
531                 goto found_index;
532             }
533         }
534
535         /* Here, we don't know about this category, so can't handle it.
536          * Fallback to the early POSIX usages */
537         Perl_warner(aTHX_ packWARN(WARN_LOCALE),
538                             "Unknown locale category %d; can't set it to %s\n",
539                                                      category, locale);
540         return NULL;
541
542       found_index: ;
543
544 #  ifdef DEBUGGING
545
546         if (DEBUG_Lv_TEST || debug_initialization) {
547             PerlIO_printf(Perl_debug_log, "%s:%d: index is %d for %s\n", __FILE__, __LINE__, index, category_name(category));
548         }
549
550 #  endif
551
552     }
553
554     mask = category_masks[index];
555
556 #  ifdef DEBUGGING
557
558     if (DEBUG_Lv_TEST || debug_initialization) {
559         PerlIO_printf(Perl_debug_log, "%s:%d: category name is %s; mask is 0x%x\n", __FILE__, __LINE__, category_names[index], mask);
560     }
561
562 #  endif
563
564     /* If just querying what the existing locale is ... */
565     if (locale == NULL) {
566         locale_t cur_obj = uselocale((locale_t) 0);
567
568 #  ifdef DEBUGGING
569
570         if (DEBUG_Lv_TEST || debug_initialization) {
571             PerlIO_printf(Perl_debug_log, "%s:%d: emulate_setlocale querying %p\n", __FILE__, __LINE__, cur_obj);
572         }
573
574 #  endif
575
576         if (cur_obj == LC_GLOBAL_LOCALE) {
577             return my_setlocale(category, NULL);
578         }
579
580 #  ifdef HAS_QUERYLOCALE
581
582         return (char *) querylocale(mask, cur_obj);
583
584 #  else
585
586         /* If this assert fails, adjust the size of curlocales in intrpvar.h */
587         STATIC_ASSERT_STMT(C_ARRAY_LENGTH(PL_curlocales) > LC_ALL_INDEX);
588
589 #    if defined(_NL_LOCALE_NAME) && defined(DEBUGGING)
590
591         {
592             /* Internal glibc for querylocale(), but doesn't handle
593              * empty-string ("") locale properly; who knows what other
594              * glitches.  Check it for now, under debug. */
595
596             char * temp_name = nl_langinfo_l(_NL_LOCALE_NAME(category),
597                                              uselocale((locale_t) 0));
598             /*
599             PerlIO_printf(Perl_debug_log, "%s:%d: temp_name=%s\n", __FILE__, __LINE__, temp_name ? temp_name : "NULL");
600             PerlIO_printf(Perl_debug_log, "%s:%d: index=%d\n", __FILE__, __LINE__, index);
601             PerlIO_printf(Perl_debug_log, "%s:%d: PL_curlocales[index]=%s\n", __FILE__, __LINE__, PL_curlocales[index]);
602             */
603             if (temp_name && PL_curlocales[index] && strNE(temp_name, "")) {
604                 if (         strNE(PL_curlocales[index], temp_name)
605                     && ! (   isNAME_C_OR_POSIX(temp_name)
606                           && isNAME_C_OR_POSIX(PL_curlocales[index]))) {
607
608 #      ifdef USE_C_BACKTRACE
609
610                     dump_c_backtrace(Perl_debug_log, 20, 1);
611
612 #      endif
613
614                     Perl_croak(aTHX_ "panic: Mismatch between what Perl thinks %s is"
615                                      " (%s) and what internal glibc thinks"
616                                      " (%s)\n", category_names[index],
617                                      PL_curlocales[index], temp_name);
618                 }
619
620                 return temp_name;
621             }
622         }
623
624 #    endif
625
626         /* Without querylocale(), we have to use our record-keeping we've
627          *  done. */
628
629         if (category != LC_ALL) {
630
631 #    ifdef DEBUGGING
632
633             if (DEBUG_Lv_TEST || debug_initialization) {
634                 PerlIO_printf(Perl_debug_log, "%s:%d: emulate_setlocale returning %s\n", __FILE__, __LINE__, PL_curlocales[index]);
635             }
636
637 #    endif
638
639             return PL_curlocales[index];
640         }
641         else {  /* For LC_ALL */
642             unsigned int i;
643             Size_t names_len = 0;
644             char * all_string;
645             bool are_all_categories_the_same_locale = TRUE;
646
647             /* If we have a valid LC_ALL value, just return it */
648             if (PL_curlocales[LC_ALL_INDEX]) {
649
650 #    ifdef DEBUGGING
651
652                 if (DEBUG_Lv_TEST || debug_initialization) {
653                     PerlIO_printf(Perl_debug_log, "%s:%d: emulate_setlocale returning %s\n", __FILE__, __LINE__, PL_curlocales[LC_ALL_INDEX]);
654                 }
655
656 #    endif
657
658                 return PL_curlocales[LC_ALL_INDEX];
659             }
660
661             /* Otherwise, we need to construct a string of name=value pairs.
662              * We use the glibc syntax, like
663              *      LC_NUMERIC=C;LC_TIME=en_US.UTF-8;...
664              *  First calculate the needed size.  Along the way, check if all
665              *  the locale names are the same */
666             for (i = 0; i < LC_ALL_INDEX; i++) {
667
668 #    ifdef DEBUGGING
669
670                 if (DEBUG_Lv_TEST || debug_initialization) {
671                     PerlIO_printf(Perl_debug_log, "%s:%d: emulate_setlocale i=%d, name=%s, locale=%s\n", __FILE__, __LINE__, i, category_names[i], PL_curlocales[i]);
672                 }
673
674 #    endif
675
676                 names_len += strlen(category_names[i])
677                           + 1                       /* '=' */
678                           + strlen(PL_curlocales[i])
679                           + 1;                      /* ';' */
680
681                 if (i > 0 && strNE(PL_curlocales[i], PL_curlocales[i-1])) {
682                     are_all_categories_the_same_locale = FALSE;
683                 }
684             }
685
686             /* If they are the same, we don't actually have to construct the
687              * string; we just make the entry in LC_ALL_INDEX valid, and be
688              * that single name */
689             if (are_all_categories_the_same_locale) {
690                 PL_curlocales[LC_ALL_INDEX] = savepv(PL_curlocales[0]);
691                 return PL_curlocales[LC_ALL_INDEX];
692             }
693
694             names_len++;    /* Trailing '\0' */
695             SAVEFREEPV(Newx(all_string, names_len, char));
696             *all_string = '\0';
697
698             /* Then fill in the string */
699             for (i = 0; i < LC_ALL_INDEX; i++) {
700
701 #    ifdef DEBUGGING
702
703                 if (DEBUG_Lv_TEST || debug_initialization) {
704                     PerlIO_printf(Perl_debug_log, "%s:%d: emulate_setlocale i=%d, name=%s, locale=%s\n", __FILE__, __LINE__, i, category_names[i], PL_curlocales[i]);
705                 }
706
707 #    endif
708
709                 my_strlcat(all_string, category_names[i], names_len);
710                 my_strlcat(all_string, "=", names_len);
711                 my_strlcat(all_string, PL_curlocales[i], names_len);
712                 my_strlcat(all_string, ";", names_len);
713             }
714
715 #    ifdef DEBUGGING
716
717             if (DEBUG_L_TEST || debug_initialization) {
718                 PerlIO_printf(Perl_debug_log, "%s:%d: emulate_setlocale returning %s\n", __FILE__, __LINE__, all_string);
719             }
720
721     #endif
722
723             return all_string;
724         }
725
726 #    ifdef EINVAL
727
728         SETERRNO(EINVAL, LIB_INVARG);
729
730 #    endif
731
732         return NULL;
733
734 #  endif
735
736     }
737
738     /* Here, we are switching locales. */
739
740 #  ifndef HAS_QUERYLOCALE
741
742     if (strEQ(locale, "")) {
743
744         /* For non-querylocale() systems, we do the setting of "" ourselves to
745          * be sure that we really know what's going on.  We follow the Linux
746          * documented behavior (but if that differs from the actual behavior,
747          * this won't work exactly as the OS implements).  We go out and
748          * examine the environment based on our understanding of how the system
749          * works, and use that to figure things out */
750
751         const char * const lc_all = PerlEnv_getenv("LC_ALL");
752
753         /* Use any "LC_ALL" environment variable, as it overrides everything
754          * else. */
755         if (lc_all && strNE(lc_all, "")) {
756             locale = lc_all;
757         }
758         else {
759
760             /* Otherwise, we need to dig deeper.  Unless overridden, the
761              * default is the LANG environment variable; if it doesn't exist,
762              * then "C" */
763
764             const char * default_name;
765
766             /* To minimize other threads messing with the environment, we copy
767              * the variable, making it a temporary.  But this doesn't work upon
768              * program initialization before any scopes are created, and at
769              * this time, there's nothing else going on that would interfere.
770              * So skip the copy in that case */
771             if (PL_scopestack_ix == 0) {
772                 default_name = PerlEnv_getenv("LANG");
773             }
774             else {
775                 default_name = savepv(PerlEnv_getenv("LANG"));
776             }
777
778             if (! default_name || strEQ(default_name, "")) {
779                 default_name = "C";
780             }
781             else if (PL_scopestack_ix != 0) {
782                 SAVEFREEPV(default_name);
783             }
784
785             if (category != LC_ALL) {
786                 const char * const name = PerlEnv_getenv(category_names[index]);
787
788                 /* Here we are setting a single category.  Assume will have the
789                  * default name */
790                 locale = default_name;
791
792                 /* But then look for an overriding environment variable */
793                 if (name && strNE(name, "")) {
794                     locale = name;
795                 }
796             }
797             else {
798                 bool did_override = FALSE;
799                 unsigned int i;
800
801                 /* Here, we are getting LC_ALL.  Any categories that don't have
802                  * a corresponding environment variable set should be set to
803                  * LANG, or to "C" if there is no LANG.  If no individual
804                  * categories differ from this, we can just set LC_ALL.  This
805                  * is buggy on systems that have extra categories that we don't
806                  * know about.  If there is an environment variable that sets
807                  * that category, we won't know to look for it, and so our use
808                  * of LANG or "C" improperly overrides it.  On the other hand,
809                  * if we don't do what is done here, and there is no
810                  * environment variable, the category's locale should be set to
811                  * LANG or "C".  So there is no good solution.  khw thinks the
812                  * best is to look at systems to see what categories they have,
813                  * and include them, and then to assume that we know the
814                  * complete set */
815
816                 for (i = 0; i < LC_ALL_INDEX; i++) {
817                     const char * const env_override
818                                     = savepv(PerlEnv_getenv(category_names[i]));
819                     const char * this_locale = (   env_override
820                                                 && strNE(env_override, ""))
821                                                ? env_override
822                                                : default_name;
823                     if (! emulate_setlocale(categories[i], this_locale, i, TRUE))
824                     {
825                         Safefree(env_override);
826                         return NULL;
827                     }
828
829                     if (strNE(this_locale, default_name)) {
830                         did_override = TRUE;
831                     }
832
833                     Safefree(env_override);
834                 }
835
836                 /* If all the categories are the same, we can set LC_ALL to
837                  * that */
838                 if (! did_override) {
839                     locale = default_name;
840                 }
841                 else {
842
843                     /* Here, LC_ALL is no longer valid, as some individual
844                      * categories don't match it.  We call ourselves
845                      * recursively, as that will execute the code that
846                      * generates the proper locale string for this situation.
847                      * We don't do the remainder of this function, as that is
848                      * to update our records, and we've just done that for the
849                      * individual categories in the loop above, and doing so
850                      * would cause LC_ALL to be done as well */
851                     return emulate_setlocale(LC_ALL, NULL, LC_ALL_INDEX, TRUE);
852                 }
853             }
854         }
855     }
856     else if (strchr(locale, ';')) {
857
858         /* LC_ALL may actually incude a conglomeration of various categories.
859          * Without querylocale, this code uses the glibc (as of this writing)
860          * syntax for representing that, but that is not a stable API, and
861          * other platforms do it differently, so we have to handle all cases
862          * ourselves */
863
864         unsigned int i;
865         const char * s = locale;
866         const char * e = locale + strlen(locale);
867         const char * p = s;
868         const char * category_end;
869         const char * name_start;
870         const char * name_end;
871
872         /* If the string that gives what to set doesn't include all categories,
873          * the omitted ones get set to "C".  To get this behavior, first set
874          * all the individual categories to "C", and override the furnished
875          * ones below */
876         for (i = 0; i < LC_ALL_INDEX; i++) {
877             if (! emulate_setlocale(categories[i], "C", i, TRUE)) {
878                 return NULL;
879             }
880         }
881
882         while (s < e) {
883
884             /* Parse through the category */
885             while (isWORDCHAR(*p)) {
886                 p++;
887             }
888             category_end = p;
889
890             if (*p++ != '=') {
891                 Perl_croak(aTHX_
892                     "panic: %s: %d: Unexpected character in locale name '%02X",
893                     __FILE__, __LINE__, *(p-1));
894             }
895
896             /* Parse through the locale name */
897             name_start = p;
898             while (p < e && *p != ';') {
899                 if (! isGRAPH(*p)) {
900                     Perl_croak(aTHX_
901                         "panic: %s: %d: Unexpected character in locale name '%02X",
902                         __FILE__, __LINE__, *(p-1));
903                 }
904                 p++;
905             }
906             name_end = p;
907
908             /* Space past the semi-colon */
909             if (p < e) {
910                 p++;
911             }
912
913             /* Find the index of the category name in our lists */
914             for (i = 0; i < LC_ALL_INDEX; i++) {
915                 char * individ_locale;
916
917                 /* Keep going if this isn't the index.  The strnNE() avoids a
918                  * Perl_form(), but would fail if ever a category name could be
919                  * a substring of another one, like if there were a
920                  * "LC_TIME_DATE" */
921                 if strnNE(s, category_names[i], category_end - s) {
922                     continue;
923                 }
924
925                 /* If this index is for the single category we're changing, we
926                  * have found the locale to set it to. */
927                 if (category == categories[i]) {
928                     locale = Perl_form(aTHX_ "%.*s",
929                                              (int) (name_end - name_start),
930                                              name_start);
931                     goto ready_to_set;
932                 }
933
934                 assert(category == LC_ALL);
935                 individ_locale = Perl_form(aTHX_ "%.*s",
936                                     (int) (name_end - name_start), name_start);
937                 if (! emulate_setlocale(categories[i], individ_locale, i, TRUE))
938                 {
939                     return NULL;
940                 }
941             }
942
943             s = p;
944         }
945
946         /* Here we have set all the individual categories by recursive calls.
947          * These collectively should have fixed up LC_ALL, so can just query
948          * what that now is */
949         assert(category == LC_ALL);
950
951         return do_setlocale_c(LC_ALL, NULL);
952     }
953
954   ready_to_set: ;
955
956     /* Here at the end of having to deal with the absence of querylocale().
957      * Some cases have already been fully handled by recursive calls to this
958      * function.  But at this point, we haven't dealt with those, but are now
959      * prepared to, knowing what the locale name to set this category to is.
960      * This would have come for free if this system had had querylocale() */
961
962 #  endif  /* end of ! querylocale */
963
964     assert(PL_C_locale_obj);
965
966     /* Switching locales generally entails freeing the current one's space (at
967      * the C library's discretion).  We need to stop using that locale before
968      * the switch.  So switch to a known locale object that we don't otherwise
969      * mess with.  This returns the locale object in effect at the time of the
970      * switch. */
971     old_obj = uselocale(PL_C_locale_obj);
972
973 #  ifdef DEBUGGING
974
975     if (DEBUG_Lv_TEST || debug_initialization) {
976         PerlIO_printf(Perl_debug_log, "%s:%d: emulate_setlocale was using %p\n", __FILE__, __LINE__, old_obj);
977     }
978
979 #  endif
980
981     if (! old_obj) {
982
983 #  ifdef DEBUGGING
984
985         if (DEBUG_L_TEST || debug_initialization) {
986             dSAVE_ERRNO;
987             PerlIO_printf(Perl_debug_log, "%s:%d: emulate_setlocale switching to C failed: %d\n", __FILE__, __LINE__, GET_ERRNO);
988             RESTORE_ERRNO;
989         }
990
991 #  endif
992
993         return NULL;
994     }
995
996 #  ifdef DEBUGGING
997
998     if (DEBUG_Lv_TEST || debug_initialization) {
999         PerlIO_printf(Perl_debug_log, "%s:%d: emulate_setlocale now using %p\n", __FILE__, __LINE__, PL_C_locale_obj);
1000     }
1001
1002 #  endif
1003
1004     /* If we weren't in a thread safe locale, set so that newlocale() below
1005      which uses 'old_obj', uses an empty one.  Same for our reserved C object.
1006      The latter is defensive coding, so that, even if there is some bug, we
1007      will never end up trying to modify either of these, as if passed to
1008      newlocale(), they can be. */
1009     if (old_obj == LC_GLOBAL_LOCALE || old_obj == PL_C_locale_obj) {
1010         old_obj = (locale_t) 0;
1011     }
1012
1013     /* Ready to create a new locale by modification of the exising one */
1014     new_obj = newlocale(mask, locale, old_obj);
1015
1016     if (! new_obj) {
1017         dSAVE_ERRNO;
1018
1019 #  ifdef DEBUGGING
1020
1021         if (DEBUG_L_TEST || debug_initialization) {
1022             PerlIO_printf(Perl_debug_log, "%s:%d: emulate_setlocale creating new object failed: %d\n", __FILE__, __LINE__, GET_ERRNO);
1023         }
1024
1025 #  endif
1026
1027         if (! uselocale(old_obj)) {
1028
1029 #  ifdef DEBUGGING
1030
1031             if (DEBUG_L_TEST || debug_initialization) {
1032                 PerlIO_printf(Perl_debug_log, "%s:%d: switching back failed: %d\n", __FILE__, __LINE__, GET_ERRNO);
1033             }
1034
1035 #  endif
1036
1037         }
1038         RESTORE_ERRNO;
1039         return NULL;
1040     }
1041
1042 #  ifdef DEBUGGING
1043
1044     if (DEBUG_Lv_TEST || debug_initialization) {
1045         PerlIO_printf(Perl_debug_log, "%s:%d: emulate_setlocale created %p; should have freed %p\n", __FILE__, __LINE__, new_obj, old_obj);
1046     }
1047
1048 #  endif
1049
1050     /* And switch into it */
1051     if (! uselocale(new_obj)) {
1052         dSAVE_ERRNO;
1053
1054 #  ifdef DEBUGGING
1055
1056         if (DEBUG_L_TEST || debug_initialization) {
1057             PerlIO_printf(Perl_debug_log, "%s:%d: emulate_setlocale switching to new object failed\n", __FILE__, __LINE__);
1058         }
1059
1060 #  endif
1061
1062         if (! uselocale(old_obj)) {
1063
1064 #  ifdef DEBUGGING
1065
1066             if (DEBUG_L_TEST || debug_initialization) {
1067                 PerlIO_printf(Perl_debug_log, "%s:%d: switching back failed: %d\n", __FILE__, __LINE__, GET_ERRNO);
1068             }
1069
1070 #  endif
1071
1072         }
1073         freelocale(new_obj);
1074         RESTORE_ERRNO;
1075         return NULL;
1076     }
1077
1078 #  ifdef DEBUGGING
1079
1080     if (DEBUG_Lv_TEST || debug_initialization) {
1081         PerlIO_printf(Perl_debug_log, "%s:%d: emulate_setlocale now using %p\n", __FILE__, __LINE__, new_obj);
1082     }
1083
1084 #  endif
1085
1086     /* We are done, except for updating our records (if the system doesn't keep
1087      * them) and in the case of locale "", we don't actually know what the
1088      * locale that got switched to is, as it came from the environment.  So
1089      * have to find it */
1090
1091 #  ifdef HAS_QUERYLOCALE
1092
1093     if (strEQ(locale, "")) {
1094         locale = querylocale(mask, new_obj);
1095     }
1096
1097 #  else
1098
1099     /* Here, 'locale' is the return value */
1100
1101     /* Without querylocale(), we have to update our records */
1102
1103     if (category == LC_ALL) {
1104         unsigned int i;
1105
1106         /* For LC_ALL, we change all individual categories to correspond */
1107                               /* PL_curlocales is a parallel array, so has same
1108                                * length as 'categories' */
1109         for (i = 0; i <= LC_ALL_INDEX; i++) {
1110             Safefree(PL_curlocales[i]);
1111             PL_curlocales[i] = savepv(locale);
1112         }
1113     }
1114     else {
1115
1116         /* For a single category, if it's not the same as the one in LC_ALL, we
1117          * nullify LC_ALL */
1118
1119         if (PL_curlocales[LC_ALL_INDEX] && strNE(PL_curlocales[LC_ALL_INDEX], locale)) {
1120             Safefree(PL_curlocales[LC_ALL_INDEX]);
1121             PL_curlocales[LC_ALL_INDEX] = NULL;
1122         }
1123
1124         /* Then update the category's record */
1125         Safefree(PL_curlocales[index]);
1126         PL_curlocales[index] = savepv(locale);
1127     }
1128
1129 #  endif
1130
1131     return locale;
1132 }
1133
1134 #endif /* USE_POSIX_2008_LOCALE */
1135
1136 #if 0   /* Code that was to emulate thread-safe locales on platforms that
1137            didn't natively support them */
1138
1139 /* The way this would work is that we would keep a per-thread list of the
1140  * correct locale for that thread.  Any operation that was locale-sensitive
1141  * would have to be changed so that it would look like this:
1142  *
1143  *      LOCALE_LOCK;
1144  *      setlocale to the correct locale for this operation
1145  *      do operation
1146  *      LOCALE_UNLOCK
1147  *
1148  * This leaves the global locale in the most recently used operation's, but it
1149  * was locked long enough to get the result.  If that result is static, it
1150  * needs to be copied before the unlock.
1151  *
1152  * Macros could be written like SETUP_LOCALE_DEPENDENT_OP(category) that did
1153  * the setup, but are no-ops when not needed, and similarly,
1154  * END_LOCALE_DEPENDENT_OP for the tear-down
1155  *
1156  * But every call to a locale-sensitive function would have to be changed, and
1157  * if a module didn't cooperate by using the mutex, things would break.
1158  *
1159  * This code was abandoned before being completed or tested, and is left as-is
1160 */
1161
1162 #  define do_setlocale_c(cat, locale) locking_setlocale(cat, locale, cat ## _INDEX, TRUE)
1163 #  define do_setlocale_r(cat, locale) locking_setlocale(cat, locale, 0, FALSE)
1164
1165 STATIC char *
1166 S_locking_setlocale(pTHX_
1167                     const int category,
1168                     const char * locale,
1169                     int index,
1170                     const bool is_index_valid
1171                    )
1172 {
1173     /* This function kind of performs a setlocale() on just the current thread;
1174      * thus it is kind of thread-safe.  It does this by keeping a thread-level
1175      * array of the current locales for each category.  Every time a locale is
1176      * switched to, it does the switch globally, but updates the thread's
1177      * array.  A query as to what the current locale is just returns the
1178      * appropriate element from the array, and doesn't actually call the system
1179      * setlocale().  The saving into the array is done in an uninterruptible
1180      * section of code, so is unaffected by whatever any other threads might be
1181      * doing.
1182      *
1183      * All locale-sensitive operations must work by first starting a critical
1184      * section, then switching to the thread's locale as kept by this function,
1185      * and then doing the operation, then ending the critical section.  Thus,
1186      * each gets done in the appropriate locale. simulating thread-safety.
1187      *
1188      * This function takes the same parameters, 'category' and 'locale', that
1189      * the regular setlocale() function does, but it also takes two additional
1190      * ones.  This is because as described earlier.  If we know on input the
1191      * index corresponding to the category into the array where we store the
1192      * current locales, we don't have to calculate it.  If the caller knows at
1193      * compile time what the index is, it it can pass it, setting
1194      * 'is_index_valid' to TRUE; otherwise the index parameter is ignored.
1195      *
1196      */
1197
1198     /* If the input index might be incorrect, calculate the correct one */
1199     if (! is_index_valid) {
1200         unsigned int i;
1201
1202         if (DEBUG_Lv_TEST || debug_initialization) {
1203             PerlIO_printf(Perl_debug_log, "%s:%d: converting category %d to index\n", __FILE__, __LINE__, category);
1204         }
1205
1206         for (i = 0; i <= LC_ALL_INDEX; i++) {
1207             if (category == categories[i]) {
1208                 index = i;
1209                 goto found_index;
1210             }
1211         }
1212
1213         /* Here, we don't know about this category, so can't handle it.
1214          * XXX best we can do is to unsafely set this
1215          * XXX warning */
1216
1217         return my_setlocale(category, locale);
1218
1219       found_index: ;
1220
1221         if (DEBUG_Lv_TEST || debug_initialization) {
1222             PerlIO_printf(Perl_debug_log, "%s:%d: index is 0x%x\n", __FILE__, __LINE__, index);
1223         }
1224     }
1225
1226     /* For a query, just return what's in our records */
1227     if (new_locale == NULL) {
1228         return curlocales[index];
1229     }
1230
1231
1232     /* Otherwise, we need to do the switch, and save the result, all in a
1233      * critical section */
1234
1235     Safefree(curlocales[[index]]);
1236
1237     /* It might be that this is called from an already-locked section of code.
1238      * We would have to detect and skip the LOCK/UNLOCK if so */
1239     LOCALE_LOCK;
1240
1241     curlocales[index] = savepv(my_setlocale(category, new_locale));
1242
1243     if (strEQ(new_locale, "")) {
1244
1245 #ifdef LC_ALL
1246
1247         /* The locale values come from the environment, and may not all be the
1248          * same, so for LC_ALL, we have to update all the others, while the
1249          * mutex is still locked */
1250
1251         if (category == LC_ALL) {
1252             unsigned int i;
1253             for (i = 0; i < LC_ALL_INDEX) {
1254                 curlocales[i] = my_setlocale(categories[i], NULL);
1255             }
1256         }
1257     }
1258
1259 #endif
1260
1261     LOCALE_UNLOCK;
1262
1263     return curlocales[index];
1264 }
1265
1266 #endif
1267 #ifdef USE_LOCALE
1268
1269 STATIC void
1270 S_set_numeric_radix(pTHX_ const bool use_locale)
1271 {
1272     /* If 'use_locale' is FALSE, set to use a dot for the radix character.  If
1273      * TRUE, use the radix character derived from the current locale */
1274
1275 #if defined(USE_LOCALE_NUMERIC) && (   defined(HAS_LOCALECONV)              \
1276                                     || defined(HAS_NL_LANGINFO))
1277
1278     const char * radix = (use_locale)
1279                          ? my_nl_langinfo(RADIXCHAR, FALSE)
1280                                         /* FALSE => already in dest locale */
1281                          : ".";
1282
1283         sv_setpv(PL_numeric_radix_sv, radix);
1284
1285     /* If this is valid UTF-8 that isn't totally ASCII, and we are in
1286         * a UTF-8 locale, then mark the radix as being in UTF-8 */
1287     if (is_utf8_non_invariant_string((U8 *) SvPVX(PL_numeric_radix_sv),
1288                                             SvCUR(PL_numeric_radix_sv))
1289         && _is_cur_LC_category_utf8(LC_NUMERIC))
1290     {
1291         SvUTF8_on(PL_numeric_radix_sv);
1292     }
1293
1294 #  ifdef DEBUGGING
1295
1296     if (DEBUG_L_TEST || debug_initialization) {
1297         PerlIO_printf(Perl_debug_log, "Locale radix is '%s', ?UTF-8=%d\n",
1298                                            SvPVX(PL_numeric_radix_sv),
1299                                            cBOOL(SvUTF8(PL_numeric_radix_sv)));
1300     }
1301
1302 #  endif
1303 #else
1304
1305     PERL_UNUSED_ARG(use_locale);
1306
1307 #endif /* USE_LOCALE_NUMERIC and can find the radix char */
1308
1309 }
1310
1311 STATIC void
1312 S_new_numeric(pTHX_ const char *newnum)
1313 {
1314
1315 #ifndef USE_LOCALE_NUMERIC
1316
1317     PERL_UNUSED_ARG(newnum);
1318
1319 #else
1320
1321     /* Called after each libc setlocale() call affecting LC_NUMERIC, to tell
1322      * core Perl this and that 'newnum' is the name of the new locale.
1323      * It installs this locale as the current underlying default.
1324      *
1325      * The default locale and the C locale can be toggled between by use of the
1326      * set_numeric_underlying() and set_numeric_standard() functions, which
1327      * should probably not be called directly, but only via macros like
1328      * SET_NUMERIC_STANDARD() in perl.h.
1329      *
1330      * The toggling is necessary mainly so that a non-dot radix decimal point
1331      * character can be output, while allowing internal calculations to use a
1332      * dot.
1333      *
1334      * This sets several interpreter-level variables:
1335      * PL_numeric_name  The underlying locale's name: a copy of 'newnum'
1336      * PL_numeric_underlying  A boolean indicating if the toggled state is such
1337      *                  that the current locale is the program's underlying
1338      *                  locale
1339      * PL_numeric_standard An int indicating if the toggled state is such
1340      *                  that the current locale is the C locale or
1341      *                  indistinguishable from the C locale.  If non-zero, it
1342      *                  is in C; if > 1, it means it may not be toggled away
1343      *                  from C.
1344      * PL_numeric_underlying_is_standard   A bool kept by this function
1345      *                  indicating that the underlying locale and the standard
1346      *                  C locale are indistinguishable for the purposes of
1347      *                  LC_NUMERIC.  This happens when both of the above two
1348      *                  variables are true at the same time.  (Toggling is a
1349      *                  no-op under these circumstances.)  This variable is
1350      *                  used to avoid having to recalculate.
1351      */
1352
1353     char *save_newnum;
1354
1355     if (! newnum) {
1356         Safefree(PL_numeric_name);
1357         PL_numeric_name = NULL;
1358         PL_numeric_standard = TRUE;
1359         PL_numeric_underlying = TRUE;
1360         PL_numeric_underlying_is_standard = TRUE;
1361         return;
1362     }
1363
1364     save_newnum = stdize_locale(savepv(newnum));
1365     PL_numeric_underlying = TRUE;
1366     PL_numeric_standard = isNAME_C_OR_POSIX(save_newnum);
1367
1368 #ifndef TS_W32_BROKEN_LOCALECONV
1369
1370     /* If its name isn't C nor POSIX, it could still be indistinguishable from
1371      * them.  But on broken Windows systems calling my_nl_langinfo() for
1372      * THOUSEP can currently (but rarely) cause a race, so avoid doing that,
1373      * and just always change the locale if not C nor POSIX on those systems */
1374     if (! PL_numeric_standard) {
1375         PL_numeric_standard = cBOOL(strEQ(".", my_nl_langinfo(RADIXCHAR,
1376                                             FALSE /* Don't toggle locale */  ))
1377                                  && strEQ("",  my_nl_langinfo(THOUSEP, FALSE)));
1378     }
1379
1380 #endif
1381
1382     /* Save the new name if it isn't the same as the previous one, if any */
1383     if (! PL_numeric_name || strNE(PL_numeric_name, save_newnum)) {
1384         Safefree(PL_numeric_name);
1385         PL_numeric_name = save_newnum;
1386     }
1387     else {
1388         Safefree(save_newnum);
1389     }
1390
1391     PL_numeric_underlying_is_standard = PL_numeric_standard;
1392
1393 #  ifdef HAS_POSIX_2008_LOCALE
1394
1395     PL_underlying_numeric_obj = newlocale(LC_NUMERIC_MASK,
1396                                           PL_numeric_name,
1397                                           PL_underlying_numeric_obj);
1398
1399 #endif
1400
1401     if (DEBUG_L_TEST || debug_initialization) {
1402         PerlIO_printf(Perl_debug_log, "Called new_numeric with %s, PL_numeric_name=%s\n", newnum, PL_numeric_name);
1403     }
1404
1405     /* Keep LC_NUMERIC in the C locale.  This is for XS modules, so they don't
1406      * have to worry about the radix being a non-dot.  (Core operations that
1407      * need the underlying locale change to it temporarily). */
1408     if (PL_numeric_standard) {
1409         set_numeric_radix(0);
1410     }
1411     else {
1412         set_numeric_standard();
1413     }
1414
1415 #endif /* USE_LOCALE_NUMERIC */
1416
1417 }
1418
1419 void
1420 Perl_set_numeric_standard(pTHX)
1421 {
1422
1423 #ifdef USE_LOCALE_NUMERIC
1424
1425     /* Toggle the LC_NUMERIC locale to C.  Most code should use the macros like
1426      * SET_NUMERIC_STANDARD() in perl.h instead of calling this directly.  The
1427      * macro avoids calling this routine if toggling isn't necessary according
1428      * to our records (which could be wrong if some XS code has changed the
1429      * locale behind our back) */
1430
1431 #  ifdef DEBUGGING
1432
1433     if (DEBUG_L_TEST || debug_initialization) {
1434         PerlIO_printf(Perl_debug_log,
1435                           "Setting LC_NUMERIC locale to standard C\n");
1436     }
1437
1438 #  endif
1439
1440     do_setlocale_c(LC_NUMERIC, "C");
1441     PL_numeric_standard = TRUE;
1442     PL_numeric_underlying = PL_numeric_underlying_is_standard;
1443     set_numeric_radix(0);
1444
1445 #endif /* USE_LOCALE_NUMERIC */
1446
1447 }
1448
1449 void
1450 Perl_set_numeric_underlying(pTHX)
1451 {
1452
1453 #ifdef USE_LOCALE_NUMERIC
1454
1455     /* Toggle the LC_NUMERIC locale to the current underlying default.  Most
1456      * code should use the macros like SET_NUMERIC_UNDERLYING() in perl.h
1457      * instead of calling this directly.  The macro avoids calling this routine
1458      * if toggling isn't necessary according to our records (which could be
1459      * wrong if some XS code has changed the locale behind our back) */
1460
1461 #  ifdef DEBUGGING
1462
1463     if (DEBUG_L_TEST || debug_initialization) {
1464         PerlIO_printf(Perl_debug_log,
1465                           "Setting LC_NUMERIC locale to %s\n",
1466                           PL_numeric_name);
1467     }
1468
1469 #  endif
1470
1471     do_setlocale_c(LC_NUMERIC, PL_numeric_name);
1472     PL_numeric_standard = PL_numeric_underlying_is_standard;
1473     PL_numeric_underlying = TRUE;
1474     set_numeric_radix(! PL_numeric_standard);
1475
1476 #endif /* USE_LOCALE_NUMERIC */
1477
1478 }
1479
1480 /*
1481  * Set up for a new ctype locale.
1482  */
1483 STATIC void
1484 S_new_ctype(pTHX_ const char *newctype)
1485 {
1486
1487 #ifndef USE_LOCALE_CTYPE
1488
1489     PERL_UNUSED_ARG(newctype);
1490     PERL_UNUSED_CONTEXT;
1491
1492 #else
1493
1494     /* Called after each libc setlocale() call affecting LC_CTYPE, to tell
1495      * core Perl this and that 'newctype' is the name of the new locale.
1496      *
1497      * This function sets up the folding arrays for all 256 bytes, assuming
1498      * that tofold() is tolc() since fold case is not a concept in POSIX,
1499      *
1500      * Any code changing the locale (outside this file) should use
1501      * Perl_setlocale or POSIX::setlocale, which call this function.  Therefore
1502      * this function should be called directly only from this file and from
1503      * POSIX::setlocale() */
1504
1505     dVAR;
1506     unsigned int i;
1507
1508     /* Don't check for problems if we are suppressing the warnings */
1509     bool check_for_problems = ckWARN_d(WARN_LOCALE) || UNLIKELY(DEBUG_L_TEST);
1510
1511     PERL_ARGS_ASSERT_NEW_CTYPE;
1512
1513     /* We will replace any bad locale warning with 1) nothing if the new one is
1514      * ok; or 2) a new warning for the bad new locale */
1515     if (PL_warn_locale) {
1516         SvREFCNT_dec_NN(PL_warn_locale);
1517         PL_warn_locale = NULL;
1518     }
1519
1520     PL_in_utf8_CTYPE_locale = _is_cur_LC_category_utf8(LC_CTYPE);
1521
1522     /* A UTF-8 locale gets standard rules.  But note that code still has to
1523      * handle this specially because of the three problematic code points */
1524     if (PL_in_utf8_CTYPE_locale) {
1525         Copy(PL_fold_latin1, PL_fold_locale, 256, U8);
1526     }
1527
1528     /* We don't populate the other lists if a UTF-8 locale, but do check that
1529      * everything works as expected, unless checking turned off */
1530     if (check_for_problems || ! PL_in_utf8_CTYPE_locale) {
1531         /* Assume enough space for every character being bad.  4 spaces each
1532          * for the 94 printable characters that are output like "'x' "; and 5
1533          * spaces each for "'\\' ", "'\t' ", and "'\n' "; plus a terminating
1534          * NUL */
1535         char bad_chars_list[ (94 * 4) + (3 * 5) + 1 ] = { '\0' };
1536         bool multi_byte_locale = FALSE;     /* Assume is a single-byte locale
1537                                                to start */
1538         unsigned int bad_count = 0;         /* Count of bad characters */
1539
1540         for (i = 0; i < 256; i++) {
1541             if (! PL_in_utf8_CTYPE_locale) {
1542                 if (isupper(i))
1543                     PL_fold_locale[i] = (U8) tolower(i);
1544                 else if (islower(i))
1545                     PL_fold_locale[i] = (U8) toupper(i);
1546                 else
1547                     PL_fold_locale[i] = (U8) i;
1548             }
1549
1550             /* If checking for locale problems, see if the native ASCII-range
1551              * printables plus \n and \t are in their expected categories in
1552              * the new locale.  If not, this could mean big trouble, upending
1553              * Perl's and most programs' assumptions, like having a
1554              * metacharacter with special meaning become a \w.  Fortunately,
1555              * it's very rare to find locales that aren't supersets of ASCII
1556              * nowadays.  It isn't a problem for most controls to be changed
1557              * into something else; we check only \n and \t, though perhaps \r
1558              * could be an issue as well. */
1559             if (    check_for_problems
1560                 && (isGRAPH_A(i) || isBLANK_A(i) || i == '\n'))
1561             {
1562                 bool is_bad = FALSE;
1563                 char name[4] = { '\0' };
1564
1565                 /* Convert the name into a string */
1566                 if (isGRAPH_A(i)) {
1567                     name[0] = i;
1568                     name[1] = '\0';
1569                 }
1570                 else if (i == '\n') {
1571                     my_strlcpy(name, "\\n", sizeof(name));
1572                 }
1573                 else if (i == '\t') {
1574                     my_strlcpy(name, "\\t", sizeof(name));
1575                 }
1576                 else {
1577                     assert(i == ' ');
1578                     my_strlcpy(name, "' '", sizeof(name));
1579                 }
1580
1581                 /* Check each possibe class */
1582                 if (UNLIKELY(cBOOL(isalnum(i)) != cBOOL(isALPHANUMERIC_A(i))))  {
1583                     is_bad = TRUE;
1584                     DEBUG_L(PerlIO_printf(Perl_debug_log,
1585                                           "isalnum('%s') unexpectedly is %d\n",
1586                                           name, cBOOL(isalnum(i))));
1587                 }
1588                 if (UNLIKELY(cBOOL(isalpha(i)) != cBOOL(isALPHA_A(i))))  {
1589                     is_bad = TRUE;
1590                     DEBUG_L(PerlIO_printf(Perl_debug_log,
1591                                           "isalpha('%s') unexpectedly is %d\n",
1592                                           name, cBOOL(isalpha(i))));
1593                 }
1594                 if (UNLIKELY(cBOOL(isdigit(i)) != cBOOL(isDIGIT_A(i))))  {
1595                     is_bad = TRUE;
1596                     DEBUG_L(PerlIO_printf(Perl_debug_log,
1597                                           "isdigit('%s') unexpectedly is %d\n",
1598                                           name, cBOOL(isdigit(i))));
1599                 }
1600                 if (UNLIKELY(cBOOL(isgraph(i)) != cBOOL(isGRAPH_A(i))))  {
1601                     is_bad = TRUE;
1602                     DEBUG_L(PerlIO_printf(Perl_debug_log,
1603                                           "isgraph('%s') unexpectedly is %d\n",
1604                                           name, cBOOL(isgraph(i))));
1605                 }
1606                 if (UNLIKELY(cBOOL(islower(i)) != cBOOL(isLOWER_A(i))))  {
1607                     is_bad = TRUE;
1608                     DEBUG_L(PerlIO_printf(Perl_debug_log,
1609                                           "islower('%s') unexpectedly is %d\n",
1610                                           name, cBOOL(islower(i))));
1611                 }
1612                 if (UNLIKELY(cBOOL(isprint(i)) != cBOOL(isPRINT_A(i))))  {
1613                     is_bad = TRUE;
1614                     DEBUG_L(PerlIO_printf(Perl_debug_log,
1615                                           "isprint('%s') unexpectedly is %d\n",
1616                                           name, cBOOL(isprint(i))));
1617                 }
1618                 if (UNLIKELY(cBOOL(ispunct(i)) != cBOOL(isPUNCT_A(i))))  {
1619                     is_bad = TRUE;
1620                     DEBUG_L(PerlIO_printf(Perl_debug_log,
1621                                           "ispunct('%s') unexpectedly is %d\n",
1622                                           name, cBOOL(ispunct(i))));
1623                 }
1624                 if (UNLIKELY(cBOOL(isspace(i)) != cBOOL(isSPACE_A(i))))  {
1625                     is_bad = TRUE;
1626                     DEBUG_L(PerlIO_printf(Perl_debug_log,
1627                                           "isspace('%s') unexpectedly is %d\n",
1628                                           name, cBOOL(isspace(i))));
1629                 }
1630                 if (UNLIKELY(cBOOL(isupper(i)) != cBOOL(isUPPER_A(i))))  {
1631                     is_bad = TRUE;
1632                     DEBUG_L(PerlIO_printf(Perl_debug_log,
1633                                           "isupper('%s') unexpectedly is %d\n",
1634                                           name, cBOOL(isupper(i))));
1635                 }
1636                 if (UNLIKELY(cBOOL(isxdigit(i))!= cBOOL(isXDIGIT_A(i))))  {
1637                     is_bad = TRUE;
1638                     DEBUG_L(PerlIO_printf(Perl_debug_log,
1639                                           "isxdigit('%s') unexpectedly is %d\n",
1640                                           name, cBOOL(isxdigit(i))));
1641                 }
1642                 if (UNLIKELY(tolower(i) != (int) toLOWER_A(i)))  {
1643                     is_bad = TRUE;
1644                     DEBUG_L(PerlIO_printf(Perl_debug_log,
1645                             "tolower('%s')=0x%x instead of the expected 0x%x\n",
1646                             name, tolower(i), (int) toLOWER_A(i)));
1647                 }
1648                 if (UNLIKELY(toupper(i) != (int) toUPPER_A(i)))  {
1649                     is_bad = TRUE;
1650                     DEBUG_L(PerlIO_printf(Perl_debug_log,
1651                             "toupper('%s')=0x%x instead of the expected 0x%x\n",
1652                             name, toupper(i), (int) toUPPER_A(i)));
1653                 }
1654                 if (UNLIKELY((i == '\n' && ! isCNTRL_LC(i))))  {
1655                     is_bad = TRUE;
1656                     DEBUG_L(PerlIO_printf(Perl_debug_log,
1657                                 "'\\n' (=%02X) is not a control\n", (int) i));
1658                 }
1659
1660                 /* Add to the list;  Separate multiple entries with a blank */
1661                 if (is_bad) {
1662                     if (bad_count) {
1663                         my_strlcat(bad_chars_list, " ", sizeof(bad_chars_list));
1664                     }
1665                     my_strlcat(bad_chars_list, name, sizeof(bad_chars_list));
1666                     bad_count++;
1667                 }
1668             }
1669         }
1670
1671 #  ifdef MB_CUR_MAX
1672
1673         /* We only handle single-byte locales (outside of UTF-8 ones; so if
1674          * this locale requires more than one byte, there are going to be
1675          * problems. */
1676         DEBUG_Lv(PerlIO_printf(Perl_debug_log,
1677                  "%s:%d: check_for_problems=%d, MB_CUR_MAX=%d\n",
1678                  __FILE__, __LINE__, check_for_problems, (int) MB_CUR_MAX));
1679
1680         if (   check_for_problems && MB_CUR_MAX > 1
1681             && ! PL_in_utf8_CTYPE_locale
1682
1683                /* Some platforms return MB_CUR_MAX > 1 for even the "C"
1684                 * locale.  Just assume that the implementation for them (plus
1685                 * for POSIX) is correct and the > 1 value is spurious.  (Since
1686                 * these are specially handled to never be considered UTF-8
1687                 * locales, as long as this is the only problem, everything
1688                 * should work fine */
1689             && strNE(newctype, "C") && strNE(newctype, "POSIX"))
1690         {
1691             multi_byte_locale = TRUE;
1692         }
1693
1694 #  endif
1695
1696         if (UNLIKELY(bad_count) || UNLIKELY(multi_byte_locale)) {
1697             if (UNLIKELY(bad_count) && PL_in_utf8_CTYPE_locale) {
1698                 PL_warn_locale = Perl_newSVpvf(aTHX_
1699                      "Locale '%s' contains (at least) the following characters"
1700                      " which have\nunexpected meanings: %s\nThe Perl program"
1701                      " will use the expected meanings",
1702                       newctype, bad_chars_list);
1703             }
1704             else {
1705                 PL_warn_locale = Perl_newSVpvf(aTHX_
1706                              "Locale '%s' may not work well.%s%s%s\n",
1707                              newctype,
1708                              (multi_byte_locale)
1709                               ? "  Some characters in it are not recognized by"
1710                                 " Perl."
1711                               : "",
1712                              (bad_count)
1713                               ? "\nThe following characters (and maybe others)"
1714                                 " may not have the same meaning as the Perl"
1715                                 " program expects:\n"
1716                               : "",
1717                              (bad_count)
1718                               ? bad_chars_list
1719                               : ""
1720                             );
1721             }
1722
1723 #  ifdef HAS_NL_LANGINFO
1724
1725             Perl_sv_catpvf(aTHX_ PL_warn_locale, "; codeset=%s",
1726                                     /* parameter FALSE is a don't care here */
1727                                     my_nl_langinfo(CODESET, FALSE));
1728
1729 #  endif
1730
1731             Perl_sv_catpvf(aTHX_ PL_warn_locale, "\n");
1732
1733             /* If we are actually in the scope of the locale or are debugging,
1734              * output the message now.  If not in that scope, we save the
1735              * message to be output at the first operation using this locale,
1736              * if that actually happens.  Most programs don't use locales, so
1737              * they are immune to bad ones.  */
1738             if (IN_LC(LC_CTYPE) || UNLIKELY(DEBUG_L_TEST)) {
1739
1740                 /* The '0' below suppresses a bogus gcc compiler warning */
1741                 Perl_warner(aTHX_ packWARN(WARN_LOCALE), SvPVX(PL_warn_locale), 0);
1742
1743                 if (IN_LC(LC_CTYPE)) {
1744                     SvREFCNT_dec_NN(PL_warn_locale);
1745                     PL_warn_locale = NULL;
1746                 }
1747             }
1748         }
1749     }
1750
1751 #endif /* USE_LOCALE_CTYPE */
1752
1753 }
1754
1755 void
1756 Perl__warn_problematic_locale()
1757 {
1758
1759 #ifdef USE_LOCALE_CTYPE
1760
1761     dTHX;
1762
1763     /* Internal-to-core function that outputs the message in PL_warn_locale,
1764      * and then NULLS it.  Should be called only through the macro
1765      * _CHECK_AND_WARN_PROBLEMATIC_LOCALE */
1766
1767     if (PL_warn_locale) {
1768         Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
1769                              SvPVX(PL_warn_locale),
1770                              0 /* dummy to avoid compiler warning */ );
1771         SvREFCNT_dec_NN(PL_warn_locale);
1772         PL_warn_locale = NULL;
1773     }
1774
1775 #endif
1776
1777 }
1778
1779 STATIC void
1780 S_new_collate(pTHX_ const char *newcoll)
1781 {
1782
1783 #ifndef USE_LOCALE_COLLATE
1784
1785     PERL_UNUSED_ARG(newcoll);
1786     PERL_UNUSED_CONTEXT;
1787
1788 #else
1789
1790     /* Called after each libc setlocale() call affecting LC_COLLATE, to tell
1791      * core Perl this and that 'newcoll' is the name of the new locale.
1792      *
1793      * The design of locale collation is that every locale change is given an
1794      * index 'PL_collation_ix'.  The first time a string particpates in an
1795      * operation that requires collation while locale collation is active, it
1796      * is given PERL_MAGIC_collxfrm magic (via sv_collxfrm_flags()).  That
1797      * magic includes the collation index, and the transformation of the string
1798      * by strxfrm(), q.v.  That transformation is used when doing comparisons,
1799      * instead of the string itself.  If a string changes, the magic is
1800      * cleared.  The next time the locale changes, the index is incremented,
1801      * and so we know during a comparison that the transformation is not
1802      * necessarily still valid, and so is recomputed.  Note that if the locale
1803      * changes enough times, the index could wrap (a U32), and it is possible
1804      * that a transformation would improperly be considered valid, leading to
1805      * an unlikely bug */
1806
1807     if (! newcoll) {
1808         if (PL_collation_name) {
1809             ++PL_collation_ix;
1810             Safefree(PL_collation_name);
1811             PL_collation_name = NULL;
1812         }
1813         PL_collation_standard = TRUE;
1814       is_standard_collation:
1815         PL_collxfrm_base = 0;
1816         PL_collxfrm_mult = 2;
1817         PL_in_utf8_COLLATE_locale = FALSE;
1818         PL_strxfrm_NUL_replacement = '\0';
1819         PL_strxfrm_max_cp = 0;
1820         return;
1821     }
1822
1823     /* If this is not the same locale as currently, set the new one up */
1824     if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
1825         ++PL_collation_ix;
1826         Safefree(PL_collation_name);
1827         PL_collation_name = stdize_locale(savepv(newcoll));
1828         PL_collation_standard = isNAME_C_OR_POSIX(newcoll);
1829         if (PL_collation_standard) {
1830             goto is_standard_collation;
1831         }
1832
1833         PL_in_utf8_COLLATE_locale = _is_cur_LC_category_utf8(LC_COLLATE);
1834         PL_strxfrm_NUL_replacement = '\0';
1835         PL_strxfrm_max_cp = 0;
1836
1837         /* A locale collation definition includes primary, secondary, tertiary,
1838          * etc. weights for each character.  To sort, the primary weights are
1839          * used, and only if they compare equal, then the secondary weights are
1840          * used, and only if they compare equal, then the tertiary, etc.
1841          *
1842          * strxfrm() works by taking the input string, say ABC, and creating an
1843          * output transformed string consisting of first the primary weights,
1844          * A¹B¹C¹ followed by the secondary ones, A²B²C²; and then the
1845          * tertiary, etc, yielding A¹B¹C¹ A²B²C² A³B³C³ ....  Some characters
1846          * may not have weights at every level.  In our example, let's say B
1847          * doesn't have a tertiary weight, and A doesn't have a secondary
1848          * weight.  The constructed string is then going to be
1849          *  A¹B¹C¹ B²C² A³C³ ....
1850          * This has the desired effect that strcmp() will look at the secondary
1851          * or tertiary weights only if the strings compare equal at all higher
1852          * priority weights.  The spaces shown here, like in
1853          *  "A¹B¹C¹ A²B²C² "
1854          * are not just for readability.  In the general case, these must
1855          * actually be bytes, which we will call here 'separator weights'; and
1856          * they must be smaller than any other weight value, but since these
1857          * are C strings, only the terminating one can be a NUL (some
1858          * implementations may include a non-NUL separator weight just before
1859          * the NUL).  Implementations tend to reserve 01 for the separator
1860          * weights.  They are needed so that a shorter string's secondary
1861          * weights won't be misconstrued as primary weights of a longer string,
1862          * etc.  By making them smaller than any other weight, the shorter
1863          * string will sort first.  (Actually, if all secondary weights are
1864          * smaller than all primary ones, there is no need for a separator
1865          * weight between those two levels, etc.)
1866          *
1867          * The length of the transformed string is roughly a linear function of
1868          * the input string.  It's not exactly linear because some characters
1869          * don't have weights at all levels.  When we call strxfrm() we have to
1870          * allocate some memory to hold the transformed string.  The
1871          * calculations below try to find coefficients 'm' and 'b' for this
1872          * locale so that m*x + b equals how much space we need, given the size
1873          * of the input string in 'x'.  If we calculate too small, we increase
1874          * the size as needed, and call strxfrm() again, but it is better to
1875          * get it right the first time to avoid wasted expensive string
1876          * transformations. */
1877
1878         {
1879             /* We use the string below to find how long the tranformation of it
1880              * is.  Almost all locales are supersets of ASCII, or at least the
1881              * ASCII letters.  We use all of them, half upper half lower,
1882              * because if we used fewer, we might hit just the ones that are
1883              * outliers in a particular locale.  Most of the strings being
1884              * collated will contain a preponderance of letters, and even if
1885              * they are above-ASCII, they are likely to have the same number of
1886              * weight levels as the ASCII ones.  It turns out that digits tend
1887              * to have fewer levels, and some punctuation has more, but those
1888              * are relatively sparse in text, and khw believes this gives a
1889              * reasonable result, but it could be changed if experience so
1890              * dictates. */
1891             const char longer[] = "ABCDEFGHIJKLMnopqrstuvwxyz";
1892             char * x_longer;        /* Transformed 'longer' */
1893             Size_t x_len_longer;    /* Length of 'x_longer' */
1894
1895             char * x_shorter;   /* We also transform a substring of 'longer' */
1896             Size_t x_len_shorter;
1897
1898             /* _mem_collxfrm() is used get the transformation (though here we
1899              * are interested only in its length).  It is used because it has
1900              * the intelligence to handle all cases, but to work, it needs some
1901              * values of 'm' and 'b' to get it started.  For the purposes of
1902              * this calculation we use a very conservative estimate of 'm' and
1903              * 'b'.  This assumes a weight can be multiple bytes, enough to
1904              * hold any UV on the platform, and there are 5 levels, 4 weight
1905              * bytes, and a trailing NUL.  */
1906             PL_collxfrm_base = 5;
1907             PL_collxfrm_mult = 5 * sizeof(UV);
1908
1909             /* Find out how long the transformation really is */
1910             x_longer = _mem_collxfrm(longer,
1911                                      sizeof(longer) - 1,
1912                                      &x_len_longer,
1913
1914                                      /* We avoid converting to UTF-8 in the
1915                                       * called function by telling it the
1916                                       * string is in UTF-8 if the locale is a
1917                                       * UTF-8 one.  Since the string passed
1918                                       * here is invariant under UTF-8, we can
1919                                       * claim it's UTF-8 even though it isn't.
1920                                       * */
1921                                      PL_in_utf8_COLLATE_locale);
1922             Safefree(x_longer);
1923
1924             /* Find out how long the transformation of a substring of 'longer'
1925              * is.  Together the lengths of these transformations are
1926              * sufficient to calculate 'm' and 'b'.  The substring is all of
1927              * 'longer' except the first character.  This minimizes the chances
1928              * of being swayed by outliers */
1929             x_shorter = _mem_collxfrm(longer + 1,
1930                                       sizeof(longer) - 2,
1931                                       &x_len_shorter,
1932                                       PL_in_utf8_COLLATE_locale);
1933             Safefree(x_shorter);
1934
1935             /* If the results are nonsensical for this simple test, the whole
1936              * locale definition is suspect.  Mark it so that locale collation
1937              * is not active at all for it.  XXX Should we warn? */
1938             if (   x_len_shorter == 0
1939                 || x_len_longer == 0
1940                 || x_len_shorter >= x_len_longer)
1941             {
1942                 PL_collxfrm_mult = 0;
1943                 PL_collxfrm_base = 0;
1944             }
1945             else {
1946                 SSize_t base;       /* Temporary */
1947
1948                 /* We have both:    m * strlen(longer)  + b = x_len_longer
1949                  *                  m * strlen(shorter) + b = x_len_shorter;
1950                  * subtracting yields:
1951                  *          m * (strlen(longer) - strlen(shorter))
1952                  *                             = x_len_longer - x_len_shorter
1953                  * But we have set things up so that 'shorter' is 1 byte smaller
1954                  * than 'longer'.  Hence:
1955                  *          m = x_len_longer - x_len_shorter
1956                  *
1957                  * But if something went wrong, make sure the multiplier is at
1958                  * least 1.
1959                  */
1960                 if (x_len_longer > x_len_shorter) {
1961                     PL_collxfrm_mult = (STRLEN) x_len_longer - x_len_shorter;
1962                 }
1963                 else {
1964                     PL_collxfrm_mult = 1;
1965                 }
1966
1967                 /*     mx + b = len
1968                  * so:      b = len - mx
1969                  * but in case something has gone wrong, make sure it is
1970                  * non-negative */
1971                 base = x_len_longer - PL_collxfrm_mult * (sizeof(longer) - 1);
1972                 if (base < 0) {
1973                     base = 0;
1974                 }
1975
1976                 /* Add 1 for the trailing NUL */
1977                 PL_collxfrm_base = base + 1;
1978             }
1979
1980 #  ifdef DEBUGGING
1981
1982             if (DEBUG_L_TEST || debug_initialization) {
1983                 PerlIO_printf(Perl_debug_log,
1984                     "%s:%d: ?UTF-8 locale=%d; x_len_shorter=%zu, "
1985                     "x_len_longer=%zu,"
1986                     " collate multipler=%zu, collate base=%zu\n",
1987                     __FILE__, __LINE__,
1988                     PL_in_utf8_COLLATE_locale,
1989                     x_len_shorter, x_len_longer,
1990                     PL_collxfrm_mult, PL_collxfrm_base);
1991             }
1992 #  endif
1993
1994         }
1995     }
1996
1997 #endif /* USE_LOCALE_COLLATE */
1998
1999 }
2000
2001 #endif
2002
2003 #ifdef WIN32
2004
2005 STATIC char *
2006 S_win32_setlocale(pTHX_ int category, const char* locale)
2007 {
2008     /* This, for Windows, emulates POSIX setlocale() behavior.  There is no
2009      * difference between the two unless the input locale is "", which normally
2010      * means on Windows to get the machine default, which is set via the
2011      * computer's "Regional and Language Options" (or its current equivalent).
2012      * In POSIX, it instead means to find the locale from the user's
2013      * environment.  This routine changes the Windows behavior to first look in
2014      * the environment, and, if anything is found, use that instead of going to
2015      * the machine default.  If there is no environment override, the machine
2016      * default is used, by calling the real setlocale() with "".
2017      *
2018      * The POSIX behavior is to use the LC_ALL variable if set; otherwise to
2019      * use the particular category's variable if set; otherwise to use the LANG
2020      * variable. */
2021
2022     bool override_LC_ALL = FALSE;
2023     char * result;
2024     unsigned int i;
2025
2026     if (locale && strEQ(locale, "")) {
2027
2028 #  ifdef LC_ALL
2029
2030         locale = PerlEnv_getenv("LC_ALL");
2031         if (! locale) {
2032             if (category ==  LC_ALL) {
2033                 override_LC_ALL = TRUE;
2034             }
2035             else {
2036
2037 #  endif
2038
2039                 for (i = 0; i < NOMINAL_LC_ALL_INDEX; i++) {
2040                     if (category == categories[i]) {
2041                         locale = PerlEnv_getenv(category_names[i]);
2042                         goto found_locale;
2043                     }
2044                 }
2045
2046                 locale = PerlEnv_getenv("LANG");
2047                 if (! locale) {
2048                     locale = "";
2049                 }
2050
2051               found_locale: ;
2052
2053 #  ifdef LC_ALL
2054
2055             }
2056         }
2057
2058 #  endif
2059
2060     }
2061
2062     result = setlocale(category, locale);
2063     DEBUG_L(STMT_START {
2064                 dSAVE_ERRNO;
2065                 PerlIO_printf(Perl_debug_log, "%s:%d: %s\n", __FILE__, __LINE__,
2066                             setlocale_debug_string(category, locale, result));
2067                 RESTORE_ERRNO;
2068             } STMT_END);
2069
2070     if (! override_LC_ALL)  {
2071         return result;
2072     }
2073
2074     /* Here the input category was LC_ALL, and we have set it to what is in the
2075      * LANG variable or the system default if there is no LANG.  But these have
2076      * lower priority than the other LC_foo variables, so override it for each
2077      * one that is set.  (If they are set to "", it means to use the same thing
2078      * we just set LC_ALL to, so can skip) */
2079
2080     for (i = 0; i < LC_ALL_INDEX; i++) {
2081         result = PerlEnv_getenv(category_names[i]);
2082         if (result && strNE(result, "")) {
2083             setlocale(categories[i], result);
2084             DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
2085                 __FILE__, __LINE__,
2086                 setlocale_debug_string(categories[i], result, "not captured")));
2087         }
2088     }
2089
2090     result = setlocale(LC_ALL, NULL);
2091     DEBUG_L(STMT_START {
2092                 dSAVE_ERRNO;
2093                 PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
2094                                __FILE__, __LINE__,
2095                                setlocale_debug_string(LC_ALL, NULL, result));
2096                 RESTORE_ERRNO;
2097             } STMT_END);
2098
2099     return result;
2100 }
2101
2102 #endif
2103
2104 /*
2105
2106 =head1 Locale-related functions and macros
2107
2108 =for apidoc Perl_setlocale
2109
2110 This is an (almost) drop-in replacement for the system L<C<setlocale(3)>>,
2111 taking the same parameters, and returning the same information, except that it
2112 returns the correct underlying C<LC_NUMERIC> locale.  Regular C<setlocale> will
2113 instead return C<C> if the underlying locale has a non-dot decimal point
2114 character, or a non-empty thousands separator for displaying floating point
2115 numbers.  This is because perl keeps that locale category such that it has a
2116 dot and empty separator, changing the locale briefly during the operations
2117 where the underlying one is required. C<Perl_setlocale> knows about this, and
2118 compensates; regular C<setlocale> doesn't.
2119
2120 Another reason it isn't completely a drop-in replacement is that it is
2121 declared to return S<C<const char *>>, whereas the system setlocale omits the
2122 C<const> (presumably because its API was specified long ago, and can't be
2123 updated; it is illegal to change the information C<setlocale> returns; doing
2124 so leads to segfaults.)
2125
2126 Finally, C<Perl_setlocale> works under all circumstances, whereas plain
2127 C<setlocale> can be completely ineffective on some platforms under some
2128 configurations.
2129
2130 C<Perl_setlocale> should not be used to change the locale except on systems
2131 where the predefined variable C<${^SAFE_LOCALES}> is 1.  On some such systems,
2132 the system C<setlocale()> is ineffective, returning the wrong information, and
2133 failing to actually change the locale.  C<Perl_setlocale>, however works
2134 properly in all circumstances.
2135
2136 The return points to a per-thread static buffer, which is overwritten the next
2137 time C<Perl_setlocale> is called from the same thread.
2138
2139 =cut
2140
2141 */
2142
2143 const char *
2144 Perl_setlocale(const int category, const char * locale)
2145 {
2146     /* This wraps POSIX::setlocale() */
2147
2148 #ifdef NO_LOCALE
2149
2150     PERL_UNUSED_ARG(category);
2151     PERL_UNUSED_ARG(locale);
2152
2153     return "C";
2154
2155 #else
2156
2157     const char * retval;
2158     const char * newlocale;
2159     dSAVEDERRNO;
2160     dTHX;
2161     DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
2162
2163 #ifdef USE_LOCALE_NUMERIC
2164
2165     /* A NULL locale means only query what the current one is.  We have the
2166      * LC_NUMERIC name saved, because we are normally switched into the C
2167      * (or equivalent) locale for it.  For an LC_ALL query, switch back to get
2168      * the correct results.  All other categories don't require special
2169      * handling */
2170     if (locale == NULL) {
2171         if (category == LC_NUMERIC) {
2172
2173             /* We don't have to copy this return value, as it is a per-thread
2174              * variable, and won't change until a future setlocale */
2175             return PL_numeric_name;
2176         }
2177
2178 #  ifdef LC_ALL
2179
2180         else if (category == LC_ALL) {
2181             STORE_LC_NUMERIC_FORCE_TO_UNDERLYING();
2182         }
2183
2184 #  endif
2185
2186     }
2187
2188 #endif
2189
2190     retval = save_to_buffer(do_setlocale_r(category, locale),
2191                             &PL_setlocale_buf, &PL_setlocale_bufsize, 0);
2192     SAVE_ERRNO;
2193
2194 #if defined(USE_LOCALE_NUMERIC) && defined(LC_ALL)
2195
2196     if (locale == NULL && category == LC_ALL) {
2197         RESTORE_LC_NUMERIC();
2198     }
2199
2200 #endif
2201
2202     DEBUG_L(PerlIO_printf(Perl_debug_log,
2203         "%s:%d: %s\n", __FILE__, __LINE__,
2204             setlocale_debug_string(category, locale, retval)));
2205
2206     RESTORE_ERRNO;
2207
2208     if (! retval) {
2209         return NULL;
2210     }
2211
2212     /* If locale == NULL, we are just querying the state */
2213     if (locale == NULL) {
2214         return retval;
2215     }
2216
2217     /* Now that have switched locales, we have to update our records to
2218      * correspond. */
2219
2220     switch (category) {
2221
2222 #ifdef USE_LOCALE_CTYPE
2223
2224         case LC_CTYPE:
2225             new_ctype(retval);
2226             break;
2227
2228 #endif
2229 #ifdef USE_LOCALE_COLLATE
2230
2231         case LC_COLLATE:
2232             new_collate(retval);
2233             break;
2234
2235 #endif
2236 #ifdef USE_LOCALE_NUMERIC
2237
2238         case LC_NUMERIC:
2239             new_numeric(retval);
2240             break;
2241
2242 #endif
2243 #ifdef LC_ALL
2244
2245         case LC_ALL:
2246
2247             /* LC_ALL updates all the things we care about.  The values may not
2248              * be the same as 'retval', as the locale "" may have set things
2249              * individually */
2250
2251 #  ifdef USE_LOCALE_CTYPE
2252
2253             newlocale = savepv(do_setlocale_c(LC_CTYPE, NULL));
2254             new_ctype(newlocale);
2255             Safefree(newlocale);
2256
2257 #  endif /* USE_LOCALE_CTYPE */
2258 #  ifdef USE_LOCALE_COLLATE
2259
2260             newlocale = savepv(do_setlocale_c(LC_COLLATE, NULL));
2261             new_collate(newlocale);
2262             Safefree(newlocale);
2263
2264 #  endif
2265 #  ifdef USE_LOCALE_NUMERIC
2266
2267             newlocale = savepv(do_setlocale_c(LC_NUMERIC, NULL));
2268             new_numeric(newlocale);
2269             Safefree(newlocale);
2270
2271 #  endif /* USE_LOCALE_NUMERIC */
2272 #endif /* LC_ALL */
2273
2274         default:
2275             break;
2276     }
2277
2278     return retval;
2279
2280 #endif
2281
2282 }
2283
2284 PERL_STATIC_INLINE const char *
2285 S_save_to_buffer(const char * string, char **buf, Size_t *buf_size, const Size_t offset)
2286 {
2287     /* Copy the NUL-terminated 'string' to 'buf' + 'offset'.  'buf' has size 'buf_size',
2288      * growing it if necessary */
2289
2290     Size_t string_size;
2291
2292     PERL_ARGS_ASSERT_SAVE_TO_BUFFER;
2293
2294     if (! string) {
2295         return NULL;
2296     }
2297
2298     string_size = strlen(string) + offset + 1;
2299
2300     if (*buf_size == 0) {
2301         Newx(*buf, string_size, char);
2302         *buf_size = string_size;
2303     }
2304     else if (string_size > *buf_size) {
2305         Renew(*buf, string_size, char);
2306         *buf_size = string_size;
2307     }
2308
2309     Copy(string, *buf + offset, string_size - offset, char);
2310     return *buf;
2311 }
2312
2313 /*
2314
2315 =for apidoc Perl_langinfo
2316
2317 This is an (almost) drop-in replacement for the system C<L<nl_langinfo(3)>>,
2318 taking the same C<item> parameter values, and returning the same information.
2319 But it is more thread-safe than regular C<nl_langinfo()>, and hides the quirks
2320 of Perl's locale handling from your code, and can be used on systems that lack
2321 a native C<nl_langinfo>.
2322
2323 Expanding on these:
2324
2325 =over
2326
2327 =item *
2328
2329 The reason it isn't quite a drop-in replacement is actually an advantage.  The
2330 only difference is that it returns S<C<const char *>>, whereas plain
2331 C<nl_langinfo()> returns S<C<char *>>, but you are (only by documentation)
2332 forbidden to write into the buffer.  By declaring this C<const>, the compiler
2333 enforces this restriction, so if it is violated, you know at compilation time,
2334 rather than getting segfaults at runtime.
2335
2336 =item *
2337
2338 It delivers the correct results for the C<RADIXCHAR> and C<THOUSEP> items,
2339 without you having to write extra code.  The reason for the extra code would be
2340 because these are from the C<LC_NUMERIC> locale category, which is normally
2341 kept set by Perl so that the radix is a dot, and the separator is the empty
2342 string, no matter what the underlying locale is supposed to be, and so to get
2343 the expected results, you have to temporarily toggle into the underlying
2344 locale, and later toggle back.  (You could use plain C<nl_langinfo> and
2345 C<L</STORE_LC_NUMERIC_FORCE_TO_UNDERLYING>> for this but then you wouldn't get
2346 the other advantages of C<Perl_langinfo()>; not keeping C<LC_NUMERIC> in the C
2347 (or equivalent) locale would break a lot of CPAN, which is expecting the radix
2348 (decimal point) character to be a dot.)
2349
2350 =item *
2351
2352 The system function it replaces can have its static return buffer trashed,
2353 not only by a subesequent call to that function, but by a C<freelocale>,
2354 C<setlocale>, or other locale change.  The returned buffer of this function is
2355 not changed until the next call to it, so the buffer is never in a trashed
2356 state.
2357
2358 =item *
2359
2360 Its return buffer is per-thread, so it also is never overwritten by a call to
2361 this function from another thread;  unlike the function it replaces.
2362
2363 =item *
2364
2365 But most importantly, it works on systems that don't have C<nl_langinfo>, such
2366 as Windows, hence makes your code more portable.  Of the fifty-some possible
2367 items specified by the POSIX 2008 standard,
2368 L<http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/langinfo.h.html>,
2369 only one is completely unimplemented, though on non-Windows platforms, another
2370 significant one is also not implemented).  It uses various techniques to
2371 recover the other items, including calling C<L<localeconv(3)>>, and
2372 C<L<strftime(3)>>, both of which are specified in C89, so should be always be
2373 available.  Later C<strftime()> versions have additional capabilities; C<""> is
2374 returned for those not available on your system.
2375
2376 It is important to note that when called with an item that is recovered by
2377 using C<localeconv>, the buffer from any previous explicit call to
2378 C<localeconv> will be overwritten.  This means you must save that buffer's
2379 contents if you need to access them after a call to this function.  (But note
2380 that you might not want to be using C<localeconv()> directly anyway, because of
2381 issues like the ones listed in the second item of this list (above) for
2382 C<RADIXCHAR> and C<THOUSEP>.  You can use the methods given in L<perlcall> to
2383 call L<POSIX/localeconv> and avoid all the issues, but then you have a hash to
2384 unpack).
2385
2386 The details for those items which may deviate from what this emulation returns
2387 and what a native C<nl_langinfo()> would return are specified in
2388 L<I18N::Langinfo>.
2389
2390 =back
2391
2392 When using C<Perl_langinfo> on systems that don't have a native
2393 C<nl_langinfo()>, you must
2394
2395  #include "perl_langinfo.h"
2396
2397 before the C<perl.h> C<#include>.  You can replace your C<langinfo.h>
2398 C<#include> with this one.  (Doing it this way keeps out the symbols that plain
2399 C<langinfo.h> would try to import into the namespace for code that doesn't need
2400 it.)
2401
2402 The original impetus for C<Perl_langinfo()> was so that code that needs to
2403 find out the current currency symbol, floating point radix character, or digit
2404 grouping separator can use, on all systems, the simpler and more
2405 thread-friendly C<nl_langinfo> API instead of C<L<localeconv(3)>> which is a
2406 pain to make thread-friendly.  For other fields returned by C<localeconv>, it
2407 is better to use the methods given in L<perlcall> to call
2408 L<C<POSIX::localeconv()>|POSIX/localeconv>, which is thread-friendly.
2409
2410 =cut
2411
2412 */
2413
2414 const char *
2415 #ifdef HAS_NL_LANGINFO
2416 Perl_langinfo(const nl_item item)
2417 #else
2418 Perl_langinfo(const int item)
2419 #endif
2420 {
2421     return my_nl_langinfo(item, TRUE);
2422 }
2423
2424 STATIC const char *
2425 #ifdef HAS_NL_LANGINFO
2426 S_my_nl_langinfo(const nl_item item, bool toggle)
2427 #else
2428 S_my_nl_langinfo(const int item, bool toggle)
2429 #endif
2430 {
2431     dTHX;
2432     const char * retval;
2433
2434 #ifdef USE_LOCALE_NUMERIC
2435
2436     /* We only need to toggle into the underlying LC_NUMERIC locale for these
2437      * two items, and only if not already there */
2438     if (toggle && ((   item != RADIXCHAR && item != THOUSEP)
2439                     || PL_numeric_underlying))
2440
2441 #endif  /* No toggling needed if not using LC_NUMERIC */
2442
2443         toggle = FALSE;
2444
2445 #if defined(HAS_NL_LANGINFO) /* nl_langinfo() is available.  */
2446 #  if   ! defined(HAS_THREAD_SAFE_NL_LANGINFO_L)      \
2447      || ! defined(HAS_POSIX_2008_LOCALE)              \
2448      || ! defined(DUPLOCALE)
2449
2450     /* Here, use plain nl_langinfo(), switching to the underlying LC_NUMERIC
2451      * for those items dependent on it.  This must be copied to a buffer before
2452      * switching back, as some systems destroy the buffer when setlocale() is
2453      * called */
2454
2455     {
2456         DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
2457
2458         if (toggle) {
2459             STORE_LC_NUMERIC_FORCE_TO_UNDERLYING();
2460         }
2461
2462         LOCALE_LOCK;    /* Prevent interference from another thread executing
2463                            this code section (the only call to nl_langinfo in
2464                            the core) */
2465
2466
2467         /* Copy to a per-thread buffer, which is also one that won't be
2468          * destroyed by a subsequent setlocale(), such as the
2469          * RESTORE_LC_NUMERIC may do just below. */
2470         retval = save_to_buffer(nl_langinfo(item),
2471                                 &PL_langinfo_buf, &PL_langinfo_bufsize, 0);
2472
2473         LOCALE_UNLOCK;
2474
2475         if (toggle) {
2476             RESTORE_LC_NUMERIC();
2477         }
2478     }
2479
2480 #  else /* Use nl_langinfo_l(), avoiding both a mutex and changing the locale */
2481
2482     {
2483         bool do_free = FALSE;
2484         locale_t cur = uselocale((locale_t) 0);
2485
2486         if (cur == LC_GLOBAL_LOCALE) {
2487             cur = duplocale(LC_GLOBAL_LOCALE);
2488             do_free = TRUE;
2489         }
2490
2491 #    ifdef USE_LOCALE_NUMERIC
2492
2493         if (toggle) {
2494             if (PL_underlying_numeric_obj) {
2495                 cur = PL_underlying_numeric_obj;
2496             }
2497             else {
2498                 cur = newlocale(LC_NUMERIC_MASK, PL_numeric_name, cur);
2499                 do_free = TRUE;
2500             }
2501         }
2502
2503 #    endif
2504
2505         /* We have to save it to a buffer, because the freelocale() just below
2506          * can invalidate the internal one */
2507         retval = save_to_buffer(nl_langinfo_l(item, cur),
2508                                 &PL_langinfo_buf, &PL_langinfo_bufsize, 0);
2509
2510         if (do_free) {
2511             freelocale(cur);
2512         }
2513     }
2514
2515 #  endif
2516
2517     if (strEQ(retval, "")) {
2518         if (item == YESSTR) {
2519             return "yes";
2520         }
2521         if (item == NOSTR) {
2522             return "no";
2523         }
2524     }
2525
2526     return retval;
2527
2528 #else   /* Below, emulate nl_langinfo as best we can */
2529
2530     {
2531
2532 #  ifdef HAS_LOCALECONV
2533
2534         const struct lconv* lc;
2535         const char * temp;
2536         DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
2537
2538 #    ifdef TS_W32_BROKEN_LOCALECONV
2539
2540         const char * save_global;
2541         const char * save_thread;
2542         int needed_size;
2543         char * ptr;
2544         char * e;
2545         char * item_start;
2546
2547 #    endif
2548 #  endif
2549 #  ifdef HAS_STRFTIME
2550
2551         struct tm tm;
2552         bool return_format = FALSE; /* Return the %format, not the value */
2553         const char * format;
2554
2555 #  endif
2556
2557         /* We copy the results to a per-thread buffer, even if not
2558          * multi-threaded.  This is in part to simplify this code, and partly
2559          * because we need a buffer anyway for strftime(), and partly because a
2560          * call of localeconv() could otherwise wipe out the buffer, and the
2561          * programmer would not be expecting this, as this is a nl_langinfo()
2562          * substitute after all, so s/he might be thinking their localeconv()
2563          * is safe until another localeconv() call. */
2564
2565         switch (item) {
2566             Size_t len;
2567
2568             /* This is unimplemented */
2569             case ERA:      /* For use with strftime() %E modifier */
2570
2571             default:
2572                 return "";
2573
2574             /* We use only an English set, since we don't know any more */
2575             case YESEXPR:   return "^[+1yY]";
2576             case YESSTR:    return "yes";
2577             case NOEXPR:    return "^[-0nN]";
2578             case NOSTR:     return "no";
2579
2580             case CODESET:
2581
2582 #  ifndef WIN32
2583
2584                 /* On non-windows, this is unimplemented, in part because of
2585                  * inconsistencies between vendors.  The Darwin native
2586                  * nl_langinfo() implementation simply looks at everything past
2587                  * any dot in the name, but that doesn't work for other
2588                  * vendors.  Many Linux locales that don't have UTF-8 in their
2589                  * names really are UTF-8, for example; z/OS locales that do
2590                  * have UTF-8 in their names, aren't really UTF-8 */
2591                 return "";
2592
2593 #  else
2594
2595                 {   /* But on Windows, the name does seem to be consistent, so
2596                        use that. */
2597                     const char * p;
2598                     const char * first;
2599                     Size_t offset = 0;
2600                     const char * name = my_setlocale(LC_CTYPE, NULL);
2601
2602                     if (isNAME_C_OR_POSIX(name)) {
2603                         return "ANSI_X3.4-1968";
2604                     }
2605
2606                     /* Find the dot in the locale name */
2607                     first = (const char *) strchr(name, '.');
2608                     if (! first) {
2609                         first = name;
2610                         goto has_nondigit;
2611                     }
2612
2613                     /* Look at everything past the dot */
2614                     first++;
2615                     p = first;
2616
2617                     while (*p) {
2618                         if (! isDIGIT(*p)) {
2619                             goto has_nondigit;
2620                         }
2621
2622                         p++;
2623                     }
2624
2625                     /* Here everything past the dot is a digit.  Treat it as a
2626                      * code page */
2627                     retval = save_to_buffer("CP", &PL_langinfo_buf,
2628                                                 &PL_langinfo_bufsize, 0);
2629                     offset = STRLENs("CP");
2630
2631                   has_nondigit:
2632
2633                     retval = save_to_buffer(first, &PL_langinfo_buf,
2634                                             &PL_langinfo_bufsize, offset);
2635                 }
2636
2637                 break;
2638
2639 #  endif
2640 #  ifdef HAS_LOCALECONV
2641
2642             case CRNCYSTR:
2643
2644                 /* We don't bother with localeconv_l() because any system that
2645                  * has it is likely to also have nl_langinfo() */
2646
2647                 LOCALE_LOCK_V;    /* Prevent interference with other threads
2648                                      using localeconv() */
2649
2650 #    ifdef TS_W32_BROKEN_LOCALECONV
2651
2652                 /* This is a workaround for a Windows bug prior to VS 15.
2653                  * What we do here is, while locked, switch to the global
2654                  * locale so localeconv() works; then switch back just before
2655                  * the unlock.  This can screw things up if some thread is
2656                  * already using the global locale while assuming no other is.
2657                  * A different workaround would be to call GetCurrencyFormat on
2658                  * a known value, and parse it; patches welcome
2659                  *
2660                  * We have to use LC_ALL instead of LC_MONETARY because of
2661                  * another bug in Windows */
2662
2663                 save_thread = savepv(my_setlocale(LC_ALL, NULL));
2664                 _configthreadlocale(_DISABLE_PER_THREAD_LOCALE);
2665                 save_global= savepv(my_setlocale(LC_ALL, NULL));
2666                 my_setlocale(LC_ALL, save_thread);
2667
2668 #    endif
2669
2670                 lc = localeconv();
2671                 if (   ! lc
2672                     || ! lc->currency_symbol
2673                     || strEQ("", lc->currency_symbol))
2674                 {
2675                     LOCALE_UNLOCK_V;
2676                     return "";
2677                 }
2678
2679                 /* Leave the first spot empty to be filled in below */
2680                 retval = save_to_buffer(lc->currency_symbol, &PL_langinfo_buf,
2681                                         &PL_langinfo_bufsize, 1);
2682                 if (lc->mon_decimal_point && strEQ(lc->mon_decimal_point, ""))
2683                 { /*  khw couldn't figure out how the localedef specifications
2684                       would show that the $ should replace the radix; this is
2685                       just a guess as to how it might work.*/
2686                     PL_langinfo_buf[0] = '.';
2687                 }
2688                 else if (lc->p_cs_precedes) {
2689                     PL_langinfo_buf[0] = '-';
2690                 }
2691                 else {
2692                     PL_langinfo_buf[0] = '+';
2693                 }
2694
2695 #    ifdef TS_W32_BROKEN_LOCALECONV
2696
2697                 my_setlocale(LC_ALL, save_global);
2698                 _configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
2699                 my_setlocale(LC_ALL, save_thread);
2700                 Safefree(save_global);
2701                 Safefree(save_thread);
2702
2703 #    endif
2704
2705                 LOCALE_UNLOCK_V;
2706                 break;
2707
2708 #    ifdef TS_W32_BROKEN_LOCALECONV
2709
2710             case RADIXCHAR:
2711
2712                 /* For this, we output a known simple floating point number to
2713                  * a buffer, and parse it, looking for the radix */
2714
2715                 if (toggle) {
2716                     STORE_LC_NUMERIC_FORCE_TO_UNDERLYING();
2717                 }
2718
2719                 if (PL_langinfo_bufsize < 10) {
2720                     PL_langinfo_bufsize = 10;
2721                     Renew(PL_langinfo_buf, PL_langinfo_bufsize, char);
2722                 }
2723
2724                 needed_size = my_snprintf(PL_langinfo_buf, PL_langinfo_bufsize,
2725                                           "%.1f", 1.5);
2726                 if (needed_size >= (int) PL_langinfo_bufsize) {
2727                     PL_langinfo_bufsize = needed_size + 1;
2728                     Renew(PL_langinfo_buf, PL_langinfo_bufsize, char);
2729                     needed_size = my_snprintf(PL_langinfo_buf, PL_langinfo_bufsize,
2730                                              "%.1f", 1.5);
2731                     assert(needed_size < (int) PL_langinfo_bufsize);
2732                 }
2733
2734                 ptr = PL_langinfo_buf;
2735                 e = PL_langinfo_buf + PL_langinfo_bufsize;
2736
2737                 /* Find the '1' */
2738                 while (ptr < e && *ptr != '1') {
2739                     ptr++;
2740                 }
2741                 ptr++;
2742
2743                 /* Find the '5' */
2744                 item_start = ptr;
2745                 while (ptr < e && *ptr != '5') {
2746                     ptr++;
2747                 }
2748
2749                 /* Everything in between is the radix string */
2750                 if (ptr >= e) {
2751                     PL_langinfo_buf[0] = '?';
2752                     PL_langinfo_buf[1] = '\0';
2753                 }
2754                 else {
2755                     *ptr = '\0';
2756                     Move(item_start, PL_langinfo_buf, ptr - PL_langinfo_buf, char);
2757                 }
2758
2759                 if (toggle) {
2760                     RESTORE_LC_NUMERIC();
2761                 }
2762
2763                 retval = PL_langinfo_buf;
2764                 break;
2765
2766 #    else
2767
2768             case RADIXCHAR:     /* No special handling needed */
2769
2770 #    endif
2771
2772             case THOUSEP:
2773
2774                 if (toggle) {
2775                     STORE_LC_NUMERIC_FORCE_TO_UNDERLYING();
2776                 }
2777
2778                 LOCALE_LOCK_V;    /* Prevent interference with other threads
2779                                      using localeconv() */
2780
2781 #    ifdef TS_W32_BROKEN_LOCALECONV
2782
2783                 /* This should only be for the thousands separator.  A
2784                  * different work around would be to use GetNumberFormat on a
2785                  * known value and parse the result to find the separator */
2786                 save_thread = savepv(my_setlocale(LC_ALL, NULL));
2787                 _configthreadlocale(_DISABLE_PER_THREAD_LOCALE);
2788                 save_global = savepv(my_setlocale(LC_ALL, NULL));
2789                 my_setlocale(LC_ALL, save_thread);
2790 #      if 0
2791                 /* This is the start of code that for broken Windows replaces
2792                  * the above and below code, and instead calls
2793                  * GetNumberFormat() and then would parse that to find the
2794                  * thousands separator.  It needs to handle UTF-16 vs -8
2795                  * issues. */
2796
2797                 needed_size = GetNumberFormatEx(PL_numeric_name, 0, "1234.5", NULL, PL_langinfo_buf, PL_langinfo_bufsize);
2798                 DEBUG_L(PerlIO_printf(Perl_debug_log,
2799                     "%s: %d: return from GetNumber, count=%d, val=%s\n",
2800                     __FILE__, __LINE__, needed_size, PL_langinfo_buf));
2801
2802 #      endif
2803 #    endif
2804
2805                 lc = localeconv();
2806                 if (! lc) {
2807                     temp = "";
2808                 }
2809                 else {
2810                     temp = (item == RADIXCHAR)
2811                              ? lc->decimal_point
2812                              : lc->thousands_sep;
2813                     if (! temp) {
2814                         temp = "";
2815                     }
2816                 }
2817
2818                 retval = save_to_buffer(temp, &PL_langinfo_buf,
2819                                         &PL_langinfo_bufsize, 0);
2820
2821 #    ifdef TS_W32_BROKEN_LOCALECONV
2822
2823                 my_setlocale(LC_ALL, save_global);
2824                 _configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
2825                 my_setlocale(LC_ALL, save_thread);
2826                 Safefree(save_global);
2827                 Safefree(save_thread);
2828
2829 #    endif
2830
2831                 LOCALE_UNLOCK_V;
2832
2833                 if (toggle) {
2834                     RESTORE_LC_NUMERIC();
2835                 }
2836
2837                 break;
2838
2839 #  endif
2840 #  ifdef HAS_STRFTIME
2841
2842             /* These are defined by C89, so we assume that strftime supports
2843              * them, and so are returned unconditionally; they may not be what
2844              * the locale actually says, but should give good enough results
2845              * for someone using them as formats (as opposed to trying to parse
2846              * them to figure out what the locale says).  The other format
2847              * items are actually tested to verify they work on the platform */
2848             case D_FMT:         return "%x";
2849             case T_FMT:         return "%X";
2850             case D_T_FMT:       return "%c";
2851
2852             /* These formats are only available in later strfmtime's */
2853             case ERA_D_FMT: case ERA_T_FMT: case ERA_D_T_FMT: case T_FMT_AMPM:
2854
2855             /* The rest can be gotten from most versions of strftime(). */
2856             case ABDAY_1: case ABDAY_2: case ABDAY_3:
2857             case ABDAY_4: case ABDAY_5: case ABDAY_6: case ABDAY_7:
2858             case ALT_DIGITS:
2859             case AM_STR: case PM_STR:
2860             case ABMON_1: case ABMON_2: case ABMON_3: case ABMON_4:
2861             case ABMON_5: case ABMON_6: case ABMON_7: case ABMON_8:
2862             case ABMON_9: case ABMON_10: case ABMON_11: case ABMON_12:
2863             case DAY_1: case DAY_2: case DAY_3: case DAY_4:
2864             case DAY_5: case DAY_6: case DAY_7:
2865             case MON_1: case MON_2: case MON_3: case MON_4:
2866             case MON_5: case MON_6: case MON_7: case MON_8:
2867             case MON_9: case MON_10: case MON_11: case MON_12:
2868
2869                 LOCALE_LOCK;
2870
2871                 init_tm(&tm);   /* Precaution against core dumps */
2872                 tm.tm_sec = 30;
2873                 tm.tm_min = 30;
2874                 tm.tm_hour = 6;
2875                 tm.tm_year = 2017 - 1900;
2876                 tm.tm_wday = 0;
2877                 tm.tm_mon = 0;
2878                 switch (item) {
2879                     default:
2880                         LOCALE_UNLOCK;
2881                         Perl_croak(aTHX_
2882                                     "panic: %s: %d: switch case: %d problem",
2883                                        __FILE__, __LINE__, item);
2884                         NOT_REACHED; /* NOTREACHED */
2885
2886                     case PM_STR: tm.tm_hour = 18;
2887                     case AM_STR:
2888                         format = "%p";
2889                         break;
2890
2891                     case ABDAY_7: tm.tm_wday++;
2892                     case ABDAY_6: tm.tm_wday++;
2893                     case ABDAY_5: tm.tm_wday++;
2894                     case ABDAY_4: tm.tm_wday++;
2895                     case ABDAY_3: tm.tm_wday++;
2896                     case ABDAY_2: tm.tm_wday++;
2897                     case ABDAY_1:
2898                         format = "%a";
2899                         break;
2900
2901                     case DAY_7: tm.tm_wday++;
2902                     case DAY_6: tm.tm_wday++;
2903                     case DAY_5: tm.tm_wday++;
2904                     case DAY_4: tm.tm_wday++;
2905                     case DAY_3: tm.tm_wday++;
2906                     case DAY_2: tm.tm_wday++;
2907                     case DAY_1:
2908                         format = "%A";
2909                         break;
2910
2911                     case ABMON_12: tm.tm_mon++;
2912                     case ABMON_11: tm.tm_mon++;
2913                     case ABMON_10: tm.tm_mon++;
2914                     case ABMON_9: tm.tm_mon++;
2915                     case ABMON_8: tm.tm_mon++;
2916                     case ABMON_7: tm.tm_mon++;
2917                     case ABMON_6: tm.tm_mon++;
2918                     case ABMON_5: tm.tm_mon++;
2919                     case ABMON_4: tm.tm_mon++;
2920                     case ABMON_3: tm.tm_mon++;
2921                     case ABMON_2: tm.tm_mon++;
2922                     case ABMON_1:
2923                         format = "%b";
2924                         break;
2925
2926                     case MON_12: tm.tm_mon++;
2927                     case MON_11: tm.tm_mon++;
2928                     case MON_10: tm.tm_mon++;
2929                     case MON_9: tm.tm_mon++;
2930                     case MON_8: tm.tm_mon++;
2931                     case MON_7: tm.tm_mon++;
2932                     case MON_6: tm.tm_mon++;
2933                     case MON_5: tm.tm_mon++;
2934                     case MON_4: tm.tm_mon++;
2935                     case MON_3: tm.tm_mon++;
2936                     case MON_2: tm.tm_mon++;
2937                     case MON_1:
2938                         format = "%B";
2939                         break;
2940
2941                     case T_FMT_AMPM:
2942                         format = "%r";
2943                         return_format = TRUE;
2944                         break;
2945
2946                     case ERA_D_FMT:
2947                         format = "%Ex";
2948                         return_format = TRUE;
2949                         break;
2950
2951                     case ERA_T_FMT:
2952                         format = "%EX";
2953                         return_format = TRUE;
2954                         break;
2955
2956                     case ERA_D_T_FMT:
2957                         format = "%Ec";
2958                         return_format = TRUE;
2959                         break;
2960
2961                     case ALT_DIGITS:
2962                         tm.tm_wday = 0;
2963                         format = "%Ow"; /* Find the alternate digit for 0 */
2964                         break;
2965                 }
2966
2967                 /* We can't use my_strftime() because it doesn't look at
2968                  * tm_wday  */
2969                 while (0 == strftime(PL_langinfo_buf, PL_langinfo_bufsize,
2970                                      format, &tm))
2971                 {
2972                     /* A zero return means one of:
2973                      *  a)  there wasn't enough space in PL_langinfo_buf
2974                      *  b)  the format, like a plain %p, returns empty
2975                      *  c)  it was an illegal format, though some
2976                      *      implementations of strftime will just return the
2977                      *      illegal format as a plain character sequence.
2978                      *
2979                      *  To quickly test for case 'b)', try again but precede
2980                      *  the format with a plain character.  If that result is
2981                      *  still empty, the problem is either 'a)' or 'c)' */
2982
2983                     Size_t format_size = strlen(format) + 1;
2984                     Size_t mod_size = format_size + 1;
2985                     char * mod_format;
2986                     char * temp_result;
2987
2988                     Newx(mod_format, mod_size, char);
2989                     Newx(temp_result, PL_langinfo_bufsize, char);
2990                     *mod_format = ' ';
2991                     my_strlcpy(mod_format + 1, format, mod_size);
2992                     len = strftime(temp_result,
2993                                    PL_langinfo_bufsize,
2994                                    mod_format, &tm);
2995                     Safefree(mod_format);
2996                     Safefree(temp_result);
2997
2998                     /* If 'len' is non-zero, it means that we had a case like
2999                      * %p which means the current locale doesn't use a.m. or
3000                      * p.m., and that is valid */
3001                     if (len == 0) {
3002
3003                         /* Here, still didn't work.  If we get well beyond a
3004                          * reasonable size, bail out to prevent an infinite
3005                          * loop. */
3006
3007                         if (PL_langinfo_bufsize > 100 * format_size) {
3008                             *PL_langinfo_buf = '\0';
3009                         }
3010                         else {
3011                             /* Double the buffer size to retry;  Add 1 in case
3012                              * original was 0, so we aren't stuck at 0.  */
3013                             PL_langinfo_bufsize *= 2;
3014                             PL_langinfo_bufsize++;
3015                             Renew(PL_langinfo_buf, PL_langinfo_bufsize, char);
3016                             continue;
3017                         }
3018                     }
3019
3020                     break;
3021                 }
3022
3023                 /* Here, we got a result.
3024                  *
3025                  * If the item is 'ALT_DIGITS', PL_langinfo_buf contains the
3026                  * alternate format for wday 0.  If the value is the same as
3027                  * the normal 0, there isn't an alternate, so clear the buffer.
3028                  * */
3029                 if (   item == ALT_DIGITS
3030                     && strEQ(PL_langinfo_buf, "0"))
3031                 {
3032                     *PL_langinfo_buf = '\0';
3033                 }
3034
3035                 /* ALT_DIGITS is problematic.  Experiments on it showed that
3036                  * strftime() did not always work properly when going from
3037                  * alt-9 to alt-10.  Only a few locales have this item defined,
3038                  * and in all of them on Linux that khw was able to find,
3039                  * nl_langinfo() merely returned the alt-0 character, possibly
3040                  * doubled.  Most Unicode digits are in blocks of 10
3041                  * consecutive code points, so that is sufficient information
3042                  * for those scripts, as we can infer alt-1, alt-2, ....  But
3043                  * for a Japanese locale, a CJK ideographic 0 is returned, and
3044                  * the CJK digits are not in code point order, so you can't
3045                  * really infer anything.  The localedef for this locale did
3046                  * specify the succeeding digits, so that strftime() works
3047                  * properly on them, without needing to infer anything.  But
3048                  * the nl_langinfo() return did not give sufficient information
3049                  * for the caller to understand what's going on.  So until
3050                  * there is evidence that it should work differently, this
3051                  * returns the alt-0 string for ALT_DIGITS.
3052                  *
3053                  * wday was chosen because its range is all a single digit.
3054                  * Things like tm_sec have two digits as the minimum: '00' */
3055
3056                 LOCALE_UNLOCK;
3057
3058                 retval = PL_langinfo_buf;
3059
3060                 /* If to return the format, not the value, overwrite the buffer
3061                  * with it.  But some strftime()s will keep the original format
3062                  * if illegal, so change those to "" */
3063                 if (return_format) {
3064                     if (strEQ(PL_langinfo_buf, format)) {
3065                         *PL_langinfo_buf = '\0';
3066                     }
3067                     else {
3068                         retval = save_to_buffer(format, &PL_langinfo_buf,
3069                                                 &PL_langinfo_bufsize, 0);
3070                     }
3071                 }
3072
3073                 break;
3074
3075 #  endif
3076
3077         }
3078     }
3079
3080     return retval;
3081
3082 #endif
3083
3084 }
3085
3086 /*
3087  * Initialize locale awareness.
3088  */
3089 int
3090 Perl_init_i18nl10n(pTHX_ int printwarn)
3091 {
3092     /* printwarn is
3093      *
3094      *    0 if not to output warning when setup locale is bad
3095      *    1 if to output warning based on value of PERL_BADLANG
3096      *    >1 if to output regardless of PERL_BADLANG
3097      *
3098      * returns
3099      *    1 = set ok or not applicable,
3100      *    0 = fallback to a locale of lower priority
3101      *   -1 = fallback to all locales failed, not even to the C locale
3102      *
3103      * Under -DDEBUGGING, if the environment variable PERL_DEBUG_LOCALE_INIT is
3104      * set, debugging information is output.
3105      *
3106      * This looks more complicated than it is, mainly due to the #ifdefs.
3107      *
3108      * We try to set LC_ALL to the value determined by the environment.  If
3109      * there is no LC_ALL on this platform, we try the individual categories we
3110      * know about.  If this works, we are done.
3111      *
3112      * But if it doesn't work, we have to do something else.  We search the
3113      * environment variables ourselves instead of relying on the system to do
3114      * it.  We look at, in order, LC_ALL, LANG, a system default locale (if we
3115      * think there is one), and the ultimate fallback "C".  This is all done in
3116      * the same loop as above to avoid duplicating code, but it makes things
3117      * more complex.  The 'trial_locales' array is initialized with just one
3118      * element; it causes the behavior described in the paragraph above this to
3119      * happen.  If that fails, we add elements to 'trial_locales', and do extra
3120      * loop iterations to cause the behavior described in this paragraph.
3121      *
3122      * On Ultrix, the locale MUST come from the environment, so there is
3123      * preliminary code to set it.  I (khw) am not sure that it is necessary,
3124      * and that this couldn't be folded into the loop, but barring any real
3125      * platforms to test on, it's staying as-is
3126      *
3127      * A slight complication is that in embedded Perls, the locale may already
3128      * be set-up, and we don't want to get it from the normal environment
3129      * variables.  This is handled by having a special environment variable
3130      * indicate we're in this situation.  We simply set setlocale's 2nd
3131      * parameter to be a NULL instead of "".  That indicates to setlocale that
3132      * it is not to change anything, but to return the current value,
3133      * effectively initializing perl's db to what the locale already is.
3134      *
3135      * We play the same trick with NULL if a LC_ALL succeeds.  We call
3136      * setlocale() on the individual categores with NULL to get their existing
3137      * values for our db, instead of trying to change them.
3138      * */
3139
3140     int ok = 1;
3141
3142 #ifndef USE_LOCALE
3143
3144     PERL_UNUSED_ARG(printwarn);
3145
3146 #else  /* USE_LOCALE */
3147 #  ifdef __GLIBC__
3148
3149     const char * const language   = savepv(PerlEnv_getenv("LANGUAGE"));
3150
3151 #  endif
3152
3153     /* NULL uses the existing already set up locale */
3154     const char * const setlocale_init = (PerlEnv_getenv("PERL_SKIP_LOCALE_INIT"))
3155                                         ? NULL
3156                                         : "";
3157     const char* trial_locales[5];   /* 5 = 1 each for "", LC_ALL, LANG, "", C */
3158     unsigned int trial_locales_count;
3159     const char * const lc_all     = savepv(PerlEnv_getenv("LC_ALL"));
3160     const char * const lang       = savepv(PerlEnv_getenv("LANG"));
3161     bool setlocale_failure = FALSE;
3162     unsigned int i;
3163
3164     /* A later getenv() could zap this, so only use here */
3165     const char * const bad_lang_use_once = PerlEnv_getenv("PERL_BADLANG");
3166
3167     const bool locwarn = (printwarn > 1
3168                           || (          printwarn
3169                               && (    ! bad_lang_use_once
3170                                   || (
3171                                          /* disallow with "" or "0" */
3172                                          *bad_lang_use_once
3173                                        && strNE("0", bad_lang_use_once)))));
3174
3175     /* setlocale() return vals; not copied so must be looked at immediately */
3176     const char * sl_result[NOMINAL_LC_ALL_INDEX + 1];
3177
3178     /* current locale for given category; should have been copied so aren't
3179      * volatile */
3180     const char * curlocales[NOMINAL_LC_ALL_INDEX + 1];
3181
3182 #  ifdef WIN32
3183
3184     /* In some systems you can find out the system default locale
3185      * and use that as the fallback locale. */
3186 #    define SYSTEM_DEFAULT_LOCALE
3187 #  endif
3188 #  ifdef SYSTEM_DEFAULT_LOCALE
3189
3190     const char *system_default_locale = NULL;
3191
3192 #  endif
3193
3194 #  ifndef DEBUGGING
3195 #    define DEBUG_LOCALE_INIT(a,b,c)
3196 #  else
3197
3198     DEBUG_INITIALIZATION_set(cBOOL(PerlEnv_getenv("PERL_DEBUG_LOCALE_INIT")));
3199
3200 #    define DEBUG_LOCALE_INIT(category, locale, result)                     \
3201         STMT_START {                                                        \
3202                 if (debug_initialization) {                                 \
3203                     PerlIO_printf(Perl_debug_log,                           \
3204                                   "%s:%d: %s\n",                            \
3205                                   __FILE__, __LINE__,                       \
3206                                   setlocale_debug_string(category,          \
3207                                                           locale,           \
3208                                                           result));         \
3209                 }                                                           \
3210         } STMT_END
3211
3212 /* Make sure the parallel arrays are properly set up */
3213 #    ifdef USE_LOCALE_NUMERIC
3214     assert(categories[LC_NUMERIC_INDEX] == LC_NUMERIC);
3215     assert(strEQ(category_names[LC_NUMERIC_INDEX], "LC_NUMERIC"));
3216 #      ifdef USE_POSIX_2008_LOCALE
3217     assert(category_masks[LC_NUMERIC_INDEX] == LC_NUMERIC_MASK);
3218 #      endif
3219 #    endif
3220 #    ifdef USE_LOCALE_CTYPE
3221     assert(categories[LC_CTYPE_INDEX] == LC_CTYPE);
3222     assert(strEQ(category_names[LC_CTYPE_INDEX], "LC_CTYPE"));
3223 #      ifdef USE_POSIX_2008_LOCALE
3224     assert(category_masks[LC_CTYPE_INDEX] == LC_CTYPE_MASK);
3225 #      endif
3226 #    endif
3227 #    ifdef USE_LOCALE_COLLATE
3228     assert(categories[LC_COLLATE_INDEX] == LC_COLLATE);
3229     assert(strEQ(category_names[LC_COLLATE_INDEX], "LC_COLLATE"));
3230 #      ifdef USE_POSIX_2008_LOCALE
3231     assert(category_masks[LC_COLLATE_INDEX] == LC_COLLATE_MASK);
3232 #      endif
3233 #    endif
3234 #    ifdef USE_LOCALE_TIME
3235     assert(categories[LC_TIME_INDEX] == LC_TIME);
3236     assert(strEQ(category_names[LC_TIME_INDEX], "LC_TIME"));
3237 #      ifdef USE_POSIX_2008_LOCALE
3238     assert(category_masks[LC_TIME_INDEX] == LC_TIME_MASK);
3239 #      endif
3240 #    endif
3241 #    ifdef USE_LOCALE_MESSAGES
3242     assert(categories[LC_MESSAGES_INDEX] == LC_MESSAGES);
3243     assert(strEQ(category_names[LC_MESSAGES_INDEX], "LC_MESSAGES"));
3244 #      ifdef USE_POSIX_2008_LOCALE
3245     assert(category_masks[LC_MESSAGES_INDEX] == LC_MESSAGES_MASK);
3246 #      endif
3247 #    endif
3248 #    ifdef USE_LOCALE_MONETARY
3249     assert(categories[LC_MONETARY_INDEX] == LC_MONETARY);
3250     assert(strEQ(category_names[LC_MONETARY_INDEX], "LC_MONETARY"));
3251 #      ifdef USE_POSIX_2008_LOCALE
3252     assert(category_masks[LC_MONETARY_INDEX] == LC_MONETARY_MASK);
3253 #      endif
3254 #    endif
3255 #    ifdef USE_LOCALE_ADDRESS
3256     assert(categories[LC_ADDRESS_INDEX] == LC_ADDRESS);
3257     assert(strEQ(category_names[LC_ADDRESS_INDEX], "LC_ADDRESS"));
3258 #      ifdef USE_POSIX_2008_LOCALE
3259     assert(category_masks[LC_ADDRESS_INDEX] == LC_ADDRESS_MASK);
3260 #      endif
3261 #    endif
3262 #    ifdef USE_LOCALE_IDENTIFICATION
3263     assert(categories[LC_IDENTIFICATION_INDEX] == LC_IDENTIFICATION);
3264     assert(strEQ(category_names[LC_IDENTIFICATION_INDEX], "LC_IDENTIFICATION"));
3265 #      ifdef USE_POSIX_2008_LOCALE
3266     assert(category_masks[LC_IDENTIFICATION_INDEX] == LC_IDENTIFICATION_MASK);
3267 #      endif
3268 #    endif
3269 #    ifdef USE_LOCALE_MEASUREMENT
3270     assert(categories[LC_MEASUREMENT_INDEX] == LC_MEASUREMENT);
3271     assert(strEQ(category_names[LC_MEASUREMENT_INDEX], "LC_MEASUREMENT"));
3272 #      ifdef USE_POSIX_2008_LOCALE
3273     assert(category_masks[LC_MEASUREMENT_INDEX] == LC_MEASUREMENT_MASK);
3274 #      endif
3275 #    endif
3276 #    ifdef USE_LOCALE_PAPER
3277     assert(categories[LC_PAPER_INDEX] == LC_PAPER);
3278     assert(strEQ(category_names[LC_PAPER_INDEX], "LC_PAPER"));
3279 #      ifdef USE_POSIX_2008_LOCALE
3280     assert(category_masks[LC_PAPER_INDEX] == LC_PAPER_MASK);
3281 #      endif
3282 #    endif
3283 #    ifdef USE_LOCALE_TELEPHONE
3284     assert(categories[LC_TELEPHONE_INDEX] == LC_TELEPHONE);
3285     assert(strEQ(category_names[LC_TELEPHONE_INDEX], "LC_TELEPHONE"));
3286 #      ifdef USE_POSIX_2008_LOCALE
3287     assert(category_masks[LC_TELEPHONE_INDEX] == LC_TELEPHONE_MASK);
3288 #      endif
3289 #    endif
3290 #    ifdef LC_ALL
3291     assert(categories[LC_ALL_INDEX] == LC_ALL);
3292     assert(strEQ(category_names[LC_ALL_INDEX], "LC_ALL"));
3293     assert(NOMINAL_LC_ALL_INDEX == LC_ALL_INDEX);
3294 #      ifdef USE_POSIX_2008_LOCALE
3295     assert(category_masks[LC_ALL_INDEX] == LC_ALL_MASK);
3296 #      endif
3297 #    endif
3298 #  endif    /* DEBUGGING */
3299
3300     /* Initialize the cache of the program's UTF-8ness for the always known
3301      * locales C and POSIX */
3302     my_strlcpy(PL_locale_utf8ness, C_and_POSIX_utf8ness,
3303                sizeof(PL_locale_utf8ness));
3304
3305 #  ifdef USE_THREAD_SAFE_LOCALE
3306 #    ifdef WIN32
3307
3308     _configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
3309
3310 #    endif
3311 #  endif
3312 #  ifdef USE_POSIX_2008_LOCALE
3313
3314     PL_C_locale_obj = newlocale(LC_ALL_MASK, "C", (locale_t) 0);
3315     if (! PL_C_locale_obj) {
3316         Perl_croak_nocontext(
3317             "panic: Cannot create POSIX 2008 C locale object; errno=%d", errno);
3318     }
3319     if (DEBUG_Lv_TEST || debug_initialization) {
3320         PerlIO_printf(Perl_debug_log, "%s:%d: created C object %p\n", __FILE__, __LINE__, PL_C_locale_obj);
3321     }
3322
3323 #  endif
3324
3325 #  ifdef USE_LOCALE_NUMERIC
3326
3327     PL_numeric_radix_sv = newSVpvs(".");
3328
3329 #  endif
3330
3331 #  if defined(USE_POSIX_2008_LOCALE) && ! defined(HAS_QUERYLOCALE)
3332
3333     /* Initialize our records.  If we have POSIX 2008, we have LC_ALL */
3334     do_setlocale_c(LC_ALL, my_setlocale(LC_ALL, NULL));
3335
3336 #  endif
3337 #  ifdef LOCALE_ENVIRON_REQUIRED
3338
3339     /*
3340      * Ultrix setlocale(..., "") fails if there are no environment
3341      * variables from which to get a locale name.
3342      */
3343
3344 #    ifndef LC_ALL
3345 #      error Ultrix without LC_ALL not implemented
3346 #    else
3347
3348     {
3349         bool done = FALSE;
3350         if (lang) {
3351             sl_result[LC_ALL_INDEX] = do_setlocale_c(LC_ALL, setlocale_init);
3352             DEBUG_LOCALE_INIT(LC_ALL, setlocale_init, sl_result[LC_ALL_INDEX]);
3353             if (sl_result[LC_ALL_INDEX])
3354                 done = TRUE;
3355             else
3356                 setlocale_failure = TRUE;
3357         }
3358         if (! setlocale_failure) {
3359             const char * locale_param;
3360             for (i = 0; i < LC_ALL_INDEX; i++) {
3361                 locale_param = (! done && (lang || PerlEnv_getenv(category_names[i])))
3362                             ? setlocale_init
3363                             : NULL;
3364                 sl_result[i] = do_setlocale_r(categories[i], locale_param);
3365                 if (! sl_result[i]) {
3366                     setlocale_failure = TRUE;
3367                 }
3368                 DEBUG_LOCALE_INIT(categories[i], locale_param, sl_result[i]);
3369             }
3370         }
3371     }
3372
3373 #    endif /* LC_ALL */
3374 #  endif /* LOCALE_ENVIRON_REQUIRED */
3375
3376     /* We try each locale in the list until we get one that works, or exhaust
3377      * the list.  Normally the loop is executed just once.  But if setting the
3378      * locale fails, inside the loop we add fallback trials to the array and so
3379      * will execute the loop multiple times */
3380     trial_locales[0] = setlocale_init;
3381     trial_locales_count = 1;
3382
3383     for (i= 0; i < trial_locales_count; i++) {
3384         const char * trial_locale = trial_locales[i];
3385
3386         if (i > 0) {
3387
3388             /* XXX This is to preserve old behavior for LOCALE_ENVIRON_REQUIRED
3389              * when i==0, but I (khw) don't think that behavior makes much
3390              * sense */
3391             setlocale_failure = FALSE;
3392
3393 #  ifdef SYSTEM_DEFAULT_LOCALE
3394 #    ifdef WIN32    /* Note that assumes Win32 has LC_ALL */
3395
3396             /* On Windows machines, an entry of "" after the 0th means to use
3397              * the system default locale, which we now proceed to get. */
3398             if (strEQ(trial_locale, "")) {
3399                 unsigned int j;
3400
3401                 /* Note that this may change the locale, but we are going to do
3402                  * that anyway just below */
3403                 system_default_locale = do_setlocale_c(LC_ALL, "");
3404                 DEBUG_LOCALE_INIT(LC_ALL, "", system_default_locale);
3405
3406                 /* Skip if invalid or if it's already on the list of locales to
3407                  * try */
3408                 if (! system_default_locale) {
3409                     goto next_iteration;
3410                 }
3411                 for (j = 0; j < trial_locales_count; j++) {
3412                     if (strEQ(system_default_locale, trial_locales[j])) {
3413                         goto next_iteration;
3414                     }
3415                 }
3416
3417                 trial_locale = system_default_locale;
3418             }
3419 #    else
3420 #      error SYSTEM_DEFAULT_LOCALE only implemented for Win32
3421 #    endif
3422 #  endif /* SYSTEM_DEFAULT_LOCALE */
3423
3424         }   /* For i > 0 */
3425
3426 #  ifdef LC_ALL
3427
3428         sl_result[LC_ALL_INDEX] = do_setlocale_c(LC_ALL, trial_locale);
3429         DEBUG_LOCALE_INIT(LC_ALL, trial_locale, sl_result[LC_ALL_INDEX]);
3430         if (! sl_result[LC_ALL_INDEX]) {
3431             setlocale_failure = TRUE;
3432         }
3433         else {
3434             /* Since LC_ALL succeeded, it should have changed all the other
3435              * categories it can to its value; so we massage things so that the
3436              * setlocales below just return their category's current values.
3437              * This adequately handles the case in NetBSD where LC_COLLATE may
3438              * not be defined for a locale, and setting it individually will
3439              * fail, whereas setting LC_ALL succeeds, leaving LC_COLLATE set to
3440              * the POSIX locale. */
3441             trial_locale = NULL;
3442         }
3443
3444 #  endif /* LC_ALL */
3445
3446         if (! setlocale_failure) {
3447             unsigned int j;
3448             for (j = 0; j < NOMINAL_LC_ALL_INDEX; j++) {
3449                 curlocales[j]
3450                         = savepv(do_setlocale_r(categories[j], trial_locale));
3451                 if (! curlocales[j]) {
3452                     setlocale_failure = TRUE;
3453                 }
3454                 DEBUG_LOCALE_INIT(categories[j], trial_locale, curlocales[j]);
3455             }
3456
3457             if (! setlocale_failure) {  /* All succeeded */
3458                 break;  /* Exit trial_locales loop */
3459             }
3460         }
3461
3462         /* Here, something failed; will need to try a fallback. */
3463         ok = 0;
3464
3465         if (i == 0) {
3466             unsigned int j;
3467
3468             if (locwarn) { /* Output failure info only on the first one */
3469
3470 #  ifdef LC_ALL
3471
3472                 PerlIO_printf(Perl_error_log,
3473                 "perl: warning: Setting locale failed.\n");
3474
3475 #  else /* !LC_ALL */
3476
3477                 PerlIO_printf(Perl_error_log,
3478                 "perl: warning: Setting locale failed for the categories:\n\t");
3479
3480                 for (j = 0; j < NOMINAL_LC_ALL_INDEX; j++) {
3481                     if (! curlocales[j]) {
3482                         PerlIO_printf(Perl_error_log, category_names[j]);
3483                     }
3484                     else {
3485                         Safefree(curlocales[j]);
3486                     }
3487                 }
3488
3489 #  endif /* LC_ALL */
3490
3491                 PerlIO_printf(Perl_error_log,
3492                     "perl: warning: Please check that your locale settings:\n");
3493
3494 #  ifdef __GLIBC__
3495
3496                 PerlIO_printf(Perl_error_log,
3497                             "\tLANGUAGE = %c%s%c,\n",
3498                             language ? '"' : '(',
3499                             language ? language : "unset",
3500                             language ? '"' : ')');
3501 #  endif
3502
3503                 PerlIO_printf(Perl_error_log,
3504                             "\tLC_ALL = %c%s%c,\n",
3505                             lc_all ? '"' : '(',
3506                             lc_all ? lc_all : "unset",
3507                             lc_all ? '"' : ')');
3508
3509 #  if defined(USE_ENVIRON_ARRAY)
3510
3511                 {
3512                     char **e;
3513
3514                     /* Look through the environment for any variables of the
3515                      * form qr/ ^ LC_ [A-Z]+ = /x, except LC_ALL which was
3516                      * already handled above.  These are assumed to be locale
3517                      * settings.  Output them and their values. */
3518                     for (e = environ; *e; e++) {
3519                         const STRLEN prefix_len = sizeof("LC_") - 1;
3520                         STRLEN uppers_len;
3521
3522                         if (     strBEGINs(*e, "LC_")
3523                             && ! strBEGINs(*e, "LC_ALL=")
3524                             && (uppers_len = strspn(*e + prefix_len,
3525                                              "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
3526                             && ((*e)[prefix_len + uppers_len] == '='))
3527                         {
3528                             PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
3529                                 (int) (prefix_len + uppers_len), *e,
3530                                 *e + prefix_len + uppers_len + 1);
3531                         }
3532                     }
3533                 }
3534
3535 #  else
3536
3537                 PerlIO_printf(Perl_error_log,
3538                             "\t(possibly more locale environment variables)\n");
3539
3540 #  endif
3541
3542                 PerlIO_printf(Perl_error_log,
3543                             "\tLANG = %c%s%c\n",
3544                             lang ? '"' : '(',
3545                             lang ? lang : "unset",
3546                             lang ? '"' : ')');
3547
3548                 PerlIO_printf(Perl_error_log,
3549                             "    are supported and installed on your system.\n");
3550             }
3551
3552             /* Calculate what fallback locales to try.  We have avoided this
3553              * until we have to, because failure is quite unlikely.  This will
3554              * usually change the upper bound of the loop we are in.
3555              *
3556              * Since the system's default way of setting the locale has not
3557              * found one that works, We use Perl's defined ordering: LC_ALL,
3558              * LANG, and the C locale.  We don't try the same locale twice, so
3559              * don't add to the list if already there.  (On POSIX systems, the
3560              * LC_ALL element will likely be a repeat of the 0th element "",
3561              * but there's no harm done by doing it explicitly.
3562              *
3563              * Note that this tries the LC_ALL environment variable even on
3564              * systems which have no LC_ALL locale setting.  This may or may
3565              * not have been originally intentional, but there's no real need
3566              * to change the behavior. */
3567             if (lc_all) {
3568                 for (j = 0; j < trial_locales_count; j++) {
3569                     if (strEQ(lc_all, trial_locales[j])) {
3570                         goto done_lc_all;
3571                     }
3572                 }
3573                 trial_locales[trial_locales_count++] = lc_all;
3574             }
3575           done_lc_all:
3576
3577             if (lang) {
3578                 for (j = 0; j < trial_locales_count; j++) {
3579                     if (strEQ(lang, trial_locales[j])) {
3580                         goto done_lang;
3581                     }
3582                 }
3583                 trial_locales[trial_locales_count++] = lang;
3584             }
3585           done_lang:
3586
3587 #  if defined(WIN32) && defined(LC_ALL)
3588
3589             /* For Windows, we also try the system default locale before "C".
3590              * (If there exists a Windows without LC_ALL we skip this because
3591              * it gets too complicated.  For those, the "C" is the next
3592              * fallback possibility).  The "" is the same as the 0th element of
3593              * the array, but the code at the loop above knows to treat it
3594              * differently when not the 0th */
3595             trial_locales[trial_locales_count++] = "";
3596
3597 #  endif
3598
3599             for (j = 0; j < trial_locales_count; j++) {
3600                 if (strEQ("C", trial_locales[j])) {
3601                     goto done_C;
3602                 }
3603             }
3604             trial_locales[trial_locales_count++] = "C";
3605
3606           done_C: ;
3607         }   /* end of first time through the loop */
3608
3609 #  ifdef WIN32
3610
3611       next_iteration: ;
3612
3613 #  endif
3614
3615     }   /* end of looping through the trial locales */
3616
3617     if (ok < 1) {   /* If we tried to fallback */
3618         const char* msg;
3619         if (! setlocale_failure) {  /* fallback succeeded */
3620            msg = "Falling back to";
3621         }
3622         else {  /* fallback failed */
3623             unsigned int j;
3624
3625             /* We dropped off the end of the loop, so have to decrement i to
3626              * get back to the value the last time through */
3627             i--;
3628
3629             ok = -1;
3630             msg = "Failed to fall back to";
3631
3632             /* To continue, we should use whatever values we've got */
3633
3634             for (j = 0; j < NOMINAL_LC_ALL_INDEX; j++) {
3635                 Safefree(curlocales[j]);
3636                 curlocales[j] = savepv(do_setlocale_r(categories[j], NULL));
3637                 DEBUG_LOCALE_INIT(categories[j], NULL, curlocales[j]);
3638             }
3639         }
3640
3641         if (locwarn) {
3642             const char * description;
3643             const char * name = "";
3644             if (strEQ(trial_locales[i], "C")) {
3645                 description = "the standard locale";
3646                 name = "C";
3647             }
3648
3649 #  ifdef SYSTEM_DEFAULT_LOCALE
3650
3651             else if (strEQ(trial_locales[i], "")) {
3652                 description = "the system default locale";
3653                 if (system_default_locale) {
3654                     name = system_default_locale;
3655                 }
3656             }
3657
3658 #  endif /* SYSTEM_DEFAULT_LOCALE */
3659
3660             else {
3661                 description = "a fallback locale";
3662                 name = trial_locales[i];
3663             }
3664             if (name && strNE(name, "")) {
3665                 PerlIO_printf(Perl_error_log,
3666                     "perl: warning: %s %s (\"%s\").\n", msg, description, name);
3667             }
3668             else {
3669                 PerlIO_printf(Perl_error_log,
3670                                    "perl: warning: %s %s.\n", msg, description);
3671             }
3672         }
3673     } /* End of tried to fallback */
3674
3675     /* Done with finding the locales; update our records */
3676
3677 #  ifdef USE_LOCALE_CTYPE
3678
3679     new_ctype(curlocales[LC_CTYPE_INDEX]);
3680
3681 #  endif
3682 #  ifdef USE_LOCALE_COLLATE
3683
3684     new_collate(curlocales[LC_COLLATE_INDEX]);
3685
3686 #  endif
3687 #  ifdef USE_LOCALE_NUMERIC
3688
3689     new_numeric(curlocales[LC_NUMERIC_INDEX]);
3690
3691 #  endif
3692
3693     for (i = 0; i < NOMINAL_LC_ALL_INDEX; i++) {
3694
3695 #  if defined(USE_ITHREADS) && ! defined(USE_THREAD_SAFE_LOCALE)
3696
3697         /* This caches whether each category's locale is UTF-8 or not.  This
3698          * may involve changing the locale.  It is ok to do this at
3699          * initialization time before any threads have started, but not later
3700          * unless thread-safe operations are used.
3701          * Caching means that if the program heeds our dictate not to change
3702          * locales in threaded applications, this data will remain valid, and
3703          * it may get queried without having to change locales.  If the
3704          * environment is such that all categories have the same locale, this
3705          * isn't needed, as the code will not change the locale; but this
3706          * handles the uncommon case where the environment has disparate
3707          * locales for the categories */
3708         (void) _is_cur_LC_category_utf8(categories[i]);
3709
3710 #  endif
3711
3712         Safefree(curlocales[i]);
3713     }
3714
3715 #  if defined(USE_PERLIO) && defined(USE_LOCALE_CTYPE)
3716
3717     /* Set PL_utf8locale to TRUE if using PerlIO _and_ the current LC_CTYPE
3718      * locale is UTF-8.  The call to new_ctype() just above has already
3719      * calculated the latter value and saved it in PL_in_utf8_CTYPE_locale. If
3720      * both PL_utf8locale and PL_unicode (set by -C or by $ENV{PERL_UNICODE})
3721      * are true, perl.c:S_parse_body() will turn on the PerlIO :utf8 layer on
3722      * STDIN, STDOUT, STDERR, _and_ the default open discipline.  */
3723     PL_utf8locale = PL_in_utf8_CTYPE_locale;
3724
3725     /* Set PL_unicode to $ENV{PERL_UNICODE} if using PerlIO.
3726        This is an alternative to using the -C command line switch
3727        (the -C if present will override this). */
3728     {
3729          const char *p = PerlEnv_getenv("PERL_UNICODE");
3730          PL_unicode = p ? parse_unicode_opts(&p) : 0;
3731          if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
3732              PL_utf8cache = -1;
3733     }
3734
3735 #  endif
3736 #  ifdef __GLIBC__
3737
3738     Safefree(language);
3739
3740 #  endif
3741
3742     Safefree(lc_all);
3743     Safefree(lang);
3744
3745 #endif /* USE_LOCALE */
3746 #ifdef DEBUGGING
3747
3748     /* So won't continue to output stuff */
3749     DEBUG_INITIALIZATION_set(FALSE);
3750
3751 #endif
3752
3753     return ok;
3754 }
3755
3756 #ifdef USE_LOCALE_COLLATE
3757
3758 char *
3759 Perl__mem_collxfrm(pTHX_ const char *input_string,
3760                          STRLEN len,    /* Length of 'input_string' */
3761                          STRLEN *xlen,  /* Set to length of returned string
3762                                            (not including the collation index
3763                                            prefix) */
3764                          bool utf8      /* Is the input in UTF-8? */
3765                    )
3766 {
3767
3768     /* _mem_collxfrm() is a bit like strxfrm() but with two important
3769      * differences. First, it handles embedded NULs. Second, it allocates a bit
3770      * more memory than needed for the transformed data itself.  The real
3771      * transformed data begins at offset COLLXFRM_HDR_LEN.  *xlen is set to
3772      * the length of that, and doesn't include the collation index size.
3773      * Please see sv_collxfrm() to see how this is used. */
3774
3775 #define COLLXFRM_HDR_LEN    sizeof(PL_collation_ix)
3776
3777     char * s = (char *) input_string;
3778     STRLEN s_strlen = strlen(input_string);
3779     char *xbuf = NULL;
3780     STRLEN xAlloc;          /* xalloc is a reserved word in VC */
3781     STRLEN length_in_chars;
3782     bool first_time = TRUE; /* Cleared after first loop iteration */
3783
3784     PERL_ARGS_ASSERT__MEM_COLLXFRM;
3785
3786     /* Must be NUL-terminated */
3787     assert(*(input_string + len) == '\0');
3788
3789     /* If this locale has defective collation, skip */
3790     if (PL_collxfrm_base == 0 && PL_collxfrm_mult == 0) {
3791         DEBUG_L(PerlIO_printf(Perl_debug_log,
3792                       "_mem_collxfrm: locale's collation is defective\n"));
3793         goto bad;
3794     }
3795
3796     /* Replace any embedded NULs with the control that sorts before any others.
3797      * This will give as good as possible results on strings that don't
3798      * otherwise contain that character, but otherwise there may be
3799      * less-than-perfect results with that character and NUL.  This is
3800      * unavoidable unless we replace strxfrm with our own implementation. */
3801     if (UNLIKELY(s_strlen < len)) {   /* Only execute if there is an embedded
3802                                          NUL */
3803         char * e = s + len;
3804         char * sans_nuls;
3805         STRLEN sans_nuls_len;
3806         int try_non_controls;
3807         char this_replacement_char[] = "?\0";   /* Room for a two-byte string,
3808                                                    making sure 2nd byte is NUL.
3809                                                  */
3810         STRLEN this_replacement_len;
3811
3812         /* If we don't know what non-NUL control character sorts lowest for
3813          * this locale, find it */
3814         if (PL_strxfrm_NUL_replacement == '\0') {
3815             int j;
3816             char * cur_min_x = NULL;    /* The min_char's xfrm, (except it also
3817                                            includes the collation index
3818                                            prefixed. */
3819
3820             DEBUG_Lv(PerlIO_printf(Perl_debug_log, "Looking to replace NUL\n"));
3821
3822             /* Unlikely, but it may be that no control will work to replace
3823              * NUL, in which case we instead look for any character.  Controls
3824              * are preferred because collation order is, in general, context
3825              * sensitive, with adjoining characters affecting the order, and
3826              * controls are less likely to have such interactions, allowing the
3827              * NUL-replacement to stand on its own.  (Another way to look at it
3828              * is to imagine what would happen if the NUL were replaced by a
3829              * combining character; it wouldn't work out all that well.) */
3830             for (try_non_controls = 0;
3831                  try_non_controls < 2;
3832                  try_non_controls++)
3833             {
3834                 /* Look through all legal code points (NUL isn't) */
3835                 for (j = 1; j < 256; j++) {
3836                     char * x;       /* j's xfrm plus collation index */
3837                     STRLEN x_len;   /* length of 'x' */
3838                     STRLEN trial_len = 1;
3839                     char cur_source[] = { '\0', '\0' };
3840
3841                     /* Skip non-controls the first time through the loop.  The
3842                      * controls in a UTF-8 locale are the L1 ones */
3843                     if (! try_non_controls && (PL_in_utf8_COLLATE_locale)
3844                                                ? ! isCNTRL_L1(j)
3845                                                : ! isCNTRL_LC(j))
3846                     {
3847                         continue;
3848                     }
3849
3850                     /* Create a 1-char string of the current code point */
3851                     cur_source[0] = (char) j;
3852
3853                     /* Then transform it */
3854                     x = _mem_collxfrm(cur_source, trial_len, &x_len,
3855                                       0 /* The string is not in UTF-8 */);
3856
3857                     /* Ignore any character that didn't successfully transform.
3858                      * */
3859                     if (! x) {
3860                         continue;
3861                     }
3862
3863                     /* If this character's transformation is lower than
3864                      * the current lowest, this one becomes the lowest */
3865                     if (   cur_min_x == NULL
3866                         || strLT(x         + COLLXFRM_HDR_LEN,
3867                                  cur_min_x + COLLXFRM_HDR_LEN))
3868                     {
3869                         PL_strxfrm_NUL_replacement = j;
3870                         cur_min_x = x;
3871                     }
3872                     else {
3873                         Safefree(x);
3874                     }
3875                 } /* end of loop through all 255 characters */
3876
3877                 /* Stop looking if found */
3878                 if (cur_min_x) {
3879                     break;
3880                 }
3881
3882                 /* Unlikely, but possible, if there aren't any controls that
3883                  * work in the locale, repeat the loop, looking for any
3884                  * character that works */
3885                 DEBUG_L(PerlIO_printf(Perl_debug_log,
3886                 "_mem_collxfrm: No control worked.  Trying non-controls\n"));
3887             } /* End of loop to try first the controls, then any char */
3888
3889             if (! cur_min_x) {
3890                 DEBUG_L(PerlIO_printf(Perl_debug_log,
3891                     "_mem_collxfrm: Couldn't find any character to replace"
3892                     " embedded NULs in locale %s with", PL_collation_name));
3893                 goto bad;
3894             }
3895
3896             DEBUG_L(PerlIO_printf(Perl_debug_log,
3897                     "_mem_collxfrm: Replacing embedded NULs in locale %s with "
3898                     "0x%02X\n", PL_collation_name, PL_strxfrm_NUL_replacement));
3899
3900             Safefree(cur_min_x);
3901         } /* End of determining the character that is to replace NULs */
3902
3903         /* If the replacement is variant under UTF-8, it must match the
3904          * UTF8-ness of the original */
3905         if ( ! UVCHR_IS_INVARIANT(PL_strxfrm_NUL_replacement) && utf8) {
3906             this_replacement_char[0] =
3907                                 UTF8_EIGHT_BIT_HI(PL_strxfrm_NUL_replacement);
3908             this_replacement_char[1] =
3909                                 UTF8_EIGHT_BIT_LO(PL_strxfrm_NUL_replacement);
3910             this_replacement_len = 2;
3911         }
3912         else {
3913             this_replacement_char[0] = PL_strxfrm_NUL_replacement;
3914             /* this_replacement_char[1] = '\0' was done at initialization */
3915             this_replacement_len = 1;
3916         }
3917
3918         /* The worst case length for the replaced string would be if every
3919          * character in it is NUL.  Multiply that by the length of each
3920          * replacement, and allow for a trailing NUL */
3921         sans_nuls_len = (len * this_replacement_len) + 1;
3922         Newx(sans_nuls, sans_nuls_len, char);
3923         *sans_nuls = '\0';
3924
3925         /* Replace each NUL with the lowest collating control.  Loop until have
3926          * exhausted all the NULs */
3927         while (s + s_strlen < e) {
3928             my_strlcat(sans_nuls, s, sans_nuls_len);
3929
3930             /* Do the actual replacement */
3931             my_strlcat(sans_nuls, this_replacement_char, sans_nuls_len);
3932
3933             /* Move past the input NUL */
3934             s += s_strlen + 1;
3935             s_strlen = strlen(s);
3936         }
3937
3938         /* And add anything that trails the final NUL */
3939         my_strlcat(sans_nuls, s, sans_nuls_len);
3940
3941         /* Switch so below we transform this modified string */
3942         s = sans_nuls;
3943         len = strlen(s);
3944     } /* End of replacing NULs */
3945
3946     /* Make sure the UTF8ness of the string and locale match */
3947     if (utf8 != PL_in_utf8_COLLATE_locale) {
3948         /* XXX convert above Unicode to 10FFFF? */
3949         const char * const t = s;   /* Temporary so we can later find where the
3950                                        input was */
3951
3952         /* Here they don't match.  Change the string's to be what the locale is
3953          * expecting */
3954
3955         if (! utf8) { /* locale is UTF-8, but input isn't; upgrade the input */
3956             s = (char *) bytes_to_utf8((const U8 *) s, &len);
3957             utf8 = TRUE;
3958         }
3959         else {   /* locale is not UTF-8; but input is; downgrade the input */
3960
3961             s = (char *) bytes_from_utf8((const U8 *) s, &len, &utf8);
3962
3963             /* If the downgrade was successful we are done, but if the input
3964              * contains things that require UTF-8 to represent, have to do
3965              * damage control ... */
3966             if (UNLIKELY(utf8)) {
3967
3968                 /* What we do is construct a non-UTF-8 string with
3969                  *  1) the characters representable by a single byte converted
3970                  *     to be so (if necessary);
3971                  *  2) and the rest converted to collate the same as the
3972                  *     highest collating representable character.  That makes
3973                  *     them collate at the end.  This is similar to how we
3974                  *     handle embedded NULs, but we use the highest collating
3975                  *     code point instead of the smallest.  Like the NUL case,
3976                  *     this isn't perfect, but is the best we can reasonably
3977                  *     do.  Every above-255 code point will sort the same as
3978                  *     the highest-sorting 0-255 code point.  If that code
3979                  *     point can combine in a sequence with some other code
3980                  *     points for weight calculations, us changing something to
3981                  *     be it can adversely affect the results.  But in most
3982                  *     cases, it should work reasonably.  And note that this is
3983                  *     really an illegal situation: using code points above 255
3984                  *     on a locale where only 0-255 are valid.  If two strings
3985                  *     sort entirely equal, then the sort order for the
3986                  *     above-255 code points will be in code point order. */
3987
3988                 utf8 = FALSE;
3989
3990                 /* If we haven't calculated the code point with the maximum
3991                  * collating order for this locale, do so now */
3992                 if (! PL_strxfrm_max_cp) {
3993                     int j;
3994
3995                     /* The current transformed string that collates the
3996                      * highest (except it also includes the prefixed collation
3997                      * index. */
3998                     char * cur_max_x = NULL;
3999
4000                     /* Look through all legal code points (NUL isn't) */
4001                     for (j = 1; j < 256; j++) {
4002                         char * x;
4003                         STRLEN x_len;
4004                         char cur_source[] = { '\0', '\0' };
4005
4006                         /* Create a 1-char string of the current code point */
4007                         cur_source[0] = (char) j;
4008
4009                         /* Then transform it */
4010                         x = _mem_collxfrm(cur_source, 1, &x_len, FALSE);
4011
4012                         /* If something went wrong (which it shouldn't), just
4013                          * ignore this code point */
4014                         if (! x) {
4015                             continue;
4016                         }
4017
4018                         /* If this character's transformation is higher than
4019                          * the current highest, this one becomes the highest */
4020                         if (   cur_max_x == NULL
4021                             || strGT(x         + COLLXFRM_HDR_LEN,
4022                                      cur_max_x + COLLXFRM_HDR_LEN))
4023                         {
4024                             PL_strxfrm_max_cp = j;
4025                             cur_max_x = x;
4026                         }
4027                         else {
4028                             Safefree(x);
4029                         }
4030                     }
4031
4032                     if (! cur_max_x) {
4033                         DEBUG_L(PerlIO_printf(Perl_debug_log,
4034                             "_mem_collxfrm: Couldn't find any character to"
4035                             " replace above-Latin1 chars in locale %s with",
4036                             PL_collation_name));
4037                         goto bad;
4038                     }
4039
4040                     DEBUG_L(PerlIO_printf(Perl_debug_log,
4041                             "_mem_collxfrm: highest 1-byte collating character"
4042                             " in locale %s is 0x%02X\n",
4043                             PL_collation_name,
4044                             PL_strxfrm_max_cp));
4045
4046                     Safefree(cur_max_x);
4047                 }
4048
4049                 /* Here we know which legal code point collates the highest.
4050                  * We are ready to construct the non-UTF-8 string.  The length
4051                  * will be at least 1 byte smaller than the input string
4052                  * (because we changed at least one 2-byte character into a
4053                  * single byte), but that is eaten up by the trailing NUL */
4054                 Newx(s, len, char);
4055
4056                 {
4057                     STRLEN i;
4058                     STRLEN d= 0;
4059                     char * e = (char *) t + len;
4060
4061                     for (i = 0; i < len; i+= UTF8SKIP(t + i)) {
4062                         U8 cur_char = t[i];
4063                         if (UTF8_IS_INVARIANT(cur_char)) {
4064                             s[d++] = cur_char;
4065                         }
4066                         else if (UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(t + i, e)) {
4067                             s[d++] = EIGHT_BIT_UTF8_TO_NATIVE(cur_char, t[i+1]);
4068                         }
4069                         else {  /* Replace illegal cp with highest collating
4070                                    one */
4071                             s[d++] = PL_strxfrm_max_cp;
4072                         }
4073                     }
4074                     s[d++] = '\0';
4075                     Renew(s, d, char);   /* Free up unused space */
4076                 }
4077             }
4078         }
4079
4080         /* Here, we have constructed a modified version of the input.  It could
4081          * be that we already had a modified copy before we did this version.
4082          * If so, that copy is no longer needed */
4083         if (t != input_string) {
4084             Safefree(t);
4085         }
4086     }
4087
4088     length_in_chars = (utf8)
4089                       ? utf8_length((U8 *) s, (U8 *) s + len)
4090                       : len;
4091
4092     /* The first element in the output is the collation id, used by
4093      * sv_collxfrm(); then comes the space for the transformed string.  The
4094      * equation should give us a good estimate as to how much is needed */
4095     xAlloc = COLLXFRM_HDR_LEN
4096            + PL_collxfrm_base
4097            + (PL_collxfrm_mult * length_in_chars);
4098     Newx(xbuf, xAlloc, char);
4099     if (UNLIKELY(! xbuf)) {
4100         DEBUG_L(PerlIO_printf(Perl_debug_log,
4101                       "_mem_collxfrm: Couldn't malloc %zu bytes\n", xAlloc));
4102         goto bad;
4103     }
4104
4105     /* Store the collation id */
4106     *(U32*)xbuf = PL_collation_ix;
4107
4108     /* Then the transformation of the input.  We loop until successful, or we
4109      * give up */
4110     for (;;) {
4111
4112         *xlen = strxfrm(xbuf + COLLXFRM_HDR_LEN, s, xAlloc - COLLXFRM_HDR_LEN);
4113
4114         /* If the transformed string occupies less space than we told strxfrm()
4115          * was available, it means it successfully transformed the whole
4116          * string. */
4117         if (*xlen < xAlloc - COLLXFRM_HDR_LEN) {
4118
4119             /* Some systems include a trailing NUL in the returned length.
4120              * Ignore it, using a loop in case multiple trailing NULs are
4121              * returned. */
4122             while (   (*xlen) > 0
4123                    && *(xbuf + COLLXFRM_HDR_LEN + (*xlen) - 1) == '\0')
4124             {
4125                 (*xlen)--;
4126             }
4127
4128             /* If the first try didn't get it, it means our prediction was low.
4129              * Modify the coefficients so that we predict a larger value in any
4130              * future transformations */
4131             if (! first_time) {
4132                 STRLEN needed = *xlen + 1;   /* +1 For trailing NUL */
4133                 STRLEN computed_guess = PL_collxfrm_base
4134                                       + (PL_collxfrm_mult * length_in_chars);
4135
4136                 /* On zero-length input, just keep current slope instead of
4137                  * dividing by 0 */
4138                 const STRLEN new_m = (length_in_chars != 0)
4139                                      ? needed / length_in_chars
4140                                      : PL_collxfrm_mult;
4141
4142                 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
4143                     "%s: %d: initial size of %zu bytes for a length "
4144                     "%zu string was insufficient, %zu needed\n",
4145                     __FILE__, __LINE__,
4146                     computed_guess, length_in_chars, needed));
4147
4148                 /* If slope increased, use it, but discard this result for
4149                  * length 1 strings, as we can't be sure that it's a real slope
4150                  * change */
4151                 if (length_in_chars > 1 && new_m  > PL_collxfrm_mult) {
4152
4153 #  ifdef DEBUGGING
4154
4155                     STRLEN old_m = PL_collxfrm_mult;
4156                     STRLEN old_b = PL_collxfrm_base;
4157
4158 #  endif
4159
4160                     PL_collxfrm_mult = new_m;
4161                     PL_collxfrm_base = 1;   /* +1 For trailing NUL */
4162                     computed_guess = PL_collxfrm_base
4163                                     + (PL_collxfrm_mult * length_in_chars);
4164                     if (computed_guess < needed) {
4165                         PL_collxfrm_base += needed - computed_guess;
4166                     }
4167
4168                     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
4169                         "%s: %d: slope is now %zu; was %zu, base "
4170                         "is now %zu; was %zu\n",
4171                         __FILE__, __LINE__,
4172                         PL_collxfrm_mult, old_m,
4173                         PL_collxfrm_base, old_b));
4174                 }
4175                 else {  /* Slope didn't change, but 'b' did */
4176                     const STRLEN new_b = needed
4177                                         - computed_guess
4178                                         + PL_collxfrm_base;
4179                     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
4180                         "%s: %d: base is now %zu; was %zu\n",
4181                         __FILE__, __LINE__,
4182                         new_b, PL_collxfrm_base));
4183                     PL_collxfrm_base = new_b;
4184                 }
4185             }
4186
4187             break;
4188         }
4189
4190         if (UNLIKELY(*xlen >= PERL_INT_MAX)) {
4191             DEBUG_L(PerlIO_printf(Perl_debug_log,
4192                   "_mem_collxfrm: Needed %zu bytes, max permissible is %u\n",
4193                   *xlen, PERL_INT_MAX));
4194             goto bad;
4195         }
4196
4197         /* A well-behaved strxfrm() returns exactly how much space it needs
4198          * (usually not including the trailing NUL) when it fails due to not
4199          * enough space being provided.  Assume that this is the case unless
4200          * it's been proven otherwise */
4201         if (LIKELY(PL_strxfrm_is_behaved) && first_time) {
4202             xAlloc = *xlen + COLLXFRM_HDR_LEN + 1;
4203         }
4204         else { /* Here, either:
4205                 *  1)  The strxfrm() has previously shown bad behavior; or
4206                 *  2)  It isn't the first time through the loop, which means
4207                 *      that the strxfrm() is now showing bad behavior, because
4208                 *      we gave it what it said was needed in the previous
4209                 *      iteration, and it came back saying it needed still more.
4210                 *      (Many versions of cygwin fit this.  When the buffer size
4211                 *      isn't sufficient, they return the input size instead of
4212                 *      how much is needed.)
4213                 * Increase the buffer size by a fixed percentage and try again.
4214                 * */
4215             xAlloc += (xAlloc / 4) + 1;
4216             PL_strxfrm_is_behaved = FALSE;
4217
4218 #  ifdef DEBUGGING
4219
4220             if (DEBUG_Lv_TEST || debug_initialization) {
4221                 PerlIO_printf(Perl_debug_log,
4222                 "_mem_collxfrm required more space than previously calculated"
4223                 " for locale %s, trying again with new guess=%d+%zu\n",
4224                 PL_collation_name, (int) COLLXFRM_HDR_LEN,
4225                 xAlloc - COLLXFRM_HDR_LEN);
4226             }
4227
4228 #  endif
4229
4230         }
4231
4232         Renew(xbuf, xAlloc, char);
4233         if (UNLIKELY(! xbuf)) {
4234             DEBUG_L(PerlIO_printf(Perl_debug_log,
4235                       "_mem_collxfrm: Couldn't realloc %zu bytes\n", xAlloc));
4236             goto bad;
4237         }
4238
4239         first_time = FALSE;
4240     }
4241
4242
4243 #  ifdef DEBUGGING
4244
4245     if (DEBUG_Lv_TEST || debug_initialization) {
4246
4247         print_collxfrm_input_and_return(s, s + len, xlen, utf8);
4248         PerlIO_printf(Perl_debug_log, "Its xfrm is:");
4249         PerlIO_printf(Perl_debug_log, "%s\n",
4250                       _byte_dump_string((U8 *) xbuf + COLLXFRM_HDR_LEN,
4251                        *xlen, 1));
4252     }
4253
4254 #  endif
4255
4256     /* Free up unneeded space; retain ehough for trailing NUL */
4257     Renew(xbuf, COLLXFRM_HDR_LEN + *xlen + 1, char);
4258
4259     if (s != input_string) {
4260         Safefree(s);
4261     }
4262
4263     return xbuf;
4264
4265   bad:
4266     Safefree(xbuf);
4267     if (s != input_string) {
4268         Safefree(s);
4269     }
4270     *xlen = 0;
4271
4272 #  ifdef DEBUGGING
4273
4274     if (DEBUG_Lv_TEST || debug_initialization) {
4275         print_collxfrm_input_and_return(s, s + len, NULL, utf8);
4276     }
4277
4278 #  endif
4279
4280     return NULL;
4281 }
4282
4283 #  ifdef DEBUGGING
4284
4285 STATIC void
4286 S_print_collxfrm_input_and_return(pTHX_
4287                                   const char * const s,
4288                                   const char * const e,
4289                                   const STRLEN * const xlen,
4290                                   const bool is_utf8)
4291 {
4292
4293     PERL_ARGS_ASSERT_PRINT_COLLXFRM_INPUT_AND_RETURN;
4294
4295     PerlIO_printf(Perl_debug_log, "_mem_collxfrm[%" UVuf "]: returning ",
4296                                                         (UV)PL_collation_ix);
4297     if (xlen) {
4298         PerlIO_printf(Perl_debug_log, "%zu", *xlen);
4299     }
4300     else {
4301         PerlIO_printf(Perl_debug_log, "NULL");
4302     }
4303     PerlIO_printf(Perl_debug_log, " for locale '%s', string='",
4304                                                             PL_collation_name);
4305     print_bytes_for_locale(s, e, is_utf8);
4306
4307     PerlIO_printf(Perl_debug_log, "'\n");
4308 }
4309
4310 #  endif    /* DEBUGGING */
4311 #endif /* USE_LOCALE_COLLATE */
4312 #ifdef DEBUGGING
4313
4314 STATIC void
4315 S_print_bytes_for_locale(pTHX_
4316                     const char * const s,
4317                     const char * const e,
4318                     const bool is_utf8)
4319 {
4320     const char * t = s;
4321     bool prev_was_printable = TRUE;
4322     bool first_time = TRUE;
4323
4324     PERL_ARGS_ASSERT_PRINT_BYTES_FOR_LOCALE;
4325
4326     while (t < e) {
4327         UV cp = (is_utf8)
4328                 ?  utf8_to_uvchr_buf((U8 *) t, e, NULL)
4329                 : * (U8 *) t;
4330         if (isPRINT(cp)) {
4331             if (! prev_was_printable) {
4332                 PerlIO_printf(Perl_debug_log, " ");
4333             }
4334             PerlIO_printf(Perl_debug_log, "%c", (U8) cp);
4335             prev_was_printable = TRUE;
4336         }
4337         else {
4338             if (! first_time) {
4339                 PerlIO_printf(Perl_debug_log, " ");
4340             }
4341             PerlIO_printf(Perl_debug_log, "%02" UVXf, cp);
4342             prev_was_printable = FALSE;
4343         }
4344         t += (is_utf8) ? UTF8SKIP(t) : 1;
4345         first_time = FALSE;
4346     }
4347 }
4348
4349 #endif   /* #ifdef DEBUGGING */
4350
4351 #ifdef USE_LOCALE
4352
4353 STATIC const char *
4354 S_switch_category_locale_to_template(pTHX_ const int switch_category, const int template_category, const char * template_locale)
4355 {
4356     /* Changes the locale for LC_'switch_category" to that of
4357      * LC_'template_category', if they aren't already the same.  If not NULL,
4358      * 'template_locale' is the locale that 'template_category' is in.
4359      *
4360      * Returns a copy of the name of the original locale for 'switch_category'
4361      * so can be switched back to with the companion function
4362      * restore_switched_locale(),  (NULL if no restoral is necessary.) */
4363
4364     char * restore_to_locale = NULL;
4365
4366     if (switch_category == template_category) { /* No changes needed */
4367         return NULL;
4368     }
4369
4370     /* Find the original locale of the category we may need to change, so that
4371      * it can be restored to later */
4372     restore_to_locale = stdize_locale(savepv(do_setlocale_r(switch_category,
4373                                                             NULL)));
4374     if (! restore_to_locale) {
4375         Perl_croak(aTHX_
4376              "panic: %s: %d: Could not find current %s locale, errno=%d\n",
4377                 __FILE__, __LINE__, category_name(switch_category), errno);
4378     }
4379
4380     /* If the locale of the template category wasn't passed in, find it now */
4381     if (template_locale == NULL) {
4382         template_locale = do_setlocale_r(template_category, NULL);
4383         if (! template_locale) {
4384             Perl_croak(aTHX_
4385              "panic: %s: %d: Could not find current %s locale, errno=%d\n",
4386                    __FILE__, __LINE__, category_name(template_category), errno);
4387         }
4388     }
4389
4390     /* It the locales are the same, there's nothing to do */
4391     if (strEQ(restore_to_locale, template_locale)) {
4392         Safefree(restore_to_locale);
4393
4394         DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s locale unchanged as %s\n",
4395                             category_name(switch_category), restore_to_locale));
4396
4397         return NULL;
4398     }
4399
4400     /* Finally, change the locale to the template one */
4401     if (! do_setlocale_r(switch_category, template_locale)) {
4402         Perl_croak(aTHX_
4403          "panic: %s: %d: Could not change %s locale to %s, errno=%d\n",
4404                             __FILE__, __LINE__, category_name(switch_category),
4405                                                        template_locale, errno);
4406     }
4407
4408     DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s locale switched to %s\n",
4409                             category_name(switch_category), template_locale));
4410
4411     return restore_to_locale;
4412 }
4413
4414 STATIC void
4415 S_restore_switched_locale(pTHX_ const int category, const char * const original_locale)
4416 {
4417     /* Restores the locale for LC_'category' to 'original_locale' (which is a
4418      * copy that will be freed by this function), or do nothing if the latter
4419      * parameter is NULL */
4420
4421     if (original_locale == NULL) {
4422         return;
4423     }
4424
4425     if (! do_setlocale_r(category, original_locale)) {
4426         Perl_croak(aTHX_
4427              "panic: %s: %d: setlocale %s restore to %s failed, errno=%d\n",
4428                  __FILE__, __LINE__,
4429                              category_name(category), original_locale, errno);
4430     }
4431
4432     Safefree(original_locale);
4433 }
4434
4435 /* is_cur_LC_category_utf8 uses a small char buffer to avoid malloc/free */
4436 #define CUR_LC_BUFFER_SIZE  64
4437
4438 bool
4439 Perl__is_cur_LC_category_utf8(pTHX_ int category)
4440 {
4441     /* Returns TRUE if the current locale for 'category' is UTF-8; FALSE
4442      * otherwise. 'category' may not be LC_ALL.  If the platform doesn't have
4443      * nl_langinfo(), nor MB_CUR_MAX, this employs a heuristic, which hence
4444      * could give the wrong result.  The result will very likely be correct for
4445      * languages that have commonly used non-ASCII characters, but for notably
4446      * English, it comes down to if the locale's name ends in something like
4447      * "UTF-8".  It errs on the side of not being a UTF-8 locale.
4448      *
4449      * If the platform is early C89, not containing mbtowc(), or we are
4450      * compiled to not pay attention to LC_CTYPE, this employs heuristics.
4451      * These work very well for non-Latin locales or those whose currency
4452      * symbol isn't a '$' nor plain ASCII text.  But without LC_CTYPE and at
4453      * least MB_CUR_MAX, English locales with an ASCII currency symbol depend
4454      * on the name containing UTF-8 or not. */
4455
4456     /* Name of current locale corresponding to the input category */
4457     const char *save_input_locale = NULL;
4458
4459     bool is_utf8 = FALSE;                /* The return value */
4460
4461     /* The variables below are for the cache of previous lookups using this
4462      * function.  The cache is a C string, described at the definition for
4463      * 'C_and_POSIX_utf8ness'.
4464      *
4465      * The first part of the cache is fixed, for the C and POSIX locales.  The
4466      * varying part starts just after them. */
4467     char * utf8ness_cache = PL_locale_utf8ness + STRLENs(C_and_POSIX_utf8ness);
4468
4469     Size_t utf8ness_cache_size; /* Size of the varying portion */
4470     Size_t input_name_len;      /* Length in bytes of save_input_locale */
4471     Size_t input_name_len_with_overhead;    /* plus extra chars used to store
4472                                                the name in the cache */
4473     char * delimited;           /* The name plus the delimiters used to store
4474                                    it in the cache */
4475     char buffer[CUR_LC_BUFFER_SIZE];        /* small buffer */
4476     char * name_pos;            /* position of 'delimited' in the cache, or 0
4477                                    if not there */
4478
4479
4480 #  ifdef LC_ALL
4481
4482     assert(category != LC_ALL);
4483
4484 #  endif
4485
4486     /* Get the desired category's locale */
4487     save_input_locale = stdize_locale(savepv(do_setlocale_r(category, NULL)));
4488     if (! save_input_locale) {
4489         Perl_croak(aTHX_
4490              "panic: %s: %d: Could not find current %s locale, errno=%d\n",
4491                      __FILE__, __LINE__, category_name(category), errno);
4492     }
4493
4494     DEBUG_L(PerlIO_printf(Perl_debug_log,
4495                           "Current locale for %s is %s\n",
4496                           category_name(category), save_input_locale));
4497
4498     input_name_len = strlen(save_input_locale);
4499
4500     /* In our cache, each name is accompanied by two delimiters and a single
4501      * utf8ness digit */
4502     input_name_len_with_overhead = input_name_len + 3;
4503
4504     if ( input_name_len_with_overhead <= CUR_LC_BUFFER_SIZE ) {
4505         /* we can use the buffer, avoid a malloc */
4506         delimited = buffer;
4507     } else { /* need a malloc */
4508         /* Allocate and populate space for a copy of the name surrounded by the
4509          * delimiters */
4510         Newx(delimited, input_name_len_with_overhead, char);
4511     }
4512
4513     delimited[0] = UTF8NESS_SEP[0];
4514     Copy(save_input_locale, delimited + 1, input_name_len, char);
4515     delimited[input_name_len+1] = UTF8NESS_PREFIX[0];
4516     delimited[input_name_len+2] = '\0';
4517
4518     /* And see if that is in the cache */
4519     name_pos = instr(PL_locale_utf8ness, delimited);
4520     if (name_pos) {
4521         is_utf8 = *(name_pos + input_name_len_with_overhead - 1) - '0';
4522
4523 #  ifdef DEBUGGING
4524
4525         if (DEBUG_Lv_TEST || debug_initialization) {
4526             PerlIO_printf(Perl_debug_log, "UTF8ness for locale %s=%d, \n",
4527                                           save_input_locale, is_utf8);
4528         }
4529
4530 #  endif
4531
4532         /* And, if not already in that position, move it to the beginning of
4533          * the non-constant portion of the list, since it is the most recently
4534          * used.  (We don't have to worry about overflow, since just moving
4535          * existing names around) */
4536         if (name_pos > utf8ness_cache) {
4537             Move(utf8ness_cache,
4538                  utf8ness_cache + input_name_len_with_overhead,
4539                  name_pos - utf8ness_cache, char);
4540             Copy(delimited,
4541                  utf8ness_cache,
4542                  input_name_len_with_overhead - 1, char);
4543             utf8ness_cache[input_name_len_with_overhead - 1] = is_utf8 + '0';
4544         }
4545
4546         /* free only when not using the buffer */
4547         if ( delimited != buffer ) Safefree(delimited);
4548         Safefree(save_input_locale);
4549         return is_utf8;
4550     }
4551
4552     /* Here we don't have stored the utf8ness for the input locale.  We have to
4553      * calculate it */
4554
4555 #  if        defined(USE_LOCALE_CTYPE)                                  \
4556      && (    defined(HAS_NL_LANGINFO)                                   \
4557          || (defined(HAS_MBTOWC) || defined(HAS_MBRTOWC)))
4558
4559     {
4560         const char *original_ctype_locale
4561                         = switch_category_locale_to_template(LC_CTYPE,
4562                                                              category,
4563                                                              save_input_locale);
4564
4565         /* Here the current LC_CTYPE is set to the locale of the category whose
4566          * information is desired.  This means that nl_langinfo() and mbtowc()
4567          * should give the correct results */
4568
4569 #    ifdef MB_CUR_MAX  /* But we can potentially rule out UTF-8ness, avoiding
4570                           calling the functions if we have this */
4571
4572             /* Standard UTF-8 needs at least 4 bytes to represent the maximum
4573              * Unicode code point. */
4574
4575             DEBUG_L(PerlIO_printf(Perl_debug_log, "%s: %d: MB_CUR_MAX=%d\n",
4576                                        __FILE__, __LINE__, (int) MB_CUR_MAX));
4577             if ((unsigned) MB_CUR_MAX < STRLENs(MAX_UNICODE_UTF8)) {
4578                 is_utf8 = FALSE;
4579                 restore_switched_locale(LC_CTYPE, original_ctype_locale);
4580                 goto finish_and_return;
4581             }
4582
4583 #    endif
4584 #    if defined(HAS_NL_LANGINFO)
4585
4586         { /* The task is easiest if the platform has this POSIX 2001 function.
4587              Except on some platforms it can wrongly return "", so have to have
4588              a fallback.  And it can return that it's UTF-8, even if there are
4589              variances from that.  For example, Turkish locales may use the
4590              alternate dotted I rules, and sometimes it appears to be a
4591              defective locale definition.  XXX We should probably check for
4592              these in the Latin1 range and warn (but on glibc, requires
4593              iswalnum() etc. due to their not handling 80-FF correctly */
4594             const char *codeset = my_nl_langinfo(CODESET, FALSE);
4595                                           /* FALSE => already in dest locale */
4596
4597             DEBUG_Lv(PerlIO_printf(Perl_debug_log,
4598                             "\tnllanginfo returned CODESET '%s'\n", codeset));
4599
4600             if (codeset && strNE(codeset, "")) {
4601
4602                               /* If the implementation of foldEQ() somehow were
4603                                * to change to not go byte-by-byte, this could
4604                                * read past end of string, as only one length is
4605                                * checked.  But currently, a premature NUL will
4606                                * compare false, and it will stop there */
4607                 is_utf8 = cBOOL(   foldEQ(codeset, STR_WITH_LEN("UTF-8"))
4608                                 || foldEQ(codeset, STR_WITH_LEN("UTF8")));
4609
4610                 DEBUG_L(PerlIO_printf(Perl_debug_log,
4611                        "\tnllanginfo returned CODESET '%s'; ?UTF8 locale=%d\n",
4612                                                      codeset,         is_utf8));
4613                 restore_switched_locale(LC_CTYPE, original_ctype_locale);
4614                 goto finish_and_return;
4615             }
4616         }
4617
4618 #    endif
4619 #    if defined(HAS_MBTOWC) || defined(HAS_MBRTOWC)
4620      /* We can see if this is a UTF-8-like locale if have mbtowc().  It was a
4621       * late adder to C89, so very likely to have it.  However, testing has
4622       * shown that, like nl_langinfo() above, there are locales that are not
4623       * strictly UTF-8 that this will return that they are */
4624
4625         {
4626             wchar_t wc;
4627             int len;
4628             dSAVEDERRNO;
4629
4630 #      if defined(HAS_MBRTOWC) && defined(USE_ITHREADS)
4631
4632             mbstate_t ps;
4633
4634 #      endif
4635
4636             /* mbrtowc() and mbtowc() convert a byte string to a wide
4637              * character.  Feed a byte string to one of them and check that the
4638              * result is the expected Unicode code point */
4639
4640 #      if defined(HAS_MBRTOWC) && defined(USE_ITHREADS)
4641             /* Prefer this function if available, as it's reentrant */
4642
4643             memset(&ps, 0, sizeof(ps));;
4644             PERL_UNUSED_RESULT(mbrtowc(&wc, NULL, 0, &ps)); /* Reset any shift
4645                                                                state */
4646             SETERRNO(0, 0);
4647             len = mbrtowc(&wc, STR_WITH_LEN(REPLACEMENT_CHARACTER_UTF8), &ps);
4648             SAVE_ERRNO;
4649
4650 #      else
4651
4652             LOCALE_LOCK;
4653             PERL_UNUSED_RESULT(mbtowc(&wc, NULL, 0));/* Reset any shift state */
4654             SETERRNO(0, 0);
4655             len = mbtowc(&wc, STR_WITH_LEN(REPLACEMENT_CHARACTER_UTF8));
4656             SAVE_ERRNO;
4657             LOCALE_UNLOCK;
4658
4659 #      endif
4660
4661             RESTORE_ERRNO;
4662             DEBUG_Lv(PerlIO_printf(Perl_debug_log,
4663                     "\treturn from mbtowc; len=%d; code_point=%x; errno=%d\n",
4664                                    len,      (unsigned int) wc, GET_ERRNO));
4665
4666             is_utf8 = cBOOL(   len == STRLENs(REPLACEMENT_CHARACTER_UTF8)
4667                             && wc == (wchar_t) UNICODE_REPLACEMENT);
4668         }
4669
4670 #    endif
4671
4672         restore_switched_locale(LC_CTYPE, original_ctype_locale);
4673         goto finish_and_return;
4674     }
4675
4676 #  else
4677
4678         /* Here, we must have a C89 compiler that doesn't have mbtowc().  Next
4679          * try looking at the currency symbol to see if it disambiguates
4680          * things.  Often that will be in the native script, and if the symbol
4681          * isn't in UTF-8, we know that the locale isn't.  If it is non-ASCII
4682          * UTF-8, we infer that the locale is too, as the odds of a non-UTF8
4683          * string being valid UTF-8 are quite small */
4684
4685 #    ifdef USE_LOCALE_MONETARY
4686
4687         /* If have LC_MONETARY, we can look at the currency symbol.  Often that
4688          * will be in the native script.  We do this one first because there is
4689          * just one string to examine, so potentially avoids work */
4690
4691         {
4692             const char *original_monetary_locale
4693                         = switch_category_locale_to_template(LC_MONETARY,
4694                                                              category,
4695                                                              save_input_locale);
4696             bool only_ascii = FALSE;
4697             const U8 * currency_string
4698                             = (const U8 *) my_nl_langinfo(CRNCYSTR, FALSE);
4699                                       /* 2nd param not relevant for this item */
4700             const U8 * first_variant;
4701
4702             assert(   *currency_string == '-'
4703                    || *currency_string == '+'
4704                    || *currency_string == '.');
4705
4706             currency_string++;
4707
4708             if (is_utf8_invariant_string_loc(currency_string, 0, &first_variant))
4709             {
4710                 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));
4711                 only_ascii = TRUE;
4712             }
4713             else {
4714                 is_utf8 = is_strict_utf8_string(first_variant, 0);
4715             }
4716
4717             restore_switched_locale(LC_MONETARY, original_monetary_locale);
4718
4719             if (! only_ascii) {
4720
4721                 /* It isn't a UTF-8 locale if the symbol is not legal UTF-8;
4722                  * otherwise assume the locale is UTF-8 if and only if the symbol
4723                  * is non-ascii UTF-8. */
4724                 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "\t?Currency symbol for %s is UTF-8=%d\n",
4725                                         save_input_locale, is_utf8));
4726                 goto finish_and_return;
4727             }
4728         }
4729
4730 #    endif /* USE_LOCALE_MONETARY */
4731 #    if defined(HAS_STRFTIME) && defined(USE_LOCALE_TIME)
4732
4733     /* Still haven't found a non-ASCII string to disambiguate UTF-8 or not.  Try
4734      * the names of the months and weekdays, timezone, and am/pm indicator */
4735         {
4736             const char *original_time_locale
4737                             = switch_category_locale_to_template(LC_TIME,
4738                                                                  category,
4739                                                                  save_input_locale);
4740             int hour = 10;
4741             bool is_dst = FALSE;
4742             int dom = 1;
4743             int month = 0;
4744             int i;
4745             char * formatted_time;
4746
4747             /* Here the current LC_TIME is set to the locale of the category
4748              * whose information is desired.  Look at all the days of the week and
4749              * month names, and the timezone and am/pm indicator for UTF-8 variant
4750              * characters.  The first such a one found will tell us if the locale
4751              * is UTF-8 or not */
4752
4753             for (i = 0; i < 7 + 12; i++) {  /* 7 days; 12 months */
4754                 formatted_time = my_strftime("%A %B %Z %p",
4755                                 0, 0, hour, dom, month, 2012 - 1900, 0, 0, is_dst);
4756                 if ( ! formatted_time
4757                     || is_utf8_invariant_string((U8 *) formatted_time, 0))
4758                 {
4759
4760                     /* Here, we didn't find a non-ASCII.  Try the next time through
4761                      * with the complemented dst and am/pm, and try with the next
4762                      * weekday.  After we have gotten all weekdays, try the next
4763                      * month */
4764                     is_dst = ! is_dst;
4765                     hour = (hour + 12) % 24;
4766                     dom++;
4767                     if (i > 6) {
4768                         month++;
4769                     }
4770                     continue;
4771                 }
4772
4773                 /* Here, we have a non-ASCII.  Return TRUE is it is valid UTF8;
4774                  * false otherwise.  But first, restore LC_TIME to its original
4775                  * locale if we changed it */
4776                 restore_switched_locale(LC_TIME, original_time_locale);
4777
4778                 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "\t?time-related strings for %s are UTF-8=%d\n",
4779                                     save_input_locale,
4780                                     is_utf8_string((U8 *) formatted_time, 0)));
4781                 is_utf8 = is_utf8_string((U8 *) formatted_time, 0);
4782                 goto finish_and_return;
4783             }
4784
4785             /* Falling off the end of the loop indicates all the names were just
4786              * ASCII.  Go on to the next test.  If we changed it, restore LC_TIME
4787              * to its original locale */
4788             restore_switched_locale(LC_TIME, original_time_locale);
4789             DEBUG_Lv(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));
4790         }
4791
4792 #    endif
4793
4794 #    if 0 && defined(USE_LOCALE_MESSAGES) && defined(HAS_SYS_ERRLIST)
4795
4796     /* This code is ifdefd out because it was found to not be necessary in testing
4797      * on our dromedary test machine, which has over 700 locales.  There, this
4798      * added no value to looking at the currency symbol and the time strings.  I
4799      * left it in so as to avoid rewriting it if real-world experience indicates
4800      * that dromedary is an outlier.  Essentially, instead of returning abpve if we
4801      * haven't found illegal utf8, we continue on and examine all the strerror()
4802      * messages on the platform for utf8ness.  If all are ASCII, we still don't
4803      * know the answer; but otherwise we have a pretty good indication of the
4804      * utf8ness.  The reason this doesn't help much is that the messages may not
4805      * have been translated into the locale.  The currency symbol and time strings
4806      * are much more likely to have been translated.  */
4807         {
4808             int e;
4809             bool non_ascii = FALSE;
4810             const char *original_messages_locale
4811                             = switch_category_locale_to_template(LC_MESSAGES,
4812                                                                  category,
4813                                                                  save_input_locale);
4814             const char * errmsg = NULL;
4815
4816             /* Here the current LC_MESSAGES is set to the locale of the category
4817              * whose information is desired.  Look through all the messages.  We
4818              * can't use Strerror() here because it may expand to code that
4819              * segfaults in miniperl */
4820
4821             for (e = 0; e <= sys_nerr; e++) {
4822                 errno = 0;
4823                 errmsg = sys_errlist[e];
4824                 if (errno || !errmsg) {
4825                     break;
4826                 }
4827                 errmsg = savepv(errmsg);
4828                 if (! is_utf8_invariant_string((U8 *) errmsg, 0)) {
4829                     non_ascii = TRUE;
4830                     is_utf8 = is_utf8_string((U8 *) errmsg, 0);
4831                     break;
4832                 }
4833             }
4834             Safefree(errmsg);
4835
4836             restore_switched_locale(LC_MESSAGES, original_messages_locale);
4837
4838             if (non_ascii) {
4839
4840                 /* Any non-UTF-8 message means not a UTF-8 locale; if all are valid,
4841                  * any non-ascii means it is one; otherwise we assume it isn't */
4842                 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "\t?error messages for %s are UTF-8=%d\n",
4843                                     save_input_locale,
4844                                     is_utf8));
4845                 goto finish_and_return;
4846             }
4847
4848             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));
4849         }
4850
4851 #    endif
4852 #    ifndef EBCDIC  /* On os390, even if the name ends with "UTF-8', it isn't a
4853                    UTF-8 locale */
4854
4855     /* As a last resort, look at the locale name to see if it matches
4856      * qr/UTF -?  * 8 /ix, or some other common locale names.  This "name", the
4857      * return of setlocale(), is actually defined to be opaque, so we can't
4858      * really rely on the absence of various substrings in the name to indicate
4859      * its UTF-8ness, but if it has UTF8 in the name, it is extremely likely to
4860      * be a UTF-8 locale.  Similarly for the other common names */
4861
4862     {
4863         const Size_t final_pos = strlen(save_input_locale) - 1;
4864
4865         if (final_pos >= 3) {
4866             const char *name = save_input_locale;
4867
4868             /* Find next 'U' or 'u' and look from there */
4869             while ((name += strcspn(name, "Uu") + 1)
4870                                         <= save_input_locale + final_pos - 2)
4871             {
4872                 if (   isALPHA_FOLD_NE(*name, 't')
4873                     || isALPHA_FOLD_NE(*(name + 1), 'f'))
4874                 {
4875                     continue;
4876                 }
4877                 name += 2;
4878                 if (*(name) == '-') {
4879                     if ((name > save_input_locale + final_pos - 1)) {
4880                         break;
4881                     }
4882                     name++;
4883                 }
4884                 if (*(name) == '8') {
4885                     DEBUG_L(PerlIO_printf(Perl_debug_log,
4886                                         "Locale %s ends with UTF-8 in name\n",
4887                                         save_input_locale));
4888                     is_utf8 = TRUE;
4889                     goto finish_and_return;
4890                 }
4891             }
4892             DEBUG_L(PerlIO_printf(Perl_debug_log,
4893                                 "Locale %s doesn't end with UTF-8 in name\n",
4894                                     save_input_locale));
4895         }
4896
4897 #      ifdef WIN32
4898
4899         /* http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756.aspx */
4900         if (memENDs(save_input_locale, final_pos, "65001")) {
4901             DEBUG_L(PerlIO_printf(Perl_debug_log,
4902                         "Locale %s ends with 65001 in name, is UTF-8 locale\n",
4903                         save_input_locale));
4904             is_utf8 = TRUE;
4905             goto finish_and_return;
4906         }
4907
4908 #      endif
4909     }
4910 #    endif
4911
4912     /* Other common encodings are the ISO 8859 series, which aren't UTF-8.  But
4913      * since we are about to return FALSE anyway, there is no point in doing
4914      * this extra work */
4915
4916 #    if 0
4917     if (instr(save_input_locale, "8859")) {
4918         DEBUG_L(PerlIO_printf(Perl_debug_log,
4919                              "Locale %s has 8859 in name, not UTF-8 locale\n",
4920                              save_input_locale));
4921         is_utf8 = FALSE;
4922         goto finish_and_return;
4923     }
4924 #    endif
4925
4926     DEBUG_L(PerlIO_printf(Perl_debug_log,
4927                           "Assuming locale %s is not a UTF-8 locale\n",
4928                                     save_input_locale));
4929     is_utf8 = FALSE;
4930
4931 #  endif /* the code that is compiled when no modern LC_CTYPE */
4932
4933   finish_and_return:
4934
4935     /* Cache this result so we don't have to go through all this next time. */
4936     utf8ness_cache_size = sizeof(PL_locale_utf8ness)
4937                        - (utf8ness_cache - PL_locale_utf8ness);
4938
4939     /* But we can't save it if it is too large for the total space available */
4940     if (LIKELY(input_name_len_with_overhead < utf8ness_cache_size)) {
4941         Size_t utf8ness_cache_len = strlen(utf8ness_cache);
4942
4943         /* Here it can fit, but we may need to clear out the oldest cached
4944          * result(s) to do so.  Check */
4945         if (utf8ness_cache_len + input_name_len_with_overhead
4946                                                         >= utf8ness_cache_size)
4947         {
4948             /* Here we have to clear something out to make room for this.
4949              * Start looking at the rightmost place where it could fit and find
4950              * the beginning of the entry that extends past that. */
4951             char * cutoff = (char *) my_memrchr(utf8ness_cache,
4952                                                 UTF8NESS_SEP[0],
4953                                                 utf8ness_cache_size
4954                                               - input_name_len_with_overhead);
4955
4956             assert(cutoff);
4957             assert(cutoff >= utf8ness_cache);
4958
4959             /* This and all subsequent entries must be removed */
4960             *cutoff = '\0';
4961             utf8ness_cache_len = strlen(utf8ness_cache);
4962         }
4963
4964         /* Make space for the new entry */
4965         Move(utf8ness_cache,
4966              utf8ness_cache + input_name_len_with_overhead,
4967              utf8ness_cache_len + 1 /* Incl. trailing NUL */, char);
4968
4969         /* And insert it */
4970         Copy(delimited, utf8ness_cache, input_name_len_with_overhead - 1, char);
4971         utf8ness_cache[input_name_len_with_overhead - 1] = is_utf8 + '0';
4972
4973         if ((PL_locale_utf8ness[strlen(PL_locale_utf8ness)-1]
4974                                                 & (PERL_UINTMAX_T) ~1) != '0')
4975         {
4976             Perl_croak(aTHX_
4977              "panic: %s: %d: Corrupt utf8ness_cache=%s\nlen=%zu,"
4978              " inserted_name=%s, its_len=%zu\n",
4979                 __FILE__, __LINE__,
4980                 PL_locale_utf8ness, strlen(PL_locale_utf8ness),
4981                 delimited, input_name_len_with_overhead);
4982         }
4983     }
4984
4985 #  ifdef DEBUGGING
4986
4987     if (DEBUG_Lv_TEST) {
4988         const char * s = PL_locale_utf8ness;
4989
4990         /* Audit the structure */
4991         while (s < PL_locale_utf8ness + strlen(PL_locale_utf8ness)) {
4992             const char *e;
4993
4994             if (*s != UTF8NESS_SEP[0]) {
4995                 Perl_croak(aTHX_
4996                            "panic: %s: %d: Corrupt utf8ness_cache: missing"
4997                            " separator %.*s<-- HERE %s\n",
4998                            __FILE__, __LINE__,
4999                            (int) (s - PL_locale_utf8ness), PL_locale_utf8ness,
5000                            s);
5001             }
5002             s++;
5003             e = strchr(s, UTF8NESS_PREFIX[0]);
5004             if (! e) {
5005                 Perl_croak(aTHX_
5006                            "panic: %s: %d: Corrupt utf8ness_cache: missing"
5007                            " separator %.*s<-- HERE %s\n",
5008                            __FILE__, __LINE__,
5009                            (int) (e - PL_locale_utf8ness), PL_locale_utf8ness,
5010                            e);
5011             }
5012             e++;
5013             if (*e != '0' && *e != '1') {
5014                 Perl_croak(aTHX_
5015                            "panic: %s: %d: Corrupt utf8ness_cache: utf8ness"
5016                            " must be [01] %.*s<-- HERE %s\n",
5017                            __FILE__, __LINE__,
5018                            (int) (e + 1 - PL_locale_utf8ness),
5019                            PL_locale_utf8ness, e + 1);
5020             }
5021             if (ninstr(PL_locale_utf8ness, s, s-1, e)) {
5022                 Perl_croak(aTHX_
5023                            "panic: %s: %d: Corrupt utf8ness_cache: entry"
5024                            " has duplicate %.*s<-- HERE %s\n",
5025                            __FILE__, __LINE__,
5026                            (int) (e - PL_locale_utf8ness), PL_locale_utf8ness,
5027                            e);
5028             }
5029             s = e + 1;
5030         }
5031     }
5032
5033     if (DEBUG_Lv_TEST || debug_initialization) {
5034
5035         PerlIO_printf(Perl_debug_log,
5036                 "PL_locale_utf8ness is now %s; returning %d\n",
5037                                      PL_locale_utf8ness, is_utf8);
5038     }
5039
5040 #  endif
5041
5042     /* free only when not using the buffer */
5043     if ( delimited != buffer ) Safefree(delimited);
5044     Safefree(save_input_locale);
5045     return is_utf8;
5046 }
5047
5048 #endif
5049
5050 bool
5051 Perl__is_in_locale_category(pTHX_ const bool compiling, const int category)
5052 {
5053     dVAR;
5054     /* Internal function which returns if we are in the scope of a pragma that
5055      * enables the locale category 'category'.  'compiling' should indicate if
5056      * this is during the compilation phase (TRUE) or not (FALSE). */
5057
5058     const COP * const cop = (compiling) ? &PL_compiling : PL_curcop;
5059
5060     SV *these_categories = cop_hints_fetch_pvs(cop, "locale", 0);
5061     if (! these_categories || these_categories == &PL_sv_placeholder) {
5062         return FALSE;
5063     }
5064
5065     /* The pseudo-category 'not_characters' is -1, so just add 1 to each to get
5066      * a valid unsigned */
5067     assert(category >= -1);
5068     return cBOOL(SvUV(these_categories) & (1U << (category + 1)));
5069 }
5070
5071 char *
5072 Perl_my_strerror(pTHX_ const int errnum)
5073 {
5074     /* Returns a mortalized copy of the text of the error message associated
5075      * with 'errnum'.  It uses the current locale's text unless the platform
5076      * doesn't have the LC_MESSAGES category or we are not being called from
5077      * within the scope of 'use locale'.  In the former case, it uses whatever
5078      * strerror returns; in the latter case it uses the text from the C locale.
5079      *
5080      * The function just calls strerror(), but temporarily switches, if needed,
5081      * to the C locale */
5082
5083     char *errstr;
5084     dVAR;
5085
5086 #ifndef USE_LOCALE_MESSAGES
5087
5088     /* If platform doesn't have messages category, we don't do any switching to
5089      * the C locale; we just use whatever strerror() returns */
5090
5091     errstr = savepv(Strerror(errnum));
5092
5093 #else   /* Has locale messages */
5094
5095     const bool within_locale_scope = IN_LC(LC_MESSAGES);
5096
5097 #  ifndef USE_ITHREADS
5098
5099     /* This function is trivial without threads. */
5100     if (within_locale_scope) {
5101         errstr = savepv(strerror(errnum));
5102     }
5103     else {
5104         const char * save_locale = savepv(do_setlocale_c(LC_MESSAGES, NULL));
5105
5106         do_setlocale_c(LC_MESSAGES, "C");
5107         errstr = savepv(strerror(errnum));
5108         do_setlocale_c(LC_MESSAGES, save_locale);
5109         Safefree(save_locale);
5110     }
5111
5112 #  elif defined(HAS_POSIX_2008_LOCALE)                      \
5113      && defined(HAS_STRERROR_L)                             \
5114      && defined(HAS_DUPLOCALE)
5115
5116     /* This function is also trivial if we don't have to worry about thread
5117      * safety and have strerror_l(), as it handles the switch of locales so we
5118      * don't have to deal with that.  We don't have to worry about thread
5119      * safety if strerror_r() is also available.  Both it and strerror_l() are
5120      * thread-safe.  Plain strerror() isn't thread safe.  But on threaded
5121      * builds when strerror_r() is available, the apparent call to strerror()
5122      * below is actually a macro that behind-the-scenes calls strerror_r(). */
5123
5124 #    ifdef HAS_STRERROR_R
5125
5126     if (within_locale_scope) {
5127         errstr = savepv(strerror(errnum));
5128     }
5129     else {
5130         errstr = savepv(strerror_l(errnum, PL_C_locale_obj));
5131     }
5132
5133 #    else
5134
5135     /* Here we have strerror_l(), but not strerror_r() and we are on a
5136      * threaded-build.  We use strerror_l() for everything, constructing a
5137      * locale to pass to it if necessary */
5138
5139     bool do_free = FALSE;
5140     locale_t locale_to_use;
5141
5142     if (within_locale_scope) {
5143         locale_to_use = uselocale((locale_t) 0);
5144         if (locale_to_use == LC_GLOBAL_LOCALE) {
5145             locale_to_use = duplocale(LC_GLOBAL_LOCALE);
5146             do_free = TRUE;
5147         }
5148     }
5149     else {  /* Use C locale if not within 'use locale' scope */
5150         locale_to_use = PL_C_locale_obj;
5151     }
5152
5153     errstr = savepv(strerror_l(errnum, locale_to_use));
5154
5155     if (do_free) {
5156         freelocale(locale_to_use);
5157     }
5158
5159 #    endif
5160 #  else /* Doesn't have strerror_l() */
5161
5162     const char * save_locale = NULL;
5163     bool locale_is_C = FALSE;
5164
5165     /* We have a critical section to prevent another thread from executing this
5166      * same code at the same time.  (On thread-safe perls, the LOCK is a
5167      * no-op.)  Since this is the only place in core that changes LC_MESSAGES
5168      * (unless the user has called setlocale(), this works to prevent races. */
5169     LOCALE_LOCK;
5170
5171     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
5172                             "my_strerror called with errnum %d\n", errnum));
5173     if (! within_locale_scope) {
5174         save_locale = do_setlocale_c(LC_MESSAGES, NULL);
5175         if (! save_locale) {
5176             Perl_croak(aTHX_
5177                  "panic: %s: %d: Could not find current LC_MESSAGES locale,"
5178                  " errno=%d\n", __FILE__, __LINE__, errno);
5179         }
5180         else {
5181             locale_is_C = isNAME_C_OR_POSIX(save_locale);
5182
5183             /* Switch to the C locale if not already in it */
5184             if (! locale_is_C) {
5185
5186                 /* The setlocale() just below likely will zap 'save_locale', so
5187                  * create a copy.  */
5188                 save_locale = savepv(save_locale);
5189                 do_setlocale_c(LC_MESSAGES, "C");
5190             }
5191         }
5192     }   /* end of ! within_locale_scope */
5193     else {
5194         DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s: %d: WITHIN locale scope\n",
5195                                                __FILE__, __LINE__));
5196     }
5197
5198     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
5199              "Any locale change has been done; about to call Strerror\n"));
5200     errstr = savepv(Strerror(errnum));
5201
5202     if (! within_locale_scope) {
5203         if (save_locale && ! locale_is_C) {
5204             if (! do_setlocale_c(LC_MESSAGES, save_locale)) {
5205                 Perl_croak(aTHX_
5206                      "panic: %s: %d: setlocale restore failed, errno=%d\n",
5207                              __FILE__, __LINE__, errno);
5208             }
5209             Safefree(save_locale);
5210         }
5211     }
5212
5213     LOCALE_UNLOCK;
5214
5215 #  endif /* End of doesn't have strerror_l */
5216 #  ifdef DEBUGGING
5217
5218     if (DEBUG_Lv_TEST) {
5219         PerlIO_printf(Perl_debug_log, "Strerror returned; saving a copy: '");
5220         print_bytes_for_locale(errstr, errstr + strlen(errstr), 0);
5221         PerlIO_printf(Perl_debug_log, "'\n");
5222     }
5223
5224 #  endif
5225 #endif   /* End of does have locale messages */
5226
5227     SAVEFREEPV(errstr);
5228     return errstr;
5229 }
5230
5231 /*
5232
5233 =for apidoc switch_to_global_locale
5234
5235 On systems without locale support, or on single-threaded builds, or on
5236 platforms that do not support per-thread locale operations, this function does
5237 nothing.  On such systems that do have locale support, only a locale global to
5238 the whole program is available.
5239
5240 On multi-threaded builds on systems that do have per-thread locale operations,
5241 this function converts the thread it is running in to use the global locale.
5242 This is for code that has not yet or cannot be updated to handle multi-threaded
5243 locale operation.  As long as only a single thread is so-converted, everything
5244 works fine, as all the other threads continue to ignore the global one, so only
5245 this thread looks at it.
5246
5247 However, on Windows systems this isn't quite true prior to Visual Studio 15,
5248 at which point Microsoft fixed a bug.  A race can occur if you use the
5249 following operations on earlier Windows platforms:
5250
5251 =over
5252
5253 =item L<POSIX::localeconv|POSIX/localeconv>
5254
5255 =item L<I18N::Langinfo>, items C<CRNCYSTR> and C<THOUSEP>
5256
5257 =item L<perlapi/Perl_langinfo>, items C<CRNCYSTR> and C<THOUSEP>
5258
5259 =back
5260
5261 The first item is not fixable (except by upgrading to a later Visual Studio
5262 release), but it would be possible to work around the latter two items by using
5263 the Windows API functions C<GetNumberFormat> and C<GetCurrencyFormat>; patches
5264 welcome.
5265
5266 Without this function call, threads that use the L<C<setlocale(3)>> system
5267 function will not work properly, as all the locale-sensitive functions will
5268 look at the per-thread locale, and C<setlocale> will have no effect on this
5269 thread.
5270
5271 Perl code should convert to either call
5272 L<C<Perl_setlocale>|perlapi/Perl_setlocale> (which is a drop-in for the system
5273 C<setlocale>) or use the methods given in L<perlcall> to call
5274 L<C<POSIX::setlocale>|POSIX/setlocale>.  Either one will transparently properly
5275 handle all cases of single- vs multi-thread, POSIX 2008-supported or not.
5276
5277 Non-Perl libraries, such as C<gtk>, that call the system C<setlocale> can
5278 continue to work if this function is called before transferring control to the
5279 library.
5280
5281 Upon return from the code that needs to use the global locale,
5282 L<C<sync_locale()>|perlapi/sync_locale> should be called to restore the safe
5283 multi-thread operation.
5284
5285 =cut
5286 */
5287
5288 void
5289 Perl_switch_to_global_locale()
5290 {
5291
5292 #ifdef USE_THREAD_SAFE_LOCALE
5293 #  ifdef WIN32
5294
5295     _configthreadlocale(_DISABLE_PER_THREAD_LOCALE);
5296
5297 #  else
5298 #    ifdef HAS_QUERYLOCALE
5299
5300     setlocale(LC_ALL, querylocale(LC_ALL_MASK, uselocale((locale_t) 0)));
5301
5302 #    else
5303
5304     {
5305         unsigned int i;
5306
5307         for (i = 0; i < LC_ALL_INDEX; i++) {
5308             setlocale(categories[i], do_setlocale_r(categories[i], NULL));
5309         }
5310     }
5311
5312 #    endif
5313
5314     uselocale(LC_GLOBAL_LOCALE);
5315
5316 #  endif
5317 #endif
5318
5319 }
5320
5321 /*
5322
5323 =for apidoc sync_locale
5324
5325 L<C<Perl_setlocale>|perlapi/Perl_setlocale> can be used at any time to query or
5326 change the locale (though changing the locale is antisocial and dangerous on
5327 multi-threaded systems that don't have multi-thread safe locale operations.
5328 (See L<perllocale/Multi-threaded operation>).  Using the system
5329 L<C<setlocale(3)>> should be avoided.  Nevertheless, certain non-Perl libraries
5330 called from XS, such as C<Gtk> do so, and this can't be changed.  When the
5331 locale is changed by XS code that didn't use
5332 L<C<Perl_setlocale>|perlapi/Perl_setlocale>, Perl needs to be told that the
5333 locale has changed.  Use this function to do so, before returning to Perl.
5334
5335 The return value is a boolean: TRUE if the global locale at the time of call
5336 was in effect; and FALSE if a per-thread locale was in effect.  This can be
5337 used by the caller that needs to restore things as-they-were to decide whether
5338 or not to call
5339 L<C<Perl_switch_to_global_locale>|perlapi/switch_to_global_locale>.
5340
5341 =cut
5342 */
5343
5344 bool
5345 Perl_sync_locale()
5346 {
5347
5348 #ifndef USE_LOCALE
5349
5350     return TRUE;
5351
5352 #else
5353
5354     const char * newlocale;
5355     dTHX;
5356
5357 #  ifdef USE_POSIX_2008_LOCALE
5358
5359     bool was_in_global_locale = FALSE;
5360     locale_t cur_obj = uselocale((locale_t) 0);
5361
5362     /* On Windows, unless the foreign code has turned off the thread-safe
5363      * locale setting, any plain setlocale() will have affected what we see, so
5364      * no need to worry.  Otherwise, If the foreign code has done a plain
5365      * setlocale(), it will only affect the global locale on POSIX systems, but
5366      * will affect the */
5367     if (cur_obj == LC_GLOBAL_LOCALE) {
5368
5369 #    ifdef HAS_QUERY_LOCALE
5370
5371         do_setlocale_c(LC_ALL, setlocale(LC_ALL, NULL));
5372
5373 #    else
5374
5375         unsigned int i;
5376
5377         /* We can't trust that we can read the LC_ALL format on the
5378          * platform, so do them individually */
5379         for (i = 0; i < LC_ALL_INDEX; i++) {
5380             do_setlocale_r(categories[i], setlocale(categories[i], NULL));
5381         }
5382
5383 #    endif
5384
5385         was_in_global_locale = TRUE;
5386     }
5387
5388 #  else
5389
5390     bool was_in_global_locale = TRUE;
5391
5392 #  endif
5393 #  ifdef USE_LOCALE_CTYPE
5394
5395     newlocale = savepv(do_setlocale_c(LC_CTYPE, NULL));
5396     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
5397         "%s:%d: %s\n", __FILE__, __LINE__,
5398         setlocale_debug_string(LC_CTYPE, NULL, newlocale)));
5399     new_ctype(newlocale);
5400     Safefree(newlocale);
5401
5402 #  endif /* USE_LOCALE_CTYPE */
5403 #  ifdef USE_LOCALE_COLLATE
5404
5405     newlocale = savepv(do_setlocale_c(LC_COLLATE, NULL));
5406     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
5407         "%s:%d: %s\n", __FILE__, __LINE__,
5408         setlocale_debug_string(LC_COLLATE, NULL, newlocale)));
5409     new_collate(newlocale);
5410     Safefree(newlocale);
5411
5412 #  endif
5413 #  ifdef USE_LOCALE_NUMERIC
5414
5415     newlocale = savepv(do_setlocale_c(LC_NUMERIC, NULL));
5416     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
5417         "%s:%d: %s\n", __FILE__, __LINE__,
5418         setlocale_debug_string(LC_NUMERIC, NULL, newlocale)));
5419     new_numeric(newlocale);
5420     Safefree(newlocale);
5421
5422 #  endif /* USE_LOCALE_NUMERIC */
5423
5424     return was_in_global_locale;
5425
5426 #endif
5427
5428 }
5429
5430 #if defined(DEBUGGING) && defined(USE_LOCALE)
5431
5432 STATIC char *
5433 S_setlocale_debug_string(const int category,        /* category number,
5434                                                            like LC_ALL */
5435                             const char* const locale,   /* locale name */
5436
5437                             /* return value from setlocale() when attempting to
5438                              * set 'category' to 'locale' */
5439                             const char* const retval)
5440 {
5441     /* Returns a pointer to a NUL-terminated string in static storage with
5442      * added text about the info passed in.  This is not thread safe and will
5443      * be overwritten by the next call, so this should be used just to
5444      * formulate a string to immediately print or savepv() on. */
5445
5446     /* initialise to a non-null value to keep it out of BSS and so keep
5447      * -DPERL_GLOBAL_STRUCT_PRIVATE happy */
5448     static char ret[256] = "If you can read this, thank your buggy C"
5449                            " library strlcpy(), and change your hints file"
5450                            " to undef it";
5451
5452     my_strlcpy(ret, "setlocale(", sizeof(ret));
5453     my_strlcat(ret, category_name(category), sizeof(ret));
5454     my_strlcat(ret, ", ", sizeof(ret));
5455
5456     if (locale) {
5457         my_strlcat(ret, "\"", sizeof(ret));
5458         my_strlcat(ret, locale, sizeof(ret));
5459         my_strlcat(ret, "\"", sizeof(ret));
5460     }
5461     else {
5462         my_strlcat(ret, "NULL", sizeof(ret));
5463     }
5464
5465     my_strlcat(ret, ") returned ", sizeof(ret));
5466
5467     if (retval) {
5468         my_strlcat(ret, "\"", sizeof(ret));
5469         my_strlcat(ret, retval, sizeof(ret));
5470         my_strlcat(ret, "\"", sizeof(ret));
5471     }
5472     else {
5473         my_strlcat(ret, "NULL", sizeof(ret));
5474     }
5475
5476     assert(strlen(ret) < sizeof(ret));
5477
5478     return ret;
5479 }
5480
5481 #endif
5482
5483 void
5484 Perl_thread_locale_init()
5485 {
5486     /* Called from a thread on startup*/
5487
5488 #ifdef USE_THREAD_SAFE_LOCALE
5489
5490     dTHX_DEBUGGING;
5491
5492     /* C starts the new thread in the global C locale.  If we are thread-safe,
5493      * we want to not be in the global locale */
5494
5495      DEBUG_L(PerlIO_printf(Perl_debug_log,
5496             "%s:%d: new thread, initial locale is %s; calling setlocale\n",
5497             __FILE__, __LINE__, setlocale(LC_ALL, NULL)));
5498
5499 #  ifdef WIN32
5500
5501     _configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
5502
5503 #  else
5504
5505     Perl_setlocale(LC_ALL, "C");
5506
5507 #  endif
5508 #endif
5509
5510 }
5511
5512 void
5513 Perl_thread_locale_term()
5514 {
5515     /* Called from a thread as it gets ready to terminate */
5516
5517 #ifdef USE_THREAD_SAFE_LOCALE
5518
5519     /* C starts the new thread in the global C locale.  If we are thread-safe,
5520      * we want to not be in the global locale */
5521
5522 #  ifndef WIN32
5523
5524     {   /* Free up */
5525         locale_t cur_obj = uselocale(LC_GLOBAL_LOCALE);
5526         if (cur_obj != LC_GLOBAL_LOCALE) {
5527             freelocale(cur_obj);
5528         }
5529     }
5530
5531 #  endif
5532 #endif
5533
5534 }
5535
5536 /*
5537  * ex: set ts=8 sts=4 sw=4 et:
5538  */