This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Add setlocale_i()
[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  * There is more than the typical amount of variation between platforms with
37  * regard to locale handling.  At the end of these introductory comments, are
38  * listed various relevent Configuration options, including some that can be
39  * used to pretend to some extent that this is being developed on a different
40  * platform than it actually is.  This allows you to make changes and catch
41  * some errors without having access to those other platforms.
42  *
43  * This code now has multi-thread-safe locale handling on systems that support
44  * that.  This is completely transparent to most XS code.  On earlier systems,
45  * it would be possible to emulate thread-safe locales, but this likely would
46  * involve a lot of locale switching, and would require XS code changes.
47  * Macros could be written so that the code wouldn't have to know which type of
48  * system is being used.
49  *
50  * Table-driven code is used for simplicity and clarity, as many operations
51  * differ only in which category is being worked on.  However the system
52  * categories need not be small contiguous integers, so do not lend themselves
53  * to table lookup.  Instead we have created our own equivalent values which
54  * are all small contiguous non-negative integers, and translation functions
55  * between the two sets.  For category 'LC_foo', the name of our index is
56  * LC_foo_INDEX_.  Various parallel tables, indexed by these, are used for the
57  * translation.  The tables are generated at compile-time based on platform
58  * characteristics and Configure options.  They hide from the code many of the
59  * vagaries of the different locale implementations out there.
60  *
61  * On unthreaded perls, most operations expand out to just the basic
62  * setlocale() calls.  That sort of is true on threaded perls on modern Windows
63  * systems where the same API, after set up, is used for thread-safe locale
64  * handling.  (But there are complications on Windows due to internal character
65  * set issues.)  On other systems, there is a completely different API,
66  * specified in POSIX 2008, to do thread-safe locales.  On these systems, our
67  * bool_setlocale_2008_i() function is used to hide the different API from the
68  * outside.  This makes it completely transparent to most XS code.
69  *
70  * A huge complicating factor is that the LC_NUMERIC category is normally held
71  * in the C locale, except during those relatively rare times when it needs to
72  * be in the underlying locale.  There is a bunch of code to accomplish this,
73  * and to allow easy switches from one state to the other.
74  *
75  * In addition, the setlocale equivalents have versions for the return context,
76  * 'void' and 'bool', besides the full return value.  This can present
77  * opportunities for avoiding work.  We don't have to necessarily create a safe
78  * copy to return if no return is desired.
79  *
80  * There are 3.5 major implementations here; which one chosen depends on what
81  * the platform has available, and Configuration options.
82  *
83  * 1) Raw posix_setlocale().  This implementation is basically the libc
84  *    setlocale(), with possibly minor tweaks.  This is used for startup, and
85  *    always for unthreaded perls, and when the API for safe locale threading
86  *    is identical to the unsafe API (Windows, currently).
87  *
88  *    This implementation is composed of two layers:
89  *      a)  posix_setlocale() implements the libc setlocale().  In most cases,
90  *          it is just an alias for the libc version.  But Windows doesn't
91  *          fully conform to the POSIX standard, and this is a layer on top of
92  *          libc to bring it more into conformance.  And in Configurations
93  *          where perl is to ignore some locale categories that the libc
94  *          setlocale() knows about, there is a layer to cope with that.
95  *      b)  stdized_setlocale() is a layer above a) that fixes some vagaries in
96  *          the return value of the libc setlocale().  On most platforms this
97  *          layer is empty; it requires perl to be Configured with a parameter
98  *          indicating the platform's defect, in order to be activated.  The
99  *          current ones are listed at the definition of the macro.
100  *
101  * 2) An implementation that adds a minimal layer above implementation 1),
102  *    making that implementation uninterruptible and returning a
103  *    per-thread/per-category value.
104  *
105  * 3a and 3b) An implementation of POSIX 2008 thread-safe locale handling,
106  *    hiding from the programmer the completely different API for this.
107  *    This automatically makes almost all code thread-safe without need for
108  *    changes.  This implementation is chosen on threaded perls when the
109  *    platform properly supports the POSIX 2008 functions, and when there is no
110  *    manual override to the contrary passed to Configure.
111  *
112  *    3a) is when the platform has a documented reliable querylocale() function
113  *        or equivalent that is selected to be used.
114  *    3b) is when we have to emulate that functionality.
115  *
116  *    Unfortunately, it seems that some platforms that claim to support these
117  *    are buggy, in one way or another.  There are workarounds encoded here,
118  *    where feasible, for platforms where the bugs are amenable to that
119  *    (glibc, for example).  But other platforms instead don't use this
120  *    implementation.
121  *
122  * z/OS (os390) is an outlier.  Locales really don't work under threads when
123  * either the radix character isn't a dot, or attempts are made to change
124  * locales after the first thread is created.  The reason is that IBM has made
125  * it thread-safe by refusing to change locales (returning failure if
126  * attempted) any time after an application has called pthread_create() to
127  * create another thread.  The expectation is that an application will set up
128  * its locale information before the first fork, and be stable thereafter.  But
129  * perl toggles LC_NUMERIC if the locale's radix character isn't a dot, as do
130  * the other toggles, which are less common.
131  *
132  * Associated with each implementation are three sets of macros that translate
133  * a consistent API into what that implementation needs.  Each set consists of
134  * three macros with the suffixes:
135  *  _c  Means the argument is a locale category number known at compile time.
136  *          An example would be LC_TIME.  This token is a compile-time constant
137  *          and can be passed to a '_c' macro.
138  *  _r  Means the argument is a locale category number whose value might not be
139  *      known until runtime
140  *  _i  Means the argument is our internal index of a locale category
141  *
142  * The three sets are:    ('_X'  means one of '_c', '_r', '_i')
143  * 1) bool_setlocale_X()
144  *      This calls the appropriate setlocale()-equivalent for the
145  *      implementation, with the category and new locale.  The input locale is
146  *      not necessarily valid, so the return is true or false depending on
147  *      whether or not the setlocale() succeeded.  This is not used for
148  *      querying the locale, so the input locale must not be NULL.
149  *
150  *      This macro is suitable for toggling the locale back and forth during an
151  *      operation.  For example, the names of days and months under LC_TIME are
152  *      strings that are also subject to LC_CTYPE.  If the locales of these two
153  *      categories differ, mojibake can result on many platforms.  The code
154  *      here will toggle LC_CTYPE into the locale of LC_TIME temporarily to
155  *      avoid this.
156  *
157  *      Several categories require extra work when their locale is changed.
158  *      LC_CTYPE, for example, requires the calculation of the table of which
159  *      characters fold to which others under /i pattern matching or fc(), as
160  *      folding is not a concept in POSIX.  This table isn't needed when the
161  *      LC_CTYPE locale gets toggled during an operation, and will be toggled
162  *      back before return to the caller.  To save work that would be
163  *      discarded, the bool_setlocale_X() implementations don't do this extra
164  *      work.  Instead, there is a separate function for just this purpose to
165  *      be done before control is transferred back to the external caller.  All
166  *      categories that have such requirements have such a function.  The
167  *      update_functions[] array contains pointers to them (or NULL for
168  *      categories which don't need a function).
169  *
170  *      Care must be taken to remember to call the separate function before
171  *      returning to an external caller, and to not use things it updates
172  *      before its call.  An alternative approach would be to have
173  *      bool_setlocale_X() always call the update, which would return
174  *      immediately if a flag wasn't set indicating it was time to actually
175  *      perform it.
176  *
177  * 2) void_setlocale_X()
178  *      This is like bool_setlocale_X(), but it is used only when it is
179  *      expected that the call must succeed, or something is seriously wrong.
180  *      A panic is issued if it fails.  The caller uses this form when it just
181  *      wants to assume things worked.
182  *
183  * 3) querylocale_X()
184  *      This returns a string that specifies the current locale for the given
185  *      category given by the input argument.  The string is safe from other
186  *      threads zapping it, and the caller need not worry about freeing it, but
187  *      it may be mortalized, so must be copied if you need to preserve it
188  *      across calls, or long term.  This returns the actual current locale,
189  *      not the nominal.  These differ, for example, when LC_NUMERIC is
190  *      supposed to be a locale whose decimal radix character is a comma.  As
191  *      mentioned above, Perl actually keeps this category set to C in such
192  *      circumstances so that XS code can just assume a dot radix character.
193  *      querylocale_X() returns the locale that libc has stored at this moment,
194  *      so most of the time will return a locale whose radix character is a
195  *      dot.  The macro query_nominal_locale_i() can be used to get the nominal
196  *      locale that an external caller would expect, for all categories except
197  *      LC_ALL.  For that, you can use the function
198  *      S_calculate_LC_ALL_string().  Or S_native_querylocale_i() will operate
199  *      on any category.
200  *
201  * The underlying C API that this implements uses category numbers, hence the
202  * code is structured to use '_r' at the API level to convert to indexes, which
203  * are then used internally with the '_i' forms.
204  *
205  * The splitting apart into setting vs querying means that the return value of
206  * the bool macros is not subject to potential clashes with other threads,
207  * eliminating any need for the calling code to worry about that and get it
208  * wrong.  Whereas, you do have to think about thread interactions when using a
209  * query.
210  *
211  * Additionally, for the implementations where there aren't any complications,
212  * a setlocale_i() is defined that is like plain setlocale(), returning the new
213  * locale.  Thus it combines a bool_setlocale_X() with a querylocale_X().  It
214  * is used only for performance on implementations that allow it, such as
215  * non-threaded perls.
216  *
217  * There are also a few other macros herein that use this naming convention to
218  * describe their category parameter.
219  *
220  * Relevant Configure options
221  *
222  *      -Accflags=-DNO_LOCALE
223  *          This compiles perl to always use the C locale, ignoring any
224  *          attempts to change it.  This could be useful on platforms with a
225  *          crippled locale implementation.
226  *
227  *      -Accflags=-DNO_THREAD_SAFE_LOCALE
228  *          Even if thread-safe operations are available on this platform and
229  *          would otherwise be used (because this is a perl with multiplicity),
230  *          perl is compiled to not use them.  This could be useful on
231  *          platforms where the libc is buggy.
232  *
233  *      -Accflags=-DNO_POSIX_2008_LOCALE
234  *          Even if the libc locale operations specified by the Posix 2008
235  *          Standard are available on this platform and would otherwise be used
236  *          (because this is a perl with multiplicity), perl is compiled to not
237  *          use them.  This could be useful on platforms where the libc is
238  *          buggy.  This is like NO_THREAD_SAFE_LOCALE, but has no effect on
239  *          platforms that don't have these functions.
240  *
241  *      -Accflags=-DUSE_POSIX_2008_LOCALE
242  *          Normally, setlocale() is used for locale operations on perls
243  *          compiled without multiplicity.  This option causes the locale
244  *          operations defined by the Posix 2008 Standard to always be used
245  *          instead.  This could be useful on platforms where the libc
246  *          setlocale() is buggy.
247  *
248  *      -Accflags=-DNO_THREAD_SAFE_QUERYLOCALE
249  *          This applies only to platforms that have a querylocale() libc
250  *          function.  perl assumes that that function is thread-safe, unless
251  *          overridden by this, typically in a hints file.  When overridden,
252  *          querylocale() is called only while the locale mutex is locked, and
253  *          the result is copied to a per-thread place before unlocking.
254  *
255  *      -Accflags=-DNO_LOCALE_CTYE
256  *      -Accflags=-DNO_LOCALE_NUMERIC
257  *          etc.
258  *
259  *          If the named category(ies) does(do) not exist on this platform,
260  *          these have no effect.  Otherwise they cause perl to be compiled to
261  *          always keep the named category(ies) in the C locale XXX
262  *
263  *      -Accflags=-DHAS_BROKEN_SETLOCALE_QUERY_LC_ALL
264  *          This would be set in a hints file to tell perl that doing a libc
265  *              setlocale(LC_ALL, NULL)
266  *          can give erroneous results, and perl will compensate to get the
267  *          correct results.  This is known to be a problem in earlier AIX
268  *          versions
269  *
270  *      -Accflags=-DHAS_LF_IN_SETLOCALE_RETURN
271  *          This would be set in a hints file to tell perl that a libc
272  *          setlocale() can return results containing \n characters that need
273  *          to be stripped off.  khw believes there aren't any such platforms
274  *          still in existence.
275  *
276  *      -Accflags=USE_FAKE_LC_ALL_POSITIONAL_NOTATION
277  *          This is used when developing Perl on a platform that uses
278  *          'name=value;' notation to represent LC_ALL when not all categories
279  *          are the same.  When so compiled, much of the code gets compiled
280  *          and exercised that applies to platforms that instead use positional
281  *          notation.  This allows for finding many bugs in that portion of the
282  *          implementation, without having to access such a platform.
283  *
284  *      -Accflags=-DWIN32_USE_FAKE_OLD_MINGW_LOCALES
285  *          This is used when developing Perl on a non-Windows platform to
286  *          compile and exercise much of the locale-related code that instead
287  *          applies to MingW platforms that don't use the more modern UCRT
288  *          library.  This allows for finding many bugs in that portion of the
289  *          implementation, without having to access such a platform.
290  */
291
292 /* If the environment says to, we can output debugging information during
293  * initialization.  This is done before option parsing, and before any thread
294  * creation, so can be a file-level static.  (Must come before #including
295  * perl.h) */
296 #include "config.h"
297
298 /* Returns the Unix errno portion; ignoring any others.  This is a macro here
299  * instead of putting it into perl.h, because unclear to khw what should be
300  * done generally. */
301 #define GET_ERRNO   saved_errno
302
303 #ifdef DEBUGGING
304 static int debug_initialization = 0;
305 #  define DEBUG_INITIALIZATION_set(v) (debug_initialization = v)
306 #  define DEBUG_LOCALE_INITIALIZATION_  debug_initialization
307
308 #  ifdef HAS_EXTENDED_OS_ERRNO
309      /* Output the non-zero errno and/or the non-zero extended errno */
310 #    define DEBUG_ERRNO                                                     \
311         dSAVE_ERRNO; dTHX;                                                  \
312         int extended = get_extended_os_errno();                             \
313         const char * errno_string;                                          \
314         if (GET_ERRNO == 0) { /* Skip output if both errno types are 0 */   \
315             if (LIKELY(extended == 0)) errno_string = "";                   \
316             else errno_string = Perl_form(aTHX_ "; $^E=%d", extended);      \
317         }                                                                   \
318         else if (LIKELY(extended == GET_ERRNO))                             \
319             errno_string = Perl_form(aTHX_ "; $!=%d", GET_ERRNO);           \
320         else errno_string = Perl_form(aTHX_ "; $!=%d, $^E=%d",              \
321                                                     GET_ERRNO, extended);
322 #  else
323      /* Output the errno, if non-zero */
324 #    define DEBUG_ERRNO                                                     \
325         dSAVE_ERRNO;                                                        \
326         const char * errno_string = "";                                     \
327         if (GET_ERRNO != 0) {                                               \
328             dTHX;                                                           \
329             errno_string = Perl_form(aTHX_ "; $!=%d", GET_ERRNO);           \
330         }
331 #  endif
332
333 /* Automatically include the caller's file, and line number in debugging output;
334  * and the errno (and/or extended errno) if non-zero.  On threaded perls add
335  * the aTHX too. */
336 #  if defined(USE_ITHREADS) && ! defined(NO_LOCALE_THREADS)
337 #    define DEBUG_PRE_STMTS                                                 \
338         DEBUG_ERRNO;                                                        \
339         PerlIO_printf(Perl_debug_log, "\n%s: %" LINE_Tf ": 0x%p%s: ",       \
340                                       __FILE__, (line_t)__LINE__, aTHX_     \
341                                       errno_string);
342 #  else
343 #    define DEBUG_PRE_STMTS                                                 \
344         DEBUG_ERRNO;                                                        \
345         PerlIO_printf(Perl_debug_log, "\n%s: %" LINE_Tf "%s: ",             \
346                                       __FILE__, (line_t)__LINE__,           \
347                                       errno_string);
348 #  endif
349 #  define DEBUG_POST_STMTS  RESTORE_ERRNO;
350 #else
351 #  define debug_initialization 0
352 #  define DEBUG_INITIALIZATION_set(v)
353 #  define DEBUG_PRE_STMTS
354 #  define DEBUG_POST_STMTS
355 #endif
356
357 #include "EXTERN.h"
358 #define PERL_IN_LOCALE_C
359 #include "perl.h"
360
361 #ifdef WIN32_USE_FAKE_OLD_MINGW_LOCALES
362
363    /* Use -Accflags=-DWIN32_USE_FAKE_OLD_MINGW_LOCALES on a POSIX or *nix box
364     * to get a semblance of pretending the locale handling is that of a MingW
365     * that doesn't use UCRT (hence 'OLD' in the name).  This exercizes code
366     * paths that are not compiled on non-Windows boxes, and allows for ASAN.
367     * This is thus a way to see if locale.c on Windows is likely going to
368     * compile, without having to use a real Win32 box.  And running the test
369     * suite will verify to a large extent our logic and memory allocation
370     * handling for such boxes.  And access to ASAN and PERL_MEMLOG Of course the underlying calls are to the POSIX
371     * libc, so any differences in implementation between those and the Windows
372     * versions will not be caught by this. */
373
374 #  define WIN32
375 #  undef P_CS_PRECEDES
376 #  undef CURRENCY_SYMBOL
377 #  define CP_UTF8 -1
378 #  undef _configthreadlocale
379 #  define _configthreadlocale(arg) NOOP
380
381 #  define MultiByteToWideChar(cp, flags, byte_string, m1, wstring, req_size) \
382                     (mbsrtowcs(wstring, &(byte_string), req_size, NULL) + 1)
383 #  define WideCharToMultiByte(cp, flags, wstring, m1, byte_string,          \
384                               req_size, default_char, found_default_char)   \
385                     (wcsrtombs(byte_string, &(wstring), req_size, NULL) + 1)
386
387 #  ifdef USE_LOCALE
388
389 static const wchar_t * wsetlocale_buf = NULL;
390 static Size_t wsetlocale_buf_size = 0;
391 static PerlInterpreter * wsetlocale_buf_aTHX = NULL;
392
393 STATIC
394 const wchar_t *
395 S_wsetlocale(const int category, const wchar_t * wlocale)
396 {
397     /* Windows uses a setlocale that takes a wchar_t* locale.  Other boxes
398      * don't have this, so this Windows replacement converts the wchar_t input
399      * to plain 'char*', calls plain setlocale(), and converts the result back
400      * to 'wchar_t*' */
401
402     const char * byte_locale = NULL;
403     if (wlocale) {
404         byte_locale = Win_wstring_to_byte_string(CP_UTF8, wlocale);
405     }
406
407     const char * byte_result = setlocale(category, byte_locale);
408     Safefree(byte_locale);
409     if (byte_result == NULL) {
410         return NULL;
411     }
412
413     const wchar_t * wresult = Win_byte_string_to_wstring(CP_UTF8, byte_result);
414
415     if (! wresult) {
416         return NULL;
417     }
418
419     /* Emulate a global static memory return from wsetlocale().  This currently
420      * leaks at process end; would require changing LOCALE_TERM to fix that */
421     Size_t string_size = wcslen(wresult) + 1;
422
423     if (wsetlocale_buf_size == 0) {
424         Newx(wsetlocale_buf, string_size, wchar_t);
425         wsetlocale_buf_size = string_size;
426
427 #  ifdef MULTIPLICITY
428
429         dTHX;
430         wsetlocale_buf_aTHX = aTHX;
431
432 #  endif
433
434     }
435     else if (string_size > wsetlocale_buf_size) {
436         Renew(wsetlocale_buf, string_size, wchar_t);
437         wsetlocale_buf_size = string_size;
438     }
439
440     Copy(wresult, wsetlocale_buf, string_size, wchar_t);
441     Safefree(wresult);
442
443     return wsetlocale_buf;
444 }
445
446 #  define _wsetlocale(category, wlocale)  S_wsetlocale(category, wlocale)
447 #  endif
448 #endif  /* WIN32_USE_FAKE_OLD_MINGW_LOCALES */
449
450 #ifdef USE_LOCALE
451 #  if defined(USE_FAKE_LC_ALL_POSITIONAL_NOTATION) && defined(LC_ALL)
452
453 /* This simulates an underlying positional notation for LC_ALL when compiled on
454  * a system that uses name=value notation.  Use this to develop on Linux and
455  * make a quick check that things have some chance of working on a positional
456  * box.  Enable by adding to the Congfigure parameters:
457  *      -Accflags=USE_FAKE_LC_ALL_POSITIONAL_NOTATION
458  *
459  * NOTE it redefines setlocale() and usequerylocale()
460  * */
461
462 STATIC const char *
463 S_positional_name_value_xlation(const char * locale, bool direction)
464 {   /* direction == 1 is from name=value to positional
465        direction == 0 is from positional to name=value */
466     assert(locale);
467
468     dTHX;
469     const char * individ_locales[LC_ALL_INDEX_] = { NULL };
470
471     /* This parses either notation */
472     switch (parse_LC_ALL_string(locale,
473                                 (const char **) &individ_locales,
474                                 no_override,  /* Handled by other code */
475                                 false,      /* Return only [0] if suffices */
476                                 false,      /* Don't panic on error */
477                                 __LINE__))
478     {
479       default:      /* Some compilers don't realize that below is the complete
480                        list of the available enum values */
481       case invalid:
482         return NULL;
483
484       case no_array:
485         return locale;
486       case only_element_0:
487         SAVEFREEPV(individ_locales[0]);
488         return individ_locales[0];
489       case full_array:
490        {
491         calc_LC_ALL_format  format = (direction)
492                                      ? EXTERNAL_FORMAT_FOR_SET
493                                      : INTERNAL_FORMAT;
494         const char * retval = calculate_LC_ALL_string(individ_locales,
495                                                       format,
496                                                       WANT_TEMP_PV,
497                                                       __LINE__);
498
499         for (unsigned int i = 0; i < LC_ALL_INDEX_; i++) {
500             Safefree(individ_locales[i]);
501         }
502
503         return retval;
504        }
505     }
506 }
507
508 STATIC const char *
509 S_positional_setlocale(int cat, const char * locale)
510 {
511     if (cat != LC_ALL) return setlocale(cat, locale);
512
513     if (locale && strNE(locale, "")) {
514         locale = S_positional_name_value_xlation(locale, 0);
515         if (! locale) return NULL;
516     }
517
518     locale = setlocale(cat, locale);
519     if (locale == NULL) return NULL;
520     return S_positional_name_value_xlation(locale, 1);
521 }
522
523 #    undef setlocale
524 #    define setlocale(a,b)  S_positional_setlocale(a,b)
525 #    ifdef USE_POSIX_2008_LOCALE
526
527 STATIC locale_t
528 S_positional_newlocale(int mask, const char * locale, locale_t base)
529 {
530     assert(locale);
531
532     if (mask != LC_ALL_MASK) return newlocale(mask, locale, base);
533
534     if (strNE(locale, "")) locale = S_positional_name_value_xlation(locale, 0);
535     if (locale == NULL) return NULL;
536     return newlocale(LC_ALL_MASK, locale, base);
537 }
538
539 #    undef newlocale
540 #    define newlocale(a,b,c)  S_positional_newlocale(a,b,c)
541 #    endif
542 #  endif
543 #endif  /* End of fake positional notation */
544
545 #include "reentr.h"
546
547 #ifdef I_WCHAR
548 #  include <wchar.h>
549 #endif
550 #ifdef I_WCTYPE
551 #  include <wctype.h>
552 #endif
553
554  /* The main errno that gets used is this one, on platforms that support it */
555 #ifdef EINVAL
556 #  define SET_EINVAL  SETERRNO(EINVAL, LIB_INVARG)
557 #else
558 #  define SET_EINVAL
559 #endif
560
561 /* If we have any of these library functions, we can reliably determine is a
562  * locale is a UTF-8 one or not.  And if we aren't using locales at all, we act
563  * as if everything is the C locale, so the answer there is always "No, it
564  * isn't UTF-8"; this too is reliably accurate */
565 #if   defined(HAS_SOME_LANGINFO) || defined(HAS_MBTOWC)                 \
566    || defined(HAS_MBRTOWC) || ! defined(USE_LOCALE)
567 #  define HAS_RELIABLE_UTF8NESS_DETERMINATION
568 #endif
569
570 /* This is a starting guess as to when this is true.  It definititely isn't
571  * true on *BSD where positional LC_ALL notation is used.  Likely this will end
572  * up being defined in hints files. */
573 #ifdef PERL_LC_ALL_USES_NAME_VALUE_PAIRS
574 #  define NEWLOCALE_HANDLES_DISPARATE_LC_ALL
575 #endif
576
577 /* But regardless, we have to look at individual categories if some are
578  * ignored.  */
579 #ifdef HAS_IGNORED_LOCALE_CATEGORIES_
580 #  undef NEWLOCALE_HANDLES_DISPARATE_LC_ALL
581 #endif
582 #ifdef USE_LOCALE
583
584 /* Not all categories need be set to the same locale.  This macro determines if
585  * 'name' which represents LC_ALL is uniform or disparate.  There are two
586  * situations: 1) the platform uses unordered name=value pairs; 2) the platform
587  * uses ordered positional values, with a separator string between them */
588 #  ifdef PERL_LC_ALL_SEPARATOR   /* positional */
589 #    define is_disparate_LC_ALL(name)  cBOOL(instr(name, PERL_LC_ALL_SEPARATOR))
590 #  else     /* name=value */
591
592     /* In the, hopefully never occurring, event that the platform doesn't use
593      * either mechanism for disparate LC_ALL's, assume the name=value pairs
594      * form, rather than taking the extreme step of refusing to compile.  Many
595      * programs won't have disparate locales, so will generally work */
596 #    define PERL_LC_ALL_SEPARATOR  ";"
597 #    define is_disparate_LC_ALL(name)  cBOOL(   strchr(name, ';')   \
598                                              && strchr(name, '='))
599 #  endif
600
601 /* It is possible to compile perl to always keep any individual category in the
602  * C locale.  This would be done where the implementation on a platform is
603  * flawed or incomplete.  At the time of this writing, for example, OpenBSD has
604  * not implemented LC_COLLATE beyond the C locale.  The 'category_available[]'
605  * table is a bool that says whether a category is changeable, or must be kept
606  * in C.  This macro substitutes C for the locale appropriately, expanding to
607  * nothing on the more typical case where all possible categories present on
608  * the platform are handled. */
609 #  ifdef HAS_IGNORED_LOCALE_CATEGORIES_
610 #    define need_to_override_category(i)  (! category_available[i])
611 #    define override_ignored_category(i, new_locale)                        \
612                     ((need_to_override_category(i)) ? "C" : (new_locale))
613 #  else
614 #    define need_to_override_category(i)  0
615 #    define override_ignored_category(i, new_locale)  (new_locale)
616 #  endif
617
618 PERL_STATIC_INLINE const char *
619 S_mortalized_pv_copy(pTHX_ const char * const pv)
620 {
621     PERL_ARGS_ASSERT_MORTALIZED_PV_COPY;
622
623     /* Copies the input pv, and arranges for it to be freed at an unspecified
624      * later time. */
625
626     if (pv == NULL) {
627         return NULL;
628     }
629
630     const char * copy = savepv(pv);
631     SAVEFREEPV(copy);
632     return copy;
633 }
634
635 #endif
636
637 /* Default values come from the C locale */
638 #define C_codeset "ANSI_X3.4-1968" /* Only in some Configurations, and usually
639                                       a single instance, so is a #define */
640 static const char C_decimal_point[] = ".";
641
642 #if (defined(USE_LOCALE_NUMERIC) && ! defined(TS_W32_BROKEN_LOCALECONV))    \
643  || ! (   defined(USE_LOCALE_NUMERIC)                                       \
644        && (defined(HAS_SOME_LANGINFO) || defined(HAS_LOCALECONV)))
645 static const char C_thousands_sep[] = "";
646 #endif
647
648 /* Is the C string input 'name' "C" or "POSIX"?  If so, and 'name' is the
649  * return of setlocale(), then this is extremely likely to be the C or POSIX
650  * locale.  However, the output of setlocale() is documented to be opaque, but
651  * the odds are extremely small that it would return these two strings for some
652  * other locale.  Note that VMS includes many non-ASCII characters in these two
653  * locales as controls and punctuation (below are hex bytes):
654  *   cntrl:  84-97 9B-9F
655  *   punct:  A1-A3 A5 A7-AB B0-B3 B5-B7 B9-BD BF-CF D1-DD DF-EF F1-FD
656  * Oddly, none there are listed as alphas, though some represent alphabetics
657  * http://www.nntp.perl.org/group/perl.perl5.porters/2013/02/msg198753.html */
658 #define isNAME_C_OR_POSIX(name)                                              \
659                              (   (name) != NULL                              \
660                               && (( *(name) == 'C' && (*(name + 1)) == '\0') \
661                                    || strEQ((name), "POSIX")))
662
663 #if defined(HAS_NL_LANGINFO_L) || defined(HAS_NL_LANGINFO)
664 #  define HAS_SOME_LANGINFO
665 #endif
666
667 #define my_langinfo_c(item, category, locale, retbufp, retbuf_sizep, utf8ness) \
668             my_langinfo_i(item, category##_INDEX_, locale, retbufp,            \
669                                                       retbuf_sizep,  utf8ness)
670 #ifdef USE_LOCALE
671 #  ifdef DEBUGGING
672 #    define setlocale_debug_string_i(index, locale, result)                 \
673             my_setlocale_debug_string_i(index, locale, result, __LINE__)
674 #    define setlocale_debug_string_c(category, locale, result)              \
675                 setlocale_debug_string_i(category##_INDEX_, locale, result)
676 #    define setlocale_debug_string_r(category, locale, result)              \
677              setlocale_debug_string_i(get_category_index(category),         \
678                                       locale, result)
679 #  endif
680
681 #  define toggle_locale_i(index, locale)                                    \
682                  S_toggle_locale_i(aTHX_ index, locale, __LINE__)
683 #  define toggle_locale_c(cat, locale)  toggle_locale_i(cat##_INDEX_, locale)
684 #  define restore_toggled_locale_i(index, locale)                           \
685                  S_restore_toggled_locale_i(aTHX_ index, locale, __LINE__)
686 #  define restore_toggled_locale_c(cat, locale)                             \
687                              restore_toggled_locale_i(cat##_INDEX_, locale)
688
689 /* On systems without LC_ALL, pretending it exists anyway simplifies things.
690  * Choose a value for it that is very unlikely to clash with any actual
691  * category */
692 #  define FAKE_LC_ALL  PERL_INT_MIN
693
694 /* Below are parallel arrays for locale information indexed by our mapping of
695  * category numbers into small non-negative indexes.  locale_table.h contains
696  * an entry like this for each individual category used on this system:
697  *      PERL_LOCALE_TABLE_ENTRY(CTYPE, S_new_ctype)
698  *
699  * Each array redefines PERL_LOCALE_TABLE_ENTRY to generate the information
700  * needed for that array, and #includes locale_table.h to get the valid
701  * categories.
702  *
703  * An entry for the conglomerate category LC_ALL is added here, immediately
704  * following the individual categories.  (The treatment for it varies, so can't
705  * be in locale_table.h.)
706  *
707  * Following this, each array ends with an entry for illegal categories.  All
708  * category numbers unknown to perl get mapped to this entry.  This is likely
709  * to be a parameter error from the calling program; but it could be that this
710  * platform has a category we don't know about, in which case it needs to be
711  * added, using the paradigm of one of the existing categories. */
712
713 /* The first array is the locale categories perl uses on this system, used to
714  * map our index back to the system's category number. */
715 STATIC const int categories[] = {
716
717 #  undef PERL_LOCALE_TABLE_ENTRY
718 #  define PERL_LOCALE_TABLE_ENTRY(name, call_back)  LC_ ## name,
719 #  include "locale_table.h"
720
721 #  ifdef LC_ALL
722     LC_ALL,
723 #  else
724     FAKE_LC_ALL,
725 #  endif
726
727    (FAKE_LC_ALL + 1)    /* Entry for unknown category; this number is unlikely
728                            to clash with a real category */
729 };
730
731 # define GET_NAME_AS_STRING(token)  # token
732 # define GET_LC_NAME_AS_STRING(token) GET_NAME_AS_STRING(LC_ ## token)
733
734 /* The second array is the category names. */
735 STATIC const char * const category_names[] = {
736
737 #  undef PERL_LOCALE_TABLE_ENTRY
738 #  define PERL_LOCALE_TABLE_ENTRY(name, call_back)  GET_LC_NAME_AS_STRING(name),
739 #  include "locale_table.h"
740
741 #  ifdef LC_ALL
742 #    define LC_ALL_STRING  "LC_ALL"
743 #  else
744 #    define LC_ALL_STRING  "If you see this, it is a bug in perl;"      \
745                            " please report it via perlbug"
746 #  endif
747
748     LC_ALL_STRING,
749
750 #  define LC_UNKNOWN_STRING  "Locale category unknown to Perl; if you see"  \
751                              " this, it is a bug in perl; please report it" \
752                              " via perlbug"
753     LC_UNKNOWN_STRING
754 };
755
756 STATIC const Size_t category_name_lengths[] = {
757
758 #  undef PERL_LOCALE_TABLE_ENTRY
759 #  define PERL_LOCALE_TABLE_ENTRY(name, call_back)                          \
760                                     STRLENs(GET_LC_NAME_AS_STRING(name)),
761 #  include "locale_table.h"
762
763     STRLENs(LC_ALL_STRING),
764     STRLENs(LC_UNKNOWN_STRING)
765 };
766
767 /* Each entry includes space for the '=' and ';' */
768 #  undef PERL_LOCALE_TABLE_ENTRY
769 #  define PERL_LOCALE_TABLE_ENTRY(name, call_back)                          \
770                                 + STRLENs(GET_LC_NAME_AS_STRING(name)) + 2
771
772 STATIC const Size_t lc_all_boiler_plate_length = 1  /* space for trailing NUL */
773 #  include "locale_table.h"
774 ;
775
776 /* A few categories require additional setup when they are changed.  This table
777  * points to the functions that do that setup */
778 STATIC void (*update_functions[]) (pTHX_ const char *, bool force) = {
779
780 #  undef PERL_LOCALE_TABLE_ENTRY
781 #  define PERL_LOCALE_TABLE_ENTRY(name, call_back)  call_back,
782 #  include "locale_table.h"
783
784     S_new_LC_ALL,
785     NULL,   /* No update for unknown category */
786 };
787
788 #  if defined(HAS_IGNORED_LOCALE_CATEGORIES_)
789
790 /* Indicates if each category on this platform is available to use not in
791  * the C locale */
792 STATIC const bool category_available[] = {
793
794 #  undef PERL_LOCALE_TABLE_ENTRY
795 #  define PERL_LOCALE_TABLE_ENTRY(name, call_back)  LC_ ## name ## _AVAIL_,
796 #  include "locale_table.h"
797
798 #  ifdef LC_ALL
799     true,
800 #  else
801     false
802 #  endif
803
804     false   /* LC_UNKNOWN_AVAIL_ */
805 };
806
807 #  endif
808 #  if defined(USE_POSIX_2008_LOCALE)
809
810 STATIC const int category_masks[] = {
811
812 #    undef PERL_LOCALE_TABLE_ENTRY
813 #    define PERL_LOCALE_TABLE_ENTRY(name, call_back)  LC_ ## name ## _MASK,
814 #    include "locale_table.h"
815
816     LC_ALL_MASK,    /* Will rightly refuse to compile unless this is defined */
817     0               /* Empty mask for unknown category */
818 };
819
820 #  endif
821 #  if ! defined(PERL_LC_ALL_USES_NAME_VALUE_PAIRS)
822
823 /* On platforms that use positional notation for expressing LC_ALL, this maps
824  * the position of each category to our corresponding internal index for it.
825  * This is initialized at run time if needed */
826 STATIC
827 unsigned int
828 map_LC_ALL_position_to_index[LC_ALL_INDEX_] = { PERL_UINT_MAX };
829
830 #  endif
831 #endif
832 #if defined(USE_LOCALE) || defined(DEBUGGING)
833
834 STATIC const char *
835 S_get_displayable_string(pTHX_
836                          const char * const s,
837                          const char * const e,
838                          const bool is_utf8)
839 {
840     PERL_ARGS_ASSERT_GET_DISPLAYABLE_STRING;
841
842     if (e <= s) {
843         return "";
844     }
845
846     const char * t = s;
847     bool prev_was_printable = TRUE;
848     bool first_time = TRUE;
849     char * ret;
850
851     /* Worst case scenario: All are non-printable so have a blank between each.
852      * If UTF-8, all are the largest possible code point; otherwise all are a
853      * single byte.  '(2 + 1)'  is from each byte takes 2 characters to
854      * display, and a blank (or NUL for the final one) after it */
855     const Size_t size = (e - s) * (2 + 1) * ((is_utf8) ? UVSIZE : 1);
856     Newxz(ret, size, char);
857     SAVEFREEPV(ret);
858
859     while (t < e) {
860         UV cp = (is_utf8)
861                 ?  utf8_to_uvchr_buf((U8 *) t, e, NULL)
862                 : * (U8 *) t;
863         if (isPRINT(cp)) {
864             if (! prev_was_printable) {
865                 my_strlcat(ret, " ", size);
866             }
867
868             /* Escape these to avoid any ambiguity */
869             if (cp == ' ' || cp == '\\') {
870                 my_strlcat(ret, "\\", size);
871             }
872             my_strlcat(ret, Perl_form(aTHX_ "%c", (U8) cp), size);
873             prev_was_printable = TRUE;
874         }
875         else {
876             if (! first_time) {
877                 my_strlcat(ret, " ", size);
878             }
879             my_strlcat(ret, Perl_form(aTHX_ "%02" UVXf, cp), size);
880             prev_was_printable = FALSE;
881         }
882         t += (is_utf8) ? UTF8SKIP(t) : 1;
883         first_time = FALSE;
884     }
885
886     return ret;
887 }
888
889 #endif
890 #ifdef USE_LOCALE
891
892 # define get_category_index(cat) get_category_index_helper(cat, NULL, __LINE__)
893
894 STATIC unsigned int
895 S_get_category_index_helper(pTHX_ const int category, bool * succeeded,
896                                   const line_t caller_line)
897 {
898     PERL_ARGS_ASSERT_GET_CATEGORY_INDEX_HELPER;
899
900     /* Given a category, return the equivalent internal index we generally use
901      * instead, warn or panic if not found. */
902
903     unsigned int i;
904
905 #  undef PERL_LOCALE_TABLE_ENTRY
906 #  define PERL_LOCALE_TABLE_ENTRY(name, call_back)                          \
907                     case LC_ ## name: i =  LC_ ## name ## _INDEX_; break;
908
909     switch (category) {
910
911 #  include "locale_table.h"
912 #  ifdef LC_ALL
913       case LC_ALL: i =  LC_ALL_INDEX_; break;
914 #  endif
915
916       default: goto unknown_locale;
917     }
918
919     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
920                            "index of category %d (%s) is %d;"
921                            " called from %" LINE_Tf "\n",
922                            category, category_names[i], i, caller_line));
923
924     if (succeeded) {
925         *succeeded = true;
926     }
927
928     return i;
929
930   unknown_locale:
931
932     if (succeeded) {
933         *succeeded = false;
934         return 0;   /* Arbitrary */
935     }
936
937     locale_panic_via_(Perl_form(aTHX_ "Unknown locale category %d", category),
938                       __FILE__, caller_line);
939     NOT_REACHED; /* NOTREACHED */
940 }
941
942 #endif /* ifdef USE_LOCALE */
943
944 void
945 Perl_force_locale_unlock(pTHX)
946 {
947     /* Remove any locale mutex, in preperation for an inglorious termination,
948      * typically a  panic */
949
950 #if defined(USE_LOCALE_THREADS)
951
952     /* If recursively locked, clear all at once */
953     if (PL_locale_mutex_depth > 1) {
954         PL_locale_mutex_depth = 1;
955     }
956
957     if (PL_locale_mutex_depth > 0) {
958         LOCALE_UNLOCK_;
959     }
960
961 #endif
962
963 }
964
965 #ifdef USE_POSIX_2008_LOCALE
966
967 STATIC locale_t
968 S_use_curlocale_scratch(pTHX)
969 {
970     /* This function is used to hide from the caller the case where the current
971      * locale_t object in POSIX 2008 is the global one, which is illegal in
972      * many of the P2008 API calls.  This checks for that and, if necessary
973      * creates a proper P2008 object.  Any prior object is deleted, as is any
974      * remaining object during global destruction. */
975
976     locale_t cur = uselocale((locale_t) 0);
977
978     if (cur != LC_GLOBAL_LOCALE) {
979         return cur;
980     }
981
982     if (PL_scratch_locale_obj) {
983         freelocale(PL_scratch_locale_obj);
984     }
985
986     PL_scratch_locale_obj = duplocale(LC_GLOBAL_LOCALE);
987     return PL_scratch_locale_obj;
988 }
989
990 #endif
991
992 void
993 Perl_locale_panic(const char * msg,
994                   const line_t immediate_caller_line,
995                   const char * const higher_caller_file,
996                   const line_t higher_caller_line)
997 {
998     PERL_ARGS_ASSERT_LOCALE_PANIC;
999     dTHX;
1000     dSAVE_ERRNO;
1001
1002     force_locale_unlock();
1003
1004 #ifdef USE_C_BACKTRACE
1005     dump_c_backtrace(Perl_debug_log, 20, 1);
1006 #endif
1007
1008     const char * called_by = "";
1009     if (   strNE(__FILE__, higher_caller_file)
1010         || immediate_caller_line != higher_caller_line)
1011     {
1012         called_by = Perl_form(aTHX_ "\nCalled by %s: %" LINE_Tf "\n",
1013                                     higher_caller_file, higher_caller_line);
1014     }
1015
1016     RESTORE_ERRNO;
1017
1018     const char * errno_text;
1019
1020 #ifdef HAS_EXTENDED_OS_ERRNO
1021
1022     const int extended_errnum = get_extended_os_errno();
1023     if (errno != extended_errnum) {
1024         errno_text = Perl_form(aTHX_ "; errno=%d, $^E=%d",
1025                                      errno, extended_errnum);
1026     }
1027     else
1028
1029 #endif
1030
1031     {
1032         errno_text = Perl_form(aTHX_ "; errno=%d", errno);
1033     }
1034
1035     /* diag_listed_as: panic: %s */
1036     Perl_croak(aTHX_ "%s: %" LINE_Tf ": panic: %s%s%s\n",
1037                      __FILE__, immediate_caller_line,
1038                      msg, errno_text, called_by);
1039 }
1040
1041 /* Macros to report and croak on an unexpected failure to set the locale.  The
1042  * via version has more stack trace information */
1043 #define setlocale_failure_panic_i(i, cur, fail, line, higher_line)          \
1044     setlocale_failure_panic_via_i(i, cur, fail, __LINE__, line,             \
1045                                   __FILE__, higher_line)
1046
1047 #define setlocale_failure_panic_c(cat, cur, fail, line, higher_line)        \
1048    setlocale_failure_panic_i(cat##_INDEX_, cur, fail, line, higher_line)
1049
1050 #if defined(LC_ALL) && defined(USE_LOCALE)
1051
1052 /* Expands to the code to
1053  *      result = savepvn(s, len)
1054  * if the category whose internal index is 'i' doesn't need to be kept in the C
1055  * locale on this system, or if 'action is 'no_override'.  Otherwise it expands
1056  * to
1057  *      result = savepv("C")
1058  * unless 'action' isn't 'check_that_overridden', in which case if the string
1059  * 's' isn't already "C" it panics */
1060 #  ifndef HAS_IGNORED_LOCALE_CATEGORIES_
1061 #    define OVERRIDE_AND_SAVEPV(s, len, result, i, action)                  \
1062                                                   result = savepvn(s, len)
1063 #  else
1064 #    define OVERRIDE_AND_SAVEPV(s, len, result, i, action)                  \
1065         STMT_START {                                                        \
1066             if (LIKELY(   ! need_to_override_category(i)                    \
1067                        || action == no_override)) {                         \
1068                 result = savepvn(s, len);                                   \
1069             }                                                               \
1070             else {                                                          \
1071                 const char * temp = savepvn(s, len);                        \
1072                 result = savepv(override_ignored_category(i, temp));        \
1073                 if (action == check_that_overridden && strNE(result, temp)) { \
1074                     locale_panic_(Perl_form(aTHX_                           \
1075                                 "%s expected to be '%s', instead is '%s'",  \
1076                                 category_names[i], result, temp));          \
1077                 }                                                           \
1078                 Safefree(temp);                                             \
1079             }                                                               \
1080         } STMT_END
1081 #  endif
1082
1083 STATIC parse_LC_ALL_string_return
1084 S_parse_LC_ALL_string(pTHX_ const char * string,
1085                             const char ** output,
1086                             const parse_LC_ALL_STRING_action  override,
1087                             bool always_use_full_array,
1088                             const bool panic_on_error,
1089                             const line_t caller_line)
1090 {
1091     /* This function parses the value of the input 'string' which is expected
1092      * to be the representation of an LC_ALL locale, and splits the result into
1093      * the values for the individual component categories, returning those in
1094      * the 'output' array.  Each array value will be a savepv() copy that is
1095      * the responsibility of the caller to make sure gets freed
1096      *
1097      * The locale for each category is independent of the other categories.
1098      * Often, they are all the same, but certainly not always.  Perl, in fact,
1099      * usually keeps LC_NUMERIC in the C locale, regardless of the underlying
1100      * locale.  LC_ALL has to be able to represent the case of when not all
1101      * categories have the same locale.  Platforms have differing ways of
1102      * representing this.  Internally, this file uses the 'name=value;'
1103      * representation found on some platforms, so this function always looks
1104      * for and parses that.  Other platforms use a positional notation.  On
1105      * those platforms, this function also parses that form.  It examines the
1106      * input to see which form is being parsed.
1107      *
1108      * Often, all categories will have the same locale.  This is special cased
1109      * if 'always_use_full_array' is false on input:
1110      *      1) If the input 'string' is a single value, this function doesn't
1111      *         store anything into 'output', and returns 'no_array'
1112      *      2) Some platforms will return multiple occurrences of the same
1113      *         value rather than coalescing them down to a single one.  HP-UX
1114      *         is such a one.  This function will do that collapsing for you,
1115      *         returning 'only_element_0' and saving the single value in
1116      *         output[0], which the caller will need to arrange to be freed.
1117      *         The rest of output[] is undefined, and does not need to be
1118      *         freed.
1119      *
1120      * Otherwise, the input 'string' may not be valid.  This function looks
1121      * mainly for syntactic errors, and if found, returns 'invalid'.  'output'
1122      * will not be filled in in that case, but the input state of it isn't
1123      * necessarily preserved.  Turning on -DL debugging will give details as to
1124      * the error.  If 'panic_on_error' is 'true', the function panics instead
1125      * of returning on error, with a message giving the details.
1126      *
1127      * Otherwise, output[] will be filled with the individual locale names for
1128      * all categories on the system, 'full_array' will be returned, and the
1129      * caller needs to arrange for each to be freed.  This means that either at
1130      * least one category differed from the others, or 'always_use_full_array' was
1131      * true on input.
1132      *
1133      * perl may be configured to ignore changes to a category's locale to
1134      * non-C.  The parameter 'override' tells this function what to do when
1135      * encountering such an illegal combination:
1136      *
1137      *      no_override             indicates to take no special action
1138      *      override_if_ignored,    indicates to return 'C' instead of what the
1139      *                              input string actually says.
1140      *      check_that_overridden   indicates to panic if the string says the
1141      *                              category is not 'C'.  This is used when
1142      *                              non-C is very unexpected behavior.
1143      * */
1144
1145     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
1146                            "Entering parse_LC_ALL_string; called from %"    \
1147                            LINE_Tf "\nnew='%s'\n", caller_line, string));
1148
1149 #  ifdef PERL_LC_ALL_USES_NAME_VALUE_PAIRS
1150
1151     const char separator[] = ";";
1152     const Size_t separator_len = 1;
1153     const bool single_component = (strchr(string, ';') == NULL);
1154
1155 #  else
1156
1157     /* It's possible (but quite unlikely) that the separator string is an '='
1158      * or a ';'.  Requiring both to be present for using the 'name=value;' form
1159      * properly handles those possibilities */
1160     const bool name_value = strchr(string, '=') && strchr(string, ';');
1161     const char * separator;
1162     Size_t separator_len;
1163     bool single_component;
1164     if (name_value) {
1165         separator = ";";
1166         separator_len = 1;
1167         single_component = false;   /* Since has both [;=], must be multi */
1168     }
1169     else {
1170         separator = PERL_LC_ALL_SEPARATOR;
1171         separator_len = STRLENs(PERL_LC_ALL_SEPARATOR);
1172         single_component = instr(string, separator) == NULL;
1173     }
1174
1175     Size_t component_number = 0;    /* Position in the parsing loop below */
1176
1177 #  endif
1178 #  ifndef HAS_IGNORED_LOCALE_CATEGORIES_
1179     PERL_UNUSED_ARG(override);
1180 #  else
1181
1182     /* Any ignored categories are to be set to "C", so if this single-component
1183      * LC_ALL isn't to C, it has both "C" and non-C, so isn't really a single
1184      * component.  All the non-ignored categories are set to the input
1185      * component, but the ignored ones are overridden to be C.
1186      *
1187      * This incidentally handles the case where the string is "".  The return
1188      * will be C for each ignored category and "" for the others.  Then the
1189      * caller can individually set each category, and get the right answer. */
1190     if (single_component && ! isNAME_C_OR_POSIX(string)) {
1191         for (unsigned int i = 0; i < LC_ALL_INDEX_; i++) {
1192            OVERRIDE_AND_SAVEPV(string, strlen(string), output[i], i, override);
1193         }
1194
1195         return full_array;
1196     }
1197
1198 #  endif
1199
1200     if (single_component) {
1201         if (! always_use_full_array) {
1202             return no_array;
1203         }
1204
1205         for (unsigned int i = 0; i < LC_ALL_INDEX_; i++) {
1206             output[i] = savepv(string);
1207         }
1208
1209         return full_array;
1210     }
1211
1212     /* Here the input is multiple components.  Parse through them.  (It is
1213      * possible that these components are all the same, so we check, and if so,
1214      * return just the 0th component (unless 'always_use_full_array' is true)
1215      *
1216      * This enum notes the possible errors findable in parsing */
1217     enum {
1218             incomplete,
1219             no_equals,
1220             unknown_category,
1221             contains_LC_ALL_element
1222     } error;
1223
1224     /* Keep track of the categories we have encountered so far */
1225     bool seen[LC_ALL_INDEX_] = { false };
1226
1227     Size_t index;           /* Our internal index for the current category */
1228     const char * s = string;
1229     const char * e = s + strlen(string);
1230     const char * category_end = NULL;
1231     const char * saved_first = NULL;
1232
1233     /* Parse the input locale string */
1234     while (s < e) {
1235
1236         /* 'separator' has been set up to delimit the components */
1237         const char * next_sep = instr(s, separator);
1238         if (! next_sep) {   /* At the end of the input */
1239             next_sep = e;
1240         }
1241
1242 #  ifndef PERL_LC_ALL_USES_NAME_VALUE_PAIRS
1243
1244         if (! name_value) {
1245             /* Get the index of the category in this position */
1246             index = map_LC_ALL_position_to_index[component_number++];
1247         }
1248         else
1249
1250 #  endif
1251
1252         {   /* Get the category part when each component is the
1253              * 'category=locale' form */
1254
1255             category_end = strchr(s, '=');
1256
1257             /* The '=' terminates the category name.  If no '=', is improper
1258              * form */
1259             if (! category_end) {
1260                 error = no_equals;
1261                 goto failure;
1262             }
1263
1264             /* Find our internal index of the category name; uses a linear
1265              * search.  (XXX This could be avoided by various means, but the
1266              * maximum likely search is 6 items, and khw doesn't think the
1267              * added complexity would save very much at all.) */
1268             const unsigned int name_len = (unsigned int) (category_end - s);
1269             for (index = 0; index < C_ARRAY_LENGTH(category_names); index++) {
1270                 if (   name_len == category_name_lengths[index]
1271                     && memEQ(s, category_names[index], name_len))
1272                 {
1273                     goto found_category;
1274                 }
1275             }
1276
1277             /* Here, the category is not in our list. */
1278             error = unknown_category;
1279             goto failure;
1280
1281           found_category:   /* The system knows about this category. */
1282
1283             if (index == LC_ALL_INDEX_) {
1284                 error = contains_LC_ALL_element;
1285                 goto failure;
1286             }
1287
1288             /* The locale name starts just beyond the '=' */
1289             s = category_end + 1;
1290
1291             /* Linux (and maybe others) doesn't treat a duplicate category in
1292              * the string as an error.  Instead it uses the final occurrence as
1293              * the intended value.  So if this is a duplicate, free the former
1294              * value before setting the new one */
1295             if (seen[index]) {
1296                 Safefree(output[index]);
1297             }
1298             else {
1299                 seen[index] = true;
1300             }
1301         }
1302
1303         /* Here, 'index' contains our internal index number for the current
1304          * category, and 's' points to the beginning of the locale name for
1305          * that category. */
1306         OVERRIDE_AND_SAVEPV(s, next_sep - s, output[index], index, override);
1307
1308         if (! always_use_full_array) {
1309             if (! saved_first) {
1310                 saved_first = output[index];
1311             }
1312             else {
1313                 if (strNE(saved_first, output[index])) {
1314                     always_use_full_array = true;
1315                 }
1316             }
1317         }
1318
1319         /* Next time start from the new position */
1320         s = next_sep + separator_len;
1321     }
1322
1323     /* Finished looping through all the categories
1324      *
1325      * Check if the input was incomplete. */
1326
1327 #  ifndef PERL_LC_ALL_USES_NAME_VALUE_PAIRS
1328
1329     if (! name_value) {     /* Positional notation */
1330         if (component_number != LC_ALL_INDEX_) {
1331             error = incomplete;
1332             goto failure;
1333         }
1334     }
1335     else
1336
1337 #  endif
1338
1339     {   /* Here is the name=value notation */
1340         for (unsigned int i = 0; i < LC_ALL_INDEX_; i++) {
1341             if (! seen[i]) {
1342                 error = incomplete;
1343                 goto failure;
1344             }
1345         }
1346     }
1347
1348     /* In the loop above, we changed 'always_use_full_array' to true iff not all
1349      * categories have the same locale.  Hence, if it is still 'false', all of
1350      * them are the same. */
1351     if (always_use_full_array) {
1352         return full_array;
1353     }
1354
1355     /* Free the dangling ones */
1356     for (unsigned int i = 1; i < LC_ALL_INDEX_; i++) {
1357         Safefree(output[i]);
1358         output[i] = NULL;
1359     }
1360
1361     return only_element_0;
1362
1363   failure:
1364
1365     /* Don't leave memory dangling that we allocated before the failure */
1366     for (unsigned int i = 0; i < LC_ALL_INDEX_; i++) {
1367         if (seen[i]) {
1368             Safefree(output[i]);
1369             output[i] = NULL;
1370         }
1371     }
1372
1373     const char * msg;
1374     const char * display_start = s;
1375     const char * display_end = e;
1376
1377     switch (error) {
1378         case incomplete:
1379             msg = "doesn't list every locale category";
1380             display_start = string;
1381             break;
1382         case no_equals:
1383             msg = "needs an '=' to split name=value";
1384             break;
1385         case unknown_category:
1386             msg = "is an unknown category";
1387             display_end = (category_end && category_end > display_start)
1388                           ? category_end
1389                           : e;
1390             break;
1391         case contains_LC_ALL_element:
1392             msg = "has LC_ALL, which is illegal here";
1393             break;
1394     }
1395
1396     msg = Perl_form(aTHX_ "'%.*s' %s\n",
1397                           (int) (display_end - display_start),
1398                           display_start, msg);
1399
1400     DEBUG_L(PerlIO_printf(Perl_debug_log, "%s", msg));
1401
1402     if (panic_on_error) {
1403         locale_panic_via_(msg, __FILE__, caller_line);
1404     }
1405
1406     return invalid;
1407 }
1408
1409 #  undef OVERRIDE_AND_SAVEPV
1410 #endif
1411
1412 /*==========================================================================
1413  * Here starts the code that gives a uniform interface to its callers, hiding
1414  * the differences between platforms.
1415  *
1416  * base_posix_setlocale_() presents a consistent POSIX-compliant interface to
1417  * setlocale().   Windows requres a customized base-level setlocale().  This
1418  * layer should only be used by the next level up: the plain posix_setlocale
1419  * layer.  Any necessary mutex locking needs to be done at a higher level.  The
1420  * return may be overwritten by the next call to this function */
1421 #ifdef WIN32
1422 #  define base_posix_setlocale_(cat, locale) win32_setlocale(cat, locale)
1423 #else
1424 #  define base_posix_setlocale_(cat, locale)                                \
1425                                     ((const char *) setlocale(cat, locale))
1426 #endif
1427
1428 /*==========================================================================
1429  * Here is the main posix layer.  It is the same as the base one unless the
1430  * system is lacking LC_ALL, or there are categories that we ignore, but that
1431  * the system libc knows about */
1432
1433 #if ! defined(USE_LOCALE)                                                   \
1434  ||  (defined(LC_ALL) && ! defined(HAS_IGNORED_LOCALE_CATEGORIES_))
1435 #  define posix_setlocale(cat, locale) base_posix_setlocale_(cat, locale)
1436 #else
1437 #  define posix_setlocale(cat, locale)                                      \
1438         S_posix_setlocale_with_complications(aTHX_ cat, locale, __LINE__)
1439
1440 STATIC const char *
1441 S_posix_setlocale_with_complications(pTHX_ const int cat,
1442                                            const char * new_locale,
1443                                            const line_t caller_line)
1444 {
1445     /* This implements the posix layer above the base posix layer.
1446      * It is needed to reconcile our internal records that reflect only a
1447      * proper subset of the categories known by the system. */
1448
1449     /* Querying the current locale returns the real value */
1450     if (new_locale == NULL) {
1451         new_locale = base_posix_setlocale_(cat, NULL);
1452         assert(new_locale);
1453         return new_locale;
1454     }
1455
1456     const char * locale_on_entry = NULL;
1457
1458     /* If setting from the environment, actually do the set to get the system's
1459      * idea of what that means; we may have to override later. */
1460     if (strEQ(new_locale, "")) {
1461         locale_on_entry = base_posix_setlocale_(cat, NULL);
1462         assert(locale_on_entry);
1463         new_locale = base_posix_setlocale_(cat, "");
1464         if (! new_locale) {
1465             SET_EINVAL;
1466             return NULL;
1467         }
1468     }
1469
1470 #  ifdef LC_ALL
1471
1472     const char * new_locales[LC_ALL_INDEX_] = { NULL };
1473
1474     if (cat == LC_ALL) {
1475         switch (parse_LC_ALL_string(new_locale,
1476                                     (const char **) &new_locales,
1477                                     override_if_ignored,   /* Override any
1478                                                               ignored
1479                                                               categories */
1480                                     false,    /* Return only [0] if suffices */
1481                                     false,    /* Don't panic on error */
1482                                     caller_line))
1483         {
1484           case invalid:
1485             SET_EINVAL;
1486             return NULL;
1487
1488           case no_array:
1489             break;
1490
1491           case only_element_0:
1492             new_locale = new_locales[0];
1493             SAVEFREEPV(new_locale);
1494             break;
1495
1496           case full_array:
1497
1498             /* Turn the array into a string that the libc setlocale() should
1499              * understand.   (Another option would be to loop, setting the
1500              * individual locales, and then return base(cat, NULL) */
1501             new_locale = calculate_LC_ALL_string(new_locales,
1502                                                  EXTERNAL_FORMAT_FOR_SET,
1503                                                  WANT_TEMP_PV,
1504                                                  caller_line);
1505
1506             for (unsigned i = 0; i < LC_ALL_INDEX_; i++) {
1507                 Safefree(new_locales[i]);
1508             }
1509
1510             /* And call the libc setlocale.  We could avoid this call if
1511              * locale_on_entry is set and eq the new_locale.  But that would be
1512              * only for the relatively rare case of the desired locale being
1513              * "", and the time spent in doing the string compare might be more
1514              * than that of just setting it unconditionally */
1515             new_locale = base_posix_setlocale_(cat, new_locale);
1516             if (! new_locale) {
1517                  goto failure;
1518             }
1519
1520             return new_locale;
1521         }
1522     }
1523
1524 #  endif
1525
1526     /* Here, 'new_locale' is a single value, not an aggregation.  Just set it.
1527      * */
1528     new_locale =
1529         base_posix_setlocale_(cat,
1530                               override_ignored_category(
1531                                           get_category_index(cat), new_locale));
1532     if (! new_locale) {
1533         goto failure;
1534     }
1535
1536     return new_locale;
1537
1538  failure:
1539
1540     /* 'locale_on_entry' being set indicates there has likely been a change in
1541      * locale which needs to be restored */
1542     if (locale_on_entry) {
1543         if (! base_posix_setlocale_(cat, locale_on_entry)) {
1544             setlocale_failure_panic_i(get_category_index(cat),
1545                                       NULL, locale_on_entry,
1546                                       __LINE__, caller_line);
1547         }
1548     }
1549
1550     SET_EINVAL;
1551     return NULL;
1552 }
1553
1554 #endif
1555
1556 /* End of posix layer
1557  *==========================================================================
1558  *
1559  * The next layer up is to catch vagaries and bugs in the libc setlocale return
1560  * value.  The return is not guaranteed to be stable.
1561  *
1562  * Any necessary mutex locking needs to be done at a higher level.
1563  *
1564  * On most platforms this layer is empty, expanding to just the layer
1565  * below.   To enable it, call Configure with either or both:
1566  * -Accflags=-DHAS_LF_IN_SETLOCALE_RETURN
1567  *                  to indicate that extraneous \n characters can be returned
1568  *                  by setlocale()
1569  * -Accflags=-DHAS_BROKEN_SETLOCALE_QUERY_LC_ALL
1570  *                  to indicate that setlocale(LC_ALL, NULL) cannot be relied
1571  *                  on
1572  */
1573
1574 #define STDIZED_SETLOCALE_LOCK    POSIX_SETLOCALE_LOCK
1575 #define STDIZED_SETLOCALE_UNLOCK  POSIX_SETLOCALE_UNLOCK
1576 #if ! defined(USE_LOCALE)                                                   \
1577  || ! (   defined(HAS_LF_IN_SETLOCALE_RETURN)                               \
1578        || defined(HAS_BROKEN_SETLOCALE_QUERY_LC_ALL))
1579 #  define stdized_setlocale(cat, locale)  posix_setlocale(cat, locale)
1580 #  define stdize_locale(cat, locale)  (locale)
1581 #else
1582 #  define stdized_setlocale(cat, locale)                                    \
1583         S_stdize_locale(aTHX_ cat, posix_setlocale(cat, locale), __LINE__)
1584
1585 STATIC const char *
1586 S_stdize_locale(pTHX_ const int category,
1587                       const char *input_locale,
1588                       const line_t caller_line)
1589 {
1590     /* The return value of setlocale() is opaque, but is required to be usable
1591      * as input to a future setlocale() to create the same state.
1592      * Unfortunately not all systems are compliant.  This function brings those
1593      * outliers into conformance.  It is based on what problems have arisen in
1594      * the field.
1595      *
1596      * This has similar constraints as the posix layer.  You need to lock
1597      * around it until its return is safely copied or no longer needed. (The
1598      * return may point to a global static buffer or may be mortalized.)
1599      *
1600      * The current things this corrects are:
1601      * 1) A new-line.  This function chops any \n characters
1602      * 2) A broken 'setlocale(LC_ALL, foo)'  This constructs a proper returned
1603      *                 string from the constituent categories
1604      *
1605      * If no changes were made, the input is returned as-is */
1606
1607     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
1608                           "Entering stdize_locale(%d, '%s');"
1609                           " called from %" LINE_Tf "\n",
1610                           category, input_locale, caller_line));
1611
1612     if (input_locale == NULL) {
1613         SET_EINVAL;
1614         return NULL;
1615     }
1616
1617     char * retval = (char *) input_locale;
1618
1619 #  if defined(LC_ALL) && defined(HAS_BROKEN_SETLOCALE_QUERY_LC_ALL)
1620
1621         /* If setlocale(LC_ALL, NULL) is broken, compute what the system
1622          * actually thinks it should be from its individual components */
1623     if (category == LC_ALL) {
1624         retval = (char *) calculate_LC_ALL_string(
1625                                           NULL,  /* query each individ locale */
1626                                           EXTERNAL_FORMAT_FOR_SET,
1627                                           WANT_TEMP_PV,
1628                                           caller_line);
1629     }
1630
1631 #  endif
1632 #  ifdef HAS_NL_IN_SETLOCALE_RETURN
1633
1634     char * first_bad = NULL;
1635
1636 #    ifndef LC_ALL
1637
1638     PERL_UNUSED_ARG(category);
1639     PERL_UNUSED_ARG(caller_line);
1640
1641 #      define INPUT_LOCALE  retval
1642 #      define MARK_CHANGED
1643 #    else
1644
1645     char * individ_locales[LC_ALL_INDEX_] = { NULL };
1646     bool made_changes = false;
1647     Size_t upper;
1648     if (category != LC_ALL) {
1649         individ_locales[0] = retval;
1650         upper = 0;
1651     }
1652     else {
1653
1654         /* And parse the locale string, splitting into its individual
1655          * components. */
1656         switch (parse_LC_ALL_string(retval,
1657                                     (const char **) &individ_locales,
1658                                     check_that_overridden, /* ignored
1659                                                               categories should
1660                                                               already have been
1661                                                               overridden */
1662                                     false,    /* Return only [0] if suffices */
1663                                     false,    /* Don't panic on error */
1664                                     caller_line))
1665         {
1666           case invalid:
1667             SET_EINVAL;
1668             return NULL;
1669
1670           case full_array: /* Loop below through all the component categories.
1671                             */
1672             upper = LC_ALL_INDEX_ - 1;
1673             break;
1674
1675           case no_array:
1676             /* All categories here are set to the same locale, and the parse
1677              * didn't fill in any of 'individ_locales'.  Set the 0th element to
1678              * that locale. */
1679             individ_locales[0] = retval;
1680             /* FALLTHROUGH */
1681
1682           case only_element_0: /* Element 0 is the only element we need to look
1683                                   at */
1684             upper = 0;
1685             break;
1686         }
1687     }
1688
1689     for (unsigned int i = 0; i <= upper; i++)
1690
1691 #      define INPUT_LOCALE  individ_locales[i]
1692 #      define MARK_CHANGED  made_changes = true;
1693 #    endif    /* Has LC_ALL */
1694
1695     {
1696         first_bad = (char *) strchr(INPUT_LOCALE, '\n');
1697
1698         /* Most likely, there isn't a problem with the input */
1699         if (UNLIKELY(first_bad)) {
1700
1701             /* This element will need to be adjusted.  Create a modifiable
1702              * copy. */
1703             MARK_CHANGED
1704             retval = savepv(INPUT_LOCALE);
1705             SAVEFREEPV(retval);
1706
1707             /* Translate the found position into terms of the copy */
1708             first_bad = retval + (first_bad - INPUT_LOCALE);
1709
1710             /* Get rid of the \n and what follows.  (Originally, only a
1711              * trailing \n was stripped.  Unsure what to do if not trailing) */
1712             *((char *) first_bad) = '\0';
1713         }   /* End of needs adjusting */
1714     }   /* End of looking for problems */
1715
1716 #    ifdef LC_ALL
1717
1718     /* If we had multiple elements, extra work is required */
1719     if (upper != 0) {
1720
1721         /* If no changes were made to the input, 'retval' already contains it
1722          * */
1723         if (made_changes) {
1724
1725             /* But if did make changes, need to calculate the new value */
1726             retval = (char *) calculate_LC_ALL_string(
1727                                             (const char **) &individ_locales,
1728                                             EXTERNAL_FORMAT_FOR_SET,
1729                                             WANT_TEMP_PV,
1730                                             caller_line);
1731         }
1732
1733         /* And free the no-longer needed memory */
1734         for (unsigned int i = 0; i <= upper; i++) {
1735             Safefree(individ_locales[i]);
1736         }
1737     }
1738
1739 #    endif
1740 #    undef INPUT_LOCALE
1741 #    undef MARK_CHANGED
1742 #  endif    /* HAS_NL_IN_SETLOCALE_RETURN */
1743
1744     return (const char *) retval;
1745 }
1746
1747 #endif  /* USE_LOCALE */
1748
1749 /* End of stdize_locale layer
1750  *
1751  * ==========================================================================
1752  *
1753  * The next many lines form several implementations of a layer above the
1754  * close-to-the-metal 'posix' and 'stdized' macros.  They are used to present a
1755  * uniform API to the rest of the code in this file in spite of the disparate
1756  * underlying implementations.  Which implementation gets compiled depends on
1757  * the platform capabilities (and some user choice) as determined by Configure.
1758  *
1759  * As more fully described in the introductory comments in this file, the
1760  * API of each implementation consists of three sets of macros.  Each set has
1761  * three variants with suffixes '_c', '_r', and '_i'.  In the list below '_X'
1762  * is to be replaced by any of these suffixes.
1763  *
1764  * 1) bool_setlocale_X  attempts to set the given category's locale to the
1765  *                      given value, returning if it worked or not.
1766  * 2) void_setlocale_X  is like the corresponding bool_setlocale, but used when
1767  *                      success is the only sane outcome, so failure causes it
1768  *                      to panic.
1769  * 3) querylocale_X     to see what the given category's locale is
1770  *
1771  * 4) setlocale_i()     is defined only in those implementations where the bool
1772  *                      and query forms are essentially the same, and can be
1773  *                      combined to save CPU time.
1774  *
1775  * Each implementation below is separated by ==== lines, and includes bool,
1776  * void, and query macros.  The query macros are first, followed by any
1777  * functions needed to implement them.  Then come the bool, again followed by
1778  * any implementing functions  Then are the void macros; next is setlocale_i if
1779  * present on this implementation.  Finally are any helper functions.  The sets
1780  * in each implementation are separated by ---- lines.
1781  *
1782  * The returned strings from all the querylocale...() forms in all
1783  * implementations are thread-safe, and the caller should not free them,
1784  * but each may be a mortalized copy.  If you need something stable across
1785  * calls, you need to savepv() the result yourself.
1786  *
1787  *===========================================================================*/
1788
1789 #if    (! defined(USE_LOCALE_THREADS) && ! defined(USE_POSIX_2008_LOCALE))    \
1790     || (  defined(WIN32) && defined(USE_THREAD_SAFE_LOCALE))
1791
1792 /* For non-threaded perls, the implementation just expands to the base-level
1793  * functions (except if we are Configured to nonetheless use the POSIX 2008
1794  * interface) This implementation is also used on threaded perls where
1795  * threading is invisible to us.  Currently this is only on later Windows
1796  * versions. */
1797
1798 #  define querylocale_r(cat)  mortalized_pv_copy(stdized_setlocale(cat, NULL))
1799 #  define querylocale_c(cat)  querylocale_r(cat)
1800 #  define querylocale_i(i)    querylocale_c(categories[i])
1801
1802 /*---------------------------------------------------------------------------*/
1803
1804 #  define bool_setlocale_r(cat, locale) cBOOL(posix_setlocale(cat, locale))
1805 #  define bool_setlocale_i(i, locale)                                       \
1806                                    bool_setlocale_c(categories[i], locale)
1807 #  define bool_setlocale_c(cat, locale)      bool_setlocale_r(cat, locale)
1808
1809 /*---------------------------------------------------------------------------*/
1810
1811 #  define void_setlocale_r_with_caller(cat, locale, file, line)             \
1812      STMT_START {                                                           \
1813         if (! bool_setlocale_r(cat, locale))                                \
1814             setlocale_failure_panic_via_i(get_category_index(cat),          \
1815                                           NULL, locale, __LINE__, 0,        \
1816                                           file, line);                      \
1817      } STMT_END
1818
1819 #  define void_setlocale_c_with_caller(cat, locale, file, line)             \
1820                     void_setlocale_r_with_caller(cat, locale, file, line)
1821
1822 #  define void_setlocale_i_with_caller(i, locale, file, line)               \
1823           void_setlocale_r_with_caller(categories[i], locale, file, line)
1824
1825 #  define void_setlocale_r(cat, locale)                                     \
1826             void_setlocale_r_with_caller(cat, locale, __FILE__, __LINE__)
1827 #  define void_setlocale_c(cat, locale) void_setlocale_r(cat, locale)
1828 #  define void_setlocale_i(i, locale)   void_setlocale_r(categories[i], locale)
1829
1830 /*---------------------------------------------------------------------------*/
1831
1832 /* setlocale_i is only defined for Configurations where the libc setlocale()
1833  * doesn't need any tweaking.  It allows for some shortcuts */
1834 #  ifndef USE_LOCALE_THREADS
1835 #    define setlocale_i(i, locale)   stdized_setlocale(categories[i], locale)
1836
1837 #  elif defined(WIN32) && defined(USE_THREAD_SAFE_LOCALE)
1838
1839 /* On Windows, we don't know at compile time if we are in thread-safe mode or
1840  * not.  If we are, we can just return the result of the layer below us.  If we
1841  * are in unsafe mode, we need to first copy that result to a safe place while
1842  * in a critical section */
1843
1844 #    define setlocale_i(i, locale)   S_setlocale_i(aTHX_ categories[i], locale)
1845
1846 STATIC const char *
1847 S_setlocale_i(pTHX_ const int category, const char * locale)
1848 {
1849     if (LIKELY(_configthreadlocale(0) == _ENABLE_PER_THREAD_LOCALE)) {
1850         return stdized_setlocale(category, locale);
1851     }
1852
1853     gwLOCALE_LOCK;
1854     const char * retval = save_to_buffer(stdized_setlocale(category, locale),
1855                                          &PL_setlocale_buf,
1856                                          &PL_setlocale_bufsize);
1857     gwLOCALE_UNLOCK;
1858
1859     return retval;
1860 }
1861
1862 #  endif
1863
1864 /*===========================================================================*/
1865 #elif   defined(USE_LOCALE_THREADS)                 \
1866    && ! defined(USE_THREAD_SAFE_LOCALE)
1867
1868    /* Here, there are threads, and there is no support for thread-safe
1869     * operation.  This is a dangerous situation, which perl is documented as
1870     * not supporting, but it arises in practice.  We can do a modicum of
1871     * automatic mitigation by making sure there is a per-thread return from
1872     * setlocale(), and that a mutex protects it from races */
1873
1874 #  define querylocale_r(cat)                                                \
1875                       mortalized_pv_copy(less_dicey_setlocale_r(cat, NULL))
1876 #  define querylocale_c(cat)  querylocale_r(cat)
1877 #  define querylocale_i(i)    querylocale_r(categories[i])
1878
1879 STATIC const char *
1880 S_less_dicey_setlocale_r(pTHX_ const int category, const char * locale)
1881 {
1882     const char * retval;
1883
1884     PERL_ARGS_ASSERT_LESS_DICEY_SETLOCALE_R;
1885
1886     STDIZED_SETLOCALE_LOCK;
1887
1888     retval = save_to_buffer(stdized_setlocale(category, locale),
1889                             &PL_less_dicey_locale_buf,
1890                             &PL_less_dicey_locale_bufsize);
1891
1892     STDIZED_SETLOCALE_UNLOCK;
1893
1894     return retval;
1895 }
1896
1897 /*---------------------------------------------------------------------------*/
1898
1899 #  define bool_setlocale_r(cat, locale)                                     \
1900                                less_dicey_bool_setlocale_r(cat, locale)
1901 #  define bool_setlocale_i(i, locale)                                       \
1902                                 bool_setlocale_r(categories[i], locale)
1903 #  define bool_setlocale_c(cat, locale) bool_setlocale_r(cat, locale)
1904
1905 STATIC bool
1906 S_less_dicey_bool_setlocale_r(pTHX_ const int cat, const char * locale)
1907 {
1908     bool retval;
1909
1910     PERL_ARGS_ASSERT_LESS_DICEY_BOOL_SETLOCALE_R;
1911
1912     /* Unlikely, but potentially possible that another thread could zap the
1913      * buffer from true to false or vice-versa, so need to lock here */
1914     POSIX_SETLOCALE_LOCK;
1915     retval = cBOOL(posix_setlocale(cat, locale));
1916     POSIX_SETLOCALE_UNLOCK;
1917
1918     return retval;
1919 }
1920
1921 /*---------------------------------------------------------------------------*/
1922
1923 #  define void_setlocale_r_with_caller(cat, locale, file, line)             \
1924      STMT_START {                                                           \
1925         if (! bool_setlocale_r(cat, locale))                                \
1926             setlocale_failure_panic_via_i(get_category_index(cat),          \
1927                                           NULL, locale, __LINE__, 0,        \
1928                                           file, line);                      \
1929      } STMT_END
1930
1931 #  define void_setlocale_c_with_caller(cat, locale, file, line)             \
1932                     void_setlocale_r_with_caller(cat, locale, file, line)
1933
1934 #  define void_setlocale_i_with_caller(i, locale, file, line)               \
1935           void_setlocale_r_with_caller(categories[i], locale, file, line)
1936
1937 #  define void_setlocale_r(cat, locale)                                     \
1938             void_setlocale_r_with_caller(cat, locale, __FILE__, __LINE__)
1939 #  define void_setlocale_c(cat, locale) void_setlocale_r(cat, locale)
1940 #  define void_setlocale_i(i, locale)   void_setlocale_r(categories[i], locale)
1941
1942 /*===========================================================================*/
1943
1944 #elif defined(USE_POSIX_2008_LOCALE)
1945 #  ifndef LC_ALL
1946 #    error This code assumes that LC_ALL is available on a system modern enough to have POSIX 2008
1947 #  endif
1948
1949 /* Here, there is a completely different API to get thread-safe locales.  We
1950  * emulate the setlocale() API with our own function(s).  setlocale categories,
1951  * like LC_NUMERIC, are not valid here for the POSIX 2008 API.  Instead, there
1952  * are equivalents, like LC_NUMERIC_MASK, which we use instead, which we find
1953  * by table lookup. */
1954
1955 #  if defined(__GLIBC__) && defined(USE_LOCALE_MESSAGES)
1956             /* https://sourceware.org/bugzilla/show_bug.cgi?id=24936 */
1957 #    define HAS_GLIBC_LC_MESSAGES_BUG
1958 #    include <libintl.h>
1959 #  endif
1960
1961 #  define querylocale_i(i)    querylocale_2008_i(i, __LINE__)
1962 #  define querylocale_c(cat)  querylocale_i(cat##_INDEX_)
1963 #  define querylocale_r(cat)  querylocale_i(get_category_index(cat))
1964
1965 STATIC const char *
1966 S_querylocale_2008_i(pTHX_ const unsigned int index, const line_t caller_line)
1967 {
1968     PERL_ARGS_ASSERT_QUERYLOCALE_2008_I;
1969     assert(index <= LC_ALL_INDEX_);
1970
1971     /* This function returns the name of the locale category given by the input
1972      * 'index' into our parallel tables of them.
1973      *
1974      * POSIX 2008, for some sick reason, chose not to provide a method to find
1975      * the category name of a locale, disregarding a basic linguistic tenet
1976      * that for any object, people will create a name for it.  (The next
1977      * version of the POSIX standard is proposed to fix this.)  Some vendors
1978      * have created a querylocale() function to do this in the meantime.  On
1979      * systems without querylocale(), we have to keep track of what the locale
1980      * has been set to, so that we can return its name so as to emulate
1981      * setlocale().  There are potential problems with this:
1982      *
1983      *  1)  We don't know what calling newlocale() with the locale argument ""
1984      *      actually does.  It gets its values from the program's environment.
1985      *      find_locale_from_environment() is used to work around this.  But it
1986      *      isn't fool-proof.  See the comments for that function for details.
1987      *  2)  It's possible for C code in some library to change the locale
1988      *      without us knowing it, and thus our records become wrong;
1989      *      querylocale() would catch this.  But as of September 2017, there
1990      *      are no occurrences in CPAN of uselocale().  Some libraries do use
1991      *      setlocale(), but that changes the global locale, and threads using
1992      *      per-thread locales will just ignore those changes.
1993      *  3)  Many systems have multiple names for the same locale.  Generally,
1994      *      there is an underlying base name, with aliases that evaluate to it.
1995      *      On some systems, if you set the locale to an alias, and then
1996      *      retrieve the name, you get the alias as expected; but on others you
1997      *      get the base name, not the alias you used.  And sometimes the
1998      *      charade is incomplete.  See
1999      *      https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=269375.
2000      *
2001      *      The code is structured so that the returned locale name when the
2002      *      locale is changed is whatever the result of querylocale() on the
2003      *      new locale is.  This effectively gives the result the system
2004      *      expects.  Without querylocale, the name returned is always the
2005      *      input name.  Theoretically this could cause problems, but khw knows
2006      *      of none so far, but mentions it here in case you are trying to
2007      *      debug something.  (This could be worked around by messing with the
2008      *      global locale temporarily, using setlocale() to get the base name;
2009      *      but that could cause a race.  The comments for
2010      *      find_locale_from_environment() give details on the potential race.)
2011      */
2012
2013     const locale_t cur_obj = uselocale((locale_t) 0);
2014     const char * retval;
2015
2016     DEBUG_Lv(PerlIO_printf(Perl_debug_log, "querylocale_2008_i(%s) on %p;"
2017                                            " called from %" LINE_Tf "\n",
2018                                            category_names[index], cur_obj,
2019                                            caller_line));
2020
2021     if (UNLIKELY(cur_obj == LC_GLOBAL_LOCALE)) {
2022
2023         /* Even on platforms that have querylocale(), it is unclear if they
2024          * work in the global locale, and we have the means to get the correct
2025          * answer anyway.  khw is unsure this situation even comes up these
2026          * days, hence the branch prediction */
2027         POSIX_SETLOCALE_LOCK;
2028         retval = mortalized_pv_copy(posix_setlocale(categories[index], NULL));
2029         POSIX_SETLOCALE_UNLOCK;
2030     }
2031
2032     /* Here we have handled the case of the the current locale being the global
2033      * one.  Below is the 'else' case of that.  There are two different
2034      * implementations, depending on USE_PL_CURLOCALES */
2035
2036 #  ifdef USE_PL_CURLOCALES
2037
2038     else {
2039
2040         /* PL_curlocales[] is kept up-to-date for all categories except LC_ALL,
2041          * which may have been invalidated by setting it to NULL, and if so,
2042          * should now be calculated.  (The called function updates that
2043          * element.) */
2044         if (index == LC_ALL_INDEX_ && PL_curlocales[LC_ALL_INDEX_] == NULL) {
2045             calculate_LC_ALL_string((const char **) &PL_curlocales,
2046                                     INTERNAL_FORMAT,
2047                                     WANT_VOID,
2048                                     caller_line);
2049         }
2050
2051         if (cur_obj == PL_C_locale_obj) {
2052
2053             /* If the current locale object is the C object, then the answer is
2054              * "C" or POSIX, regardless of the category.  Handling this
2055              * reasonably likely case specially shortcuts extra effort, and
2056              * hides some bugs from us in OS's that alias other locales to C,
2057              * but do so incompletely.  If our records say it is POSIX, use
2058              * that; otherwise use C.  See
2059              * https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=269375 */
2060             retval = mortalized_pv_copy((strEQ(PL_curlocales[index], "POSIX"))
2061                                         ? "POSIX"
2062                                         : "C");
2063         }
2064         else {
2065             retval = mortalized_pv_copy(PL_curlocales[index]);
2066         }
2067     }
2068
2069 #  else
2070
2071     /* Below is the implementation of the 'else' clause which handles the case
2072      * of the current locale not being the global one on platforms where
2073      * USE_PL_CURLOCALES is NOT in effect.  That means the system must have
2074      * some form of querylocale.  But these have varying characteristics, so
2075      * first create some #defines to make the actual 'else' clause uniform.
2076      *
2077      * First, glibc has a function that implements querylocale(), but is called
2078      * something else, and takes the category number; the others take the mask.
2079      * */
2080 #    if defined(USE_QUERYLOCALE) && (   defined(_NL_LOCALE_NAME)            \
2081                                      && defined(HAS_NL_LANGINFO_L))
2082 #      define my_querylocale(index, cur_obj)                                \
2083                 nl_langinfo_l(_NL_LOCALE_NAME(categories[index]), cur_obj)
2084
2085        /* Experience so far shows it is thread-safe, as well as glibc's
2086         * nl_langinfo_l(), so unless overridden, mark it so */
2087 #      ifdef NO_THREAD_SAFE_QUERYLOCALE
2088 #        undef HAS_THREAD_SAFE_QUERYLOCALE
2089 #      else
2090 #        define HAS_THREAD_SAFE_QUERYLOCALE
2091 #      endif
2092 #    else   /* below, ! glibc */
2093
2094        /* Otherwise, use the system's querylocale(). */
2095 #      define my_querylocale(index, cur_obj)                                \
2096                                querylocale(category_masks[index], cur_obj)
2097
2098        /* There is no standard for this function, and khw has never seen
2099         * anything beyond minimal vendor documentation, lacking important
2100         * details.  Experience has shown that some implementations have race
2101         * condiions, and their returns may not be thread safe.  It would be
2102         * unreliable to test for complete thread safety in Configure.  What we
2103         * do instead is to assume that it is thread-safe, unless overriden by,
2104         * say, a hints file specifying
2105         * -Accflags='-DNO_THREAD_SAFE_QUERYLOCALE */
2106 #      ifdef NO_THREAD_SAFE_QUERYLOCALE
2107 #        undef HAS_THREAD_SAFE_QUERYLOCALE
2108 #      else
2109 #        define HAS_THREAD_SAFE_QUERYLOCALE
2110 #      endif
2111 #    endif
2112
2113      /* Here, we have set up enough information to know if this querylocale()
2114       * is thread-safe, or needs to use a mutex */
2115 #    ifdef HAS_THREAD_SAFE_QUERYLOCALE
2116 #      define QUERYLOCALE_LOCK
2117 #      define QUERYLOCALE_UNLOCK
2118 #    else
2119 #      define QUERYLOCALE_LOCK    gwLOCALE_LOCK
2120 #      define QUERYLOCALE_UNLOCK  gwLOCALE_UNLOCK
2121 #    endif
2122
2123     /* Finally, everything is ready, so here is the 'else' clause to implement
2124      * the case of the current locale not being the global one on systems that
2125      * have some form of querylocale().  (POSIX will presumably eventually
2126      * publish their next version in their pipeline, which will define a
2127      * precisely specified querylocale equivalent, and there can be a new
2128      * #ifdef to use it without having to guess at its characteristics) */
2129
2130     else {
2131         /* We don't keep records when there is querylocale(), so as to avoid the
2132          * pitfalls mentioned at the beginning of this function.
2133          *
2134          * That means LC_ALL has to be calculated from all its constituent
2135          * categories each time, since the querylocale() forms on many (if not
2136          * all) platforms only work on individual categories */
2137         if (index == LC_ALL_INDEX_) {
2138             retval = calculate_LC_ALL_string(NULL, INTERNAL_FORMAT,
2139                                              WANT_TEMP_PV,
2140                                              caller_line);
2141         }
2142         else {
2143
2144             QUERYLOCALE_LOCK;
2145             retval = savepv(my_querylocale(index, cur_obj));
2146             QUERYLOCALE_UNLOCK;
2147
2148             /* querylocale() may conflate the C locale with something that
2149              * isn't exactly the same.  See for example
2150              * https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=269375
2151              * We know that if the locale object is the C one, we
2152              * are in the C locale, which may go by the name POSIX, as both, by
2153              * definition, are equivalent.  But we consider any other name
2154              * spurious, so override with "C".  As in the PL_CURLOCALES case
2155              * above, this hides those glitches, for the most part, from the
2156              * rest of our code.  (The code is ordered this way so that if the
2157              * system distinugishes "C" from "POSIX", we do too.) */
2158             if (cur_obj == PL_C_locale_obj && ! isNAME_C_OR_POSIX(retval)) {
2159                 Safefree(retval);
2160                 retval = savepv("C");
2161             }
2162
2163             SAVEFREEPV(retval);
2164         }
2165     }
2166
2167 #    undef QUERYLOCALE_LOCK
2168 #    undef QUERYLOCALE_UNLOCK
2169 #  endif
2170
2171     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2172                            "querylocale_2008_i(%s) returning '%s'\n",
2173                            category_names[index], retval));
2174     assert(strNE(retval, ""));
2175     return retval;
2176 }
2177
2178 /*---------------------------------------------------------------------------*/
2179
2180 #  define bool_setlocale_i(i, locale)                                       \
2181                               bool_setlocale_2008_i(i, locale, __LINE__)
2182 #  define bool_setlocale_c(cat, locale)                                     \
2183                                   bool_setlocale_i(cat##_INDEX_, locale)
2184 #  define bool_setlocale_r(cat, locale)                                     \
2185                        bool_setlocale_i(get_category_index(cat), locale)
2186
2187 /* If this doesn't exist on this platform, make it a no-op (to save #ifdefs) */
2188 #  ifndef update_PL_curlocales_i
2189 #    define update_PL_curlocales_i(index, new_locale, caller_line)
2190 #  endif
2191
2192 STATIC bool
2193 S_bool_setlocale_2008_i(pTHX_
2194
2195         /* Our internal index of the 'category' setlocale is called with */
2196         const unsigned int index,
2197         const char * new_locale,    /* The locale to set the category to */
2198         const line_t caller_line    /* Called from this line number */
2199        )
2200 {
2201     PERL_ARGS_ASSERT_BOOL_SETLOCALE_2008_I;
2202     assert(index <= LC_ALL_INDEX_);
2203
2204     /* This function effectively performs a setlocale() on just the current
2205      * thread; thus it is thread-safe.  It does this by using the POSIX 2008
2206      * locale functions to emulate the behavior of setlocale().  Similar to
2207      * regular setlocale(), the return from this function points to memory that
2208      * can be overwritten by other system calls, so needs to be copied
2209      * immediately if you need to retain it.  The difference here is that
2210      * system calls besides another setlocale() can overwrite it.
2211      *
2212      * By doing this, most locale-sensitive functions become thread-safe.  The
2213      * exceptions are mostly those that return a pointer to static memory.
2214      */
2215
2216     int mask = category_masks[index];
2217     const locale_t entry_obj = uselocale((locale_t) 0);
2218     const char * locale_on_entry = querylocale_i(index);
2219
2220     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2221                            "bool_setlocale_2008_i: input=%d (%s), mask=0x%x,"
2222                            " new locale=\"%s\", current locale=\"%s\","
2223                            " index=%d, entry object=%p;"
2224                            " called from %" LINE_Tf "\n",
2225                            categories[index], category_names[index], mask,
2226                            ((new_locale == NULL) ? "(nil)" : new_locale),
2227                            locale_on_entry, index, entry_obj, caller_line));
2228
2229     /* Here, trying to change the locale, but it is a no-op if the new boss is
2230      * the same as the old boss.  Except this routine is called when converting
2231      * from the global locale, so in that case we will create a per-thread
2232      * locale below (with the current values).  It also seemed that newlocale()
2233      * could free up the basis locale memory if we called it with the new and
2234      * old being the same, but khw now thinks that this was due to some other
2235      * bug, since fixed, as there are other places where newlocale() gets
2236      * similarly called without problems. */
2237     if (   entry_obj != LC_GLOBAL_LOCALE
2238         && locale_on_entry
2239         && strEQ(new_locale, locale_on_entry))
2240     {
2241         DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2242                                "bool_setlocale_2008_i: no-op to change to"
2243                                " what it already was\n"));
2244         return true;
2245     }
2246
2247 #  ifndef USE_QUERYLOCALE
2248
2249     /* Without a querylocale() mechanism, we have to figure out ourselves what
2250      * happens with setting a locale to "" */
2251
2252     if (strEQ(new_locale, "")) {
2253         new_locale = find_locale_from_environment(index);
2254         if (! new_locale) {
2255             SET_EINVAL;
2256             return false;
2257         }
2258     }
2259
2260 #  endif
2261 #  ifdef NEWLOCALE_HANDLES_DISPARATE_LC_ALL
2262
2263     const bool need_loop = false;
2264
2265 #  else
2266
2267     bool need_loop = false;
2268     const char * new_locales[LC_ALL_INDEX_] = { NULL };
2269
2270     /* If we're going to have to parse the LC_ALL string, might as well do it
2271      * now before we have made changes that we would have to back out of if the
2272      * parse fails */
2273     if (index == LC_ALL_INDEX_) {
2274         switch (parse_LC_ALL_string(new_locale,
2275                                     (const char **) &new_locales,
2276                                     override_if_ignored,
2277                                     false,    /* Return only [0] if suffices */
2278                                     false,    /* Don't panic on error */
2279                                     caller_line))
2280         {
2281           case invalid:
2282             SET_EINVAL;
2283             return false;
2284
2285           case no_array:
2286             need_loop = false;
2287             break;
2288
2289           case only_element_0:
2290             SAVEFREEPV(new_locales[0]);
2291             new_locale = new_locales[0];
2292             need_loop = false;
2293             break;
2294
2295           case full_array:
2296             need_loop = true;
2297             break;
2298         }
2299     }
2300
2301 #  endif
2302 #  ifdef HAS_GLIBC_LC_MESSAGES_BUG
2303
2304     /* For this bug, if the LC_MESSAGES locale changes, we have to do an
2305      * expensive workaround.  Save the current value so we can later determine
2306      * if it changed. */
2307     const char * old_messages_locale = NULL;
2308     if (   (index == LC_MESSAGES_INDEX_ || index == LC_ALL_INDEX_)
2309         &&  LIKELY(PL_phase != PERL_PHASE_CONSTRUCT))
2310     {
2311         old_messages_locale = querylocale_c(LC_MESSAGES);
2312     }
2313
2314 #  endif
2315
2316     assert(PL_C_locale_obj);
2317
2318     /* Now ready to switch to the input 'new_locale' */
2319
2320     /* Switching locales generally entails freeing the current one's space (at
2321      * the C library's discretion), hence we can't be using that locale at the
2322      * time of the switch (this wasn't obvious to khw from the man pages).  So
2323      * switch to a known locale object that we don't otherwise mess with. */
2324     if (! uselocale(PL_C_locale_obj)) {
2325
2326         /* Not being able to change to the C locale is severe; don't keep
2327          * going.  */
2328         setlocale_failure_panic_i(index, locale_on_entry, "C",
2329                                   __LINE__, caller_line);
2330         NOT_REACHED; /* NOTREACHED */
2331     }
2332
2333     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2334                            "bool_setlocale_2008_i: now using C"
2335                            " object=%p\n", PL_C_locale_obj));
2336
2337     /* These two objects are special:
2338      *  LC_GLOBAL_LOCALE    because it is undefined behavior to call
2339      *                      newlocale() with it as a parameter.
2340      *  PL_C_locale_obj     because newlocale() generally destroys its locale
2341      *                      object parameter when it succeeds; and we don't
2342      *                      want that happening to this immutable object.
2343      * Copies will be made for them to use instead if we get so far as to call
2344      * newlocale(). */
2345     bool entry_obj_is_special = (   entry_obj == LC_GLOBAL_LOCALE
2346                                  || entry_obj == PL_C_locale_obj);
2347     locale_t new_obj;
2348
2349     /* PL_C_locale_obj is LC_ALL set to the C locale.  If this call is to
2350      * switch to LC_ALL => C, simply use that object.  But in fact, we already
2351      * have switched to it just above, in preparation for the general case.
2352      * Since we're already there, no need to do further switching. */
2353     if (mask == LC_ALL_MASK && isNAME_C_OR_POSIX(new_locale)) {
2354         DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2355                                "bool_setlocale_2008_i: will stay in C"
2356                                " object\n"));
2357         new_obj = PL_C_locale_obj;
2358
2359         /* 'entry_obj' is now dangling, of no further use to anyone (unless it
2360          * is one of the special ones).  Free it to avoid a leak */
2361         if (! entry_obj_is_special) {
2362             freelocale(entry_obj);
2363         }
2364
2365         update_PL_curlocales_i(index, new_locale, caller_line);
2366     }
2367     else {  /* Here is the general case, not to LC_ALL => C */
2368
2369         /* The newlocale() call(s) below take a basis object to build upon to
2370          * create the changed locale, trashing it iff successful.
2371          *
2372          * For the objects that are not to be modified by this function, we
2373          * create a duplicate that gets trashed instead.
2374          *
2375          * Also if we will have to loop doing multiple newlocale()s, there is a
2376          * chance we will succeed for the first few, and then fail, having to
2377          * back out.  We need to duplicate 'entry_obj' in this case as well, so
2378          * it remains valid as something to back out to. */
2379         locale_t basis_obj = entry_obj;
2380
2381         if (entry_obj_is_special || need_loop) {
2382             basis_obj = duplocale(basis_obj);
2383             if (! basis_obj) {
2384                 locale_panic_via_("duplocale failed", __FILE__, caller_line);
2385                 NOT_REACHED; /* NOTREACHED */
2386             }
2387
2388             DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2389                                    "bool_setlocale_2008_i created %p by"
2390                                    " duping the input\n", basis_obj));
2391         }
2392
2393 #  define DEBUG_NEW_OBJECT_CREATED(category, locale, new, old, caller_line) \
2394       DEBUG_Lv(PerlIO_printf(Perl_debug_log,                                \
2395                              "bool_setlocale_2008_i(%s, %s): created %p"    \
2396                              " while freeing %p; called from %" LINE_Tf     \
2397                              " via %" LINE_Tf "\n",                         \
2398                              category, locale, new, old,                    \
2399                              caller_line, __LINE__))
2400 #  define DEBUG_NEW_OBJECT_FAILED(category, locale, basis_obj)              \
2401       DEBUG_L(PerlIO_printf(Perl_debug_log,                                 \
2402                             "bool_setlocale_2008_i: creating new object"    \
2403                             " for (%s '%s') from %p failed; called from %"  \
2404                             LINE_Tf " via %" LINE_Tf "\n",                  \
2405                             category, locale, basis_obj,                    \
2406                             caller_line, __LINE__));
2407
2408         /* Ready to create a new locale by modification of the existing one.
2409          *
2410          * NOTE: This code may incorrectly show up as a leak under the address
2411          * sanitizer. We do not free this object under normal teardown, however
2412          * you can set PERL_DESTRUCT_LEVEL=2 to cause it to be freed.
2413          */
2414
2415 #  ifdef NEWLOCALE_HANDLES_DISPARATE_LC_ALL
2416
2417         /* Some platforms have a newlocale() that can handle disparate LC_ALL
2418          * input, so on these a single call to newlocale() always works */
2419 #  else
2420
2421         /* If a single call to newlocale() will do */
2422         if (! need_loop)
2423
2424 #  endif
2425
2426         {
2427             new_obj = newlocale(mask,
2428                                 override_ignored_category(index, new_locale),
2429                                 basis_obj);
2430             if (! new_obj) {
2431                 DEBUG_NEW_OBJECT_FAILED(category_names[index], new_locale,
2432                                         basis_obj);
2433
2434                 /* Since the call failed, it didn't trash 'basis_obj', which is
2435                  * a dup for these objects, and hence would leak if we don't
2436                  * free it.  XXX However, something is seriously wrong if we
2437                  * can't switch to C or the global locale, so maybe should
2438                  * panic instead */
2439                 if (entry_obj_is_special) {
2440                     freelocale(basis_obj);
2441                 }
2442
2443                 goto must_restore_state;
2444             }
2445
2446             DEBUG_NEW_OBJECT_CREATED(category_names[index], new_locale,
2447                                      new_obj, basis_obj, caller_line);
2448
2449             update_PL_curlocales_i(index, new_locale, caller_line);
2450         }
2451
2452 #  ifndef NEWLOCALE_HANDLES_DISPARATE_LC_ALL
2453
2454         else {  /* Need multiple newlocale() calls */
2455
2456             /* Loop through the individual categories, setting the locale of
2457              * each to the corresponding name previously populated into
2458              * newlocales[].  Each iteration builds on the previous one, adding
2459              * its category to what's already been calculated, and taking as a
2460              * basis for what's been calculated 'basis_obj', which is updated
2461              * each iteration to be the result of the previous one.  Upon
2462              * success, newlocale() trashes the 'basis_obj' parameter to it.
2463              * If any iteration fails, we immediately give up, restore the
2464              * locale to what it was at the time this function was called
2465              * (saved in 'entry_obj'), and return failure. */
2466
2467             /* Loop, using the previous iteration's result as the basis for the
2468              * next one.  (The first time we effectively use the locale in
2469              * force upon entry to this function.) */
2470             for (unsigned int i = 0; i < LC_ALL_INDEX_; i++) {
2471                 new_obj = newlocale(category_masks[i],
2472                                     new_locales[i],
2473                                     basis_obj);
2474                 if (new_obj) {
2475                     DEBUG_NEW_OBJECT_CREATED(category_names[i],
2476                                              new_locales[i],
2477                                              new_obj, basis_obj,
2478                                              caller_line);
2479                     basis_obj = new_obj;
2480                     continue;
2481                 }
2482
2483                 /* Failed.  Likely this is because the proposed new locale
2484                  * isn't valid on this system. */
2485
2486                 DEBUG_NEW_OBJECT_FAILED(category_names[i],
2487                                         new_locales[i],
2488                                         basis_obj);
2489
2490                 /* newlocale() didn't trash this, since the function call
2491                  * failed */
2492                 freelocale(basis_obj);
2493
2494                 for (unsigned int j = 0; j < LC_ALL_INDEX_; j++) {
2495                     Safefree(new_locales[j]);
2496                 }
2497
2498                 goto must_restore_state;
2499             }
2500
2501             /* Success for all categories. */
2502             for (unsigned int i = 0; i < LC_ALL_INDEX_; i++) {
2503                 update_PL_curlocales_i(i, new_locales[i], caller_line);
2504                 Safefree(new_locales[i]);
2505             }
2506
2507             /* We dup'd entry_obj in case we had to fall back to it.  The
2508              * newlocale() above destroyed the dup when it first succeeded, but
2509              * entry_obj itself is left dangling, so free it */
2510             if (! entry_obj_is_special) {
2511                 freelocale(entry_obj);
2512             }
2513         }
2514
2515 #  endif    /* End of newlocale can't handle disparate LC_ALL input */
2516
2517     }
2518
2519 #  undef DEBUG_NEW_OBJECT_CREATED
2520 #  undef DEBUG_NEW_OBJECT_FAILED
2521
2522     /* Here, successfully created an object representing the desired locale;
2523      * now switch into it */
2524     if (! uselocale(new_obj)) {
2525         freelocale(new_obj);
2526         locale_panic_(Perl_form(aTHX_ "(called from %" LINE_Tf "):"
2527                                       " bool_setlocale_2008_i: switching"
2528                                       " into new locale failed",
2529                                       caller_line));
2530     }
2531
2532     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2533                            "bool_setlocale_2008_i: now using %p\n", new_obj));
2534
2535 #  ifdef MULTIPLICITY   /* Unlikely, but POSIX 2008 functions could be
2536                            Configured to be used on unthreaded perls, in which
2537                            case this object doesn't exist */
2538
2539     if (DEBUG_Lv_TEST) {
2540         if (PL_cur_locale_obj != new_obj) {
2541             PerlIO_printf(Perl_debug_log,
2542                           "bool_setlocale_2008_i: PL_cur_locale_obj"
2543                           " was %p, now is %p\n",
2544                           PL_cur_locale_obj, new_obj);
2545         }
2546     }
2547
2548     /* Update the current object */
2549     PL_cur_locale_obj = new_obj;
2550
2551 #  endif
2552 #  ifdef HAS_GLIBC_LC_MESSAGES_BUG
2553
2554     /* Invalidate the glibc cache of loaded translations if the locale has
2555      * changed, see [perl #134264] and
2556      * https://sourceware.org/bugzilla/show_bug.cgi?id=24936 */
2557     if (old_messages_locale) {
2558         if (strNE(old_messages_locale, querylocale_c(LC_MESSAGES))) {
2559             textdomain(textdomain(NULL));
2560         }
2561     }
2562
2563 #  endif
2564
2565     return true;
2566
2567   must_restore_state:
2568
2569     /* We earlier switched to the LC_ALL => C locale in anticipation of it
2570      * succeeding,  Now have to switch back to the state upon entry.  */
2571     if (! uselocale(entry_obj)) {
2572         setlocale_failure_panic_i(index, "switching back to",
2573                                   locale_on_entry, __LINE__, caller_line);
2574     }
2575
2576     return false;
2577 }
2578
2579 /*---------------------------------------------------------------------------*/
2580
2581 #  define void_setlocale_i_with_caller(i, locale, file, line)               \
2582      STMT_START {                                                           \
2583         if (! bool_setlocale_i(i, locale))                                  \
2584             setlocale_failure_panic_via_i(i, NULL, locale, __LINE__, 0,     \
2585                                           file, line);                      \
2586      } STMT_END
2587
2588 #  define void_setlocale_r_with_caller(cat, locale, file, line)             \
2589         void_setlocale_i_with_caller(get_category_index(cat), locale,       \
2590                                      file, line)
2591
2592 #  define void_setlocale_c_with_caller(cat, locale, file, line)             \
2593             void_setlocale_i_with_caller(cat##_INDEX_, locale, file, line)
2594
2595 #  define void_setlocale_i(i, locale)                                       \
2596                 void_setlocale_i_with_caller(i, locale, __FILE__, __LINE__)
2597 #  define void_setlocale_c(cat, locale)                                     \
2598                                   void_setlocale_i(cat##_INDEX_, locale)
2599 #  define void_setlocale_r(cat, locale)                                     \
2600                   void_setlocale_i(get_category_index(cat), locale)
2601
2602 /*===========================================================================*/
2603
2604 #else
2605 #  error Unexpected Configuration
2606 #endif   /* End of the various implementations of the setlocale and
2607             querylocale macros used in the remainder of this program */
2608
2609 /* query_nominal_locale_i() is used when the caller needs the locale that an
2610  * external caller would be expecting, and not what we're secretly using
2611  * behind the scenes.  It deliberately doesn't handle LC_ALL; use
2612  * calculate_LC_ALL_string() for that. */
2613 #ifdef USE_LOCALE_NUMERIC
2614 #  define query_nominal_locale_i(i)                                         \
2615       (__ASSERT_(i != LC_ALL_INDEX_)                                        \
2616        ((i == LC_NUMERIC_INDEX_) ? PL_numeric_name : querylocale_i(i)))
2617 #else
2618 #  define query_nominal_locale_i(i)                                         \
2619       (__ASSERT_(i != LC_ALL_INDEX_) querylocale_i(i))
2620 #endif
2621
2622 #ifdef USE_PL_CURLOCALES
2623
2624 STATIC void
2625 S_update_PL_curlocales_i(pTHX_
2626                          const unsigned int index,
2627                          const char * new_locale,
2628                          const line_t caller_line)
2629 {
2630     /* Update PL_curlocales[], which is parallel to the other ones indexed by
2631      * our mapping of libc category number to our internal equivalents. */
2632
2633     PERL_ARGS_ASSERT_UPDATE_PL_CURLOCALES_I;
2634     assert(index <= LC_ALL_INDEX_);
2635
2636     if (index == LC_ALL_INDEX_) {
2637
2638         /* For LC_ALL, we change all individual categories to correspond,
2639          * including the LC_ALL element */
2640         for (unsigned int i = 0; i <= LC_ALL_INDEX_; i++) {
2641             Safefree(PL_curlocales[i]);
2642             PL_curlocales[i] = NULL;
2643         }
2644
2645         switch (parse_LC_ALL_string(new_locale,
2646                                     (const char **) &PL_curlocales,
2647                                     check_that_overridden,  /* things should
2648                                                                have already
2649                                                                been overridden
2650                                                                */
2651                                     true,   /* Always fill array */
2652                                     true,   /* Panic if fails, as to get here
2653                                                it earlier had to have succeeded
2654                                                */
2655                                    caller_line))
2656
2657         {
2658           case invalid:
2659           case no_array:
2660           case only_element_0:
2661             locale_panic_via_("Unexpected return from parse_LC_ALL_string",
2662                               __FILE__, caller_line);
2663
2664           case full_array:
2665             /* parse_LC_ALL_string() has already filled PL_curlocales properly,
2666              * except for the LC_ALL element, which should be set to
2667              * 'new_locale'. */
2668             PL_curlocales[LC_ALL_INDEX_] = savepv(new_locale);
2669         }
2670     }
2671     else {  /* Not LC_ALL */
2672
2673         /* Update the single category's record */
2674         Safefree(PL_curlocales[index]);
2675         PL_curlocales[index] = savepv(new_locale);
2676
2677         /* Invalidate LC_ALL */
2678         Safefree(PL_curlocales[LC_ALL_INDEX_]);
2679         PL_curlocales[LC_ALL_INDEX_] = NULL;
2680     }
2681 }
2682
2683 #  endif  /* Need PL_curlocales[] */
2684
2685 /*===========================================================================*/
2686
2687 #if defined(USE_LOCALE)
2688
2689 /* This paradigm is needed in several places in the function below.  We have to
2690  * substitute the nominal locale for LC_NUMERIC when returning a value for
2691  * external consumption */
2692 #  ifndef USE_LOCALE_NUMERIC
2693 #    define ENTRY(i, array, format)  array[i]
2694 #  else
2695 #    define ENTRY(i, array, format)                         \
2696        (UNLIKELY(   format == EXTERNAL_FORMAT_FOR_QUERY     \
2697                  && i == LC_NUMERIC_INDEX_)                 \
2698         ? PL_numeric_name                                   \
2699         : array[i])
2700 #  endif
2701
2702 STATIC
2703 const char *
2704 S_calculate_LC_ALL_string(pTHX_ const char ** category_locales_list,
2705                                 const calc_LC_ALL_format format,
2706                                 const calc_LC_ALL_return returning,
2707                                 const line_t caller_line)
2708 {
2709     PERL_ARGS_ASSERT_CALCULATE_LC_ALL_STRING;
2710
2711     /* NOTE: On Configurations that have PL_curlocales[], this function has the
2712      * side effect of updating the LC_ALL_INDEX_ element with its result.
2713      *
2714      * This function calculates a string that defines the locale(s) LC_ALL is
2715      * set to, in either:
2716      *  1)  Our internal format if 'format' is set to INTERNAL_FORMAT.
2717      *  2)  The external format returned by Perl_setlocale() if 'format' is set
2718      *      to EXTERNAL_FORMAT_FOR_QUERY or EXTERNAL_FORMAT_FOR_SET.
2719      *
2720      *      These two are distinguished by:
2721      *       a) EXTERNAL_FORMAT_FOR_SET returns the actual locale currently in
2722      *          effect.
2723      *       b) EXTERNAL_FORMAT_FOR_QUERY returns the nominal locale.
2724      *          Currently this can differ only from the actual locale in the
2725      *          LC_NUMERIC category when it is set to a locale whose radix is
2726      *          not a dot.  (The actual locale is kept as a dot to accommodate
2727      *          the large corpus of XS code that expects it to be that;
2728      *          switched to a non-dot temporarily during certain operations
2729      *          that require the actual radix.)
2730      *
2731      * In both 1) and 2), LC_ALL's values are passed to this function by
2732      * 'category_locales_list' which is either:
2733      *  1) a pointer to an array of strings with up-to-date values of all the
2734      *     individual categories; or
2735      *  2) NULL, to indicate to use querylocale_i() to get each individual
2736      *     value.
2737      *
2738      * The caller sets 'returning' to
2739      *      WANT_TEMP_PV        the function returns the calculated string
2740      *                              as a mmortalized temporary, so the caller
2741      *                              doesn't have to worry about it being
2742      *                              per-thread, nor needs to arrange for its
2743      *                              clean-up.
2744      *      WANT_VOID               NULL is returned.  This is used when the
2745      *                              function is being called only for its side
2746      *                              effect of updating
2747      *                              PL_curlocales[LC_ALL_INDEX_]
2748      *
2749      * querylocale(), on systems that have it, doesn't tend to work for LC_ALL.
2750      * So we have to construct the answer ourselves based on the passed in
2751      * data.
2752      *
2753      * If all individual categories are the same locale, we can just set LC_ALL
2754      * to that locale.  But if not, we have to create an aggregation of all the
2755      * categories on the system.  Platforms differ as to the syntax they use
2756      * for these non-uniform locales for LC_ALL.  Some, like glibc and Windows,
2757      * use an unordered series of name=value pairs, like
2758      *      LC_NUMERIC=C;LC_TIME=en_US.UTF-8;...
2759      * to specify LC_ALL; others, like *BSD, use a positional notation with a
2760      * delimitter, typically a single '/' character:
2761      *      C/en_UK.UTF-8/...
2762      *
2763      * When the external format is desired, this function returns whatever the
2764      * system expects.  The internal format is always name=value pairs.
2765      *
2766      * For systems that have categories we don't know about, the algorithm
2767      * below won't know about those missing categories, leading to potential
2768      * bugs for code that looks at them.  If there is an environment variable
2769      * that sets that category, we won't know to look for it, and so our use of
2770      * LANG or "C" improperly overrides it.  On the other hand, if we don't do
2771      * what is done here, and there is no environment variable, the category's
2772      * locale should be set to LANG or "C".  So there is no good solution.  khw
2773      * thinks the best is to make sure we have a complete list of possible
2774      * categories, adding new ones as they show up on obscure platforms.
2775      */
2776
2777     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2778                            "Entering calculate_LC_ALL_string(%s);"
2779                            " called from %" LINE_Tf "\n",
2780                            ((format == EXTERNAL_FORMAT_FOR_QUERY)
2781                             ? "EXTERNAL_FORMAT_FOR_QUERY"
2782                             : ((format == EXTERNAL_FORMAT_FOR_SET)
2783                                ? "EXTERNAL_FORMAT_FOR_SET"
2784                                : "INTERNAL_FORMAT")),
2785                            caller_line));
2786
2787     bool input_list_was_NULL = (category_locales_list == NULL);
2788
2789     /* If there was no input category list, construct a temporary one
2790      * ourselves. */
2791     const char * my_category_locales_list[LC_ALL_INDEX_];
2792     const char ** locales_list = category_locales_list;
2793     if (locales_list == NULL) {
2794         locales_list = my_category_locales_list;
2795
2796         if (format == EXTERNAL_FORMAT_FOR_QUERY) {
2797             for (unsigned i = 0; i < LC_ALL_INDEX_; i++) {
2798                 locales_list[i] = query_nominal_locale_i(i);
2799             }
2800         }
2801         else {
2802             for (unsigned i = 0; i < LC_ALL_INDEX_; i++) {
2803                 locales_list[i] = querylocale_i(i);
2804             }
2805         }
2806     }
2807
2808     /* While we are calculating LC_ALL, we see if every category's locale is
2809      * the same as every other's or not. */
2810 #  ifndef HAS_IGNORED_LOCALE_CATEGORIES_
2811
2812     /* When we pay attention to all categories, we assume they are all the same
2813      * until proven different */
2814     bool disparate = false;
2815
2816 #  else
2817
2818     /* But if there are ignored categories, those will be set to "C", so try an
2819      * arbitrary category, and if it isn't C, we know immediately that the
2820      * locales are disparate.  (The #if conditionals are to handle the case
2821      * where LC_NUMERIC_INDEX_ is 0.  We don't want to use LC_NUMERIC to
2822      * compare, as that may be different between external and internal forms.)
2823      * */
2824 #    if ! defined(USE_LOCALE_NUMERIC)
2825
2826     bool disparate = ! isNAME_C_OR_POSIX(locales_list[0]);
2827
2828 #    elif LC_NUMERIC_INDEX_ != 0
2829
2830     bool disparate = ! isNAME_C_OR_POSIX(locales_list[0]);
2831
2832 #    else
2833
2834     /* Would need revision to handle the very unlikely case where only a single
2835      * category, LC_NUMERIC, is defined */
2836     assert(LOCALE_CATEGORIES_COUNT_ > 0);
2837
2838     bool disparate = ! isNAME_C_OR_POSIX(locales_list[1]);
2839
2840 #    endif
2841 #  endif
2842
2843     /* Calculate the needed size for the string listing the individual locales.
2844      * Initialize with values known at compile time. */
2845     Size_t total_len;
2846     const char *separator;
2847
2848 #  ifdef PERL_LC_ALL_USES_NAME_VALUE_PAIRS  /* Positional formatted LC_ALL */
2849     PERL_UNUSED_ARG(format);
2850 #  else
2851
2852     if (format != INTERNAL_FORMAT) {
2853
2854         /* Here, we will be using positional notation.  it includes n-1
2855          * separators */
2856         total_len = (  LOCALE_CATEGORIES_COUNT_ - 1)
2857                      * STRLENs(PERL_LC_ALL_SEPARATOR)
2858                   + 1;   /* And a trailing NUL */
2859         separator = PERL_LC_ALL_SEPARATOR;
2860     }
2861     else
2862
2863 #  endif
2864
2865     {
2866         /* name=value output is always used in internal format, and when
2867          * positional isn't available on the platform. */
2868         total_len = lc_all_boiler_plate_length;
2869         separator = ";";
2870     }
2871
2872     /* The total length then is just the sum of the above boiler-plate plus the
2873      * total strlen()s of the locale name of each individual category. */
2874     for (unsigned int i = 0;  i < LC_ALL_INDEX_; i++) {
2875         const char * entry = ENTRY(i, locales_list, format);
2876
2877         total_len += strlen(entry);
2878         if (! disparate && strNE(entry, locales_list[0])) {
2879             disparate = true;
2880         }
2881     }
2882
2883     bool free_if_void_return = false;
2884
2885     /* Done iterating through all the categories. */
2886     const char * retval;
2887
2888     /* If all categories have the same locale, we already know the answer */
2889     if (! disparate) {
2890             retval = locales_list[0];
2891
2892             /* If a temporary is wanted for the return, and we had to create
2893              * the input list ourselves, we created it into such a temporary,
2894              * so no further work is needed; but otherwise, make a mortal copy
2895              * of this passed-in list element */
2896             if (returning == WANT_TEMP_PV && ! input_list_was_NULL) {
2897                 retval = savepv(retval);
2898                 SAVEFREEPV(retval);
2899             }
2900
2901         /* In all cases here, there's nothing we create that needs to be freed,
2902          * so leave 'free_if_void_return' set to the default 'false'. */
2903     }
2904     else {  /* Here, not all categories have the same locale */
2905
2906             char * constructed;
2907             Newx(constructed, total_len, char);
2908
2909             /* If returning the new memory, it must be set up to be freed
2910              * later; otherwise at the end of this function */
2911             if (returning == WANT_TEMP_PV) {
2912                 SAVEFREEPV(constructed);
2913             }
2914             else {
2915                 free_if_void_return = true;
2916             }
2917
2918         constructed[0] = '\0';
2919
2920         /* Loop through all the categories */
2921         for (unsigned j = 0; j < LC_ALL_INDEX_; j++) {
2922
2923             /* Add a separator, except before the first one */
2924             if (j != 0) {
2925                 my_strlcat(constructed, separator, total_len);
2926             }
2927
2928             const char * entry;
2929             Size_t needed_len;
2930             unsigned int i = j;
2931
2932 #  ifndef PERL_LC_ALL_USES_NAME_VALUE_PAIRS
2933
2934             if (UNLIKELY(format != INTERNAL_FORMAT)) {
2935
2936                 /* In positional notation 'j' means the position, and we have
2937                  * to convert to the index 'i' */
2938                 i = map_LC_ALL_position_to_index[j];
2939
2940                 entry = ENTRY(i, locales_list, format);
2941                 needed_len = my_strlcat(constructed, entry, total_len);
2942             }
2943             else
2944
2945 #  endif
2946             {
2947                 /* Below, we are to use name=value notation, either because
2948                  * that's what the platform uses, or because this is the
2949                  * internal format, which uses that notation regardless of the
2950                  * external form */
2951
2952                 entry = ENTRY(i, locales_list, format);
2953
2954                 /* "name=locale;" */
2955                 my_strlcat(constructed, category_names[i], total_len);
2956                 my_strlcat(constructed, "=", total_len);
2957                 needed_len = my_strlcat(constructed, entry, total_len);
2958             }
2959
2960             if (LIKELY(needed_len <= total_len)) {
2961                 continue;
2962             }
2963
2964             /* If would have overflowed, panic */
2965             locale_panic_via_(Perl_form(aTHX_
2966                                         "Internal length calculation wrong.\n"
2967                                         "\"%s\" was not entirely added to"
2968                                         " \"%.*s\"; needed=%zu, had=%zu",
2969                                         entry, (int) total_len,
2970                                         constructed,
2971                                         needed_len, total_len),
2972                                 __FILE__,
2973                                 caller_line);
2974         } /* End of loop through the categories */
2975
2976         retval = constructed;
2977     } /* End of the categories' locales are displarate */
2978
2979 #  if defined(USE_PL_CURLOCALES) && defined(LC_ALL)
2980
2981     if (format == INTERNAL_FORMAT) {
2982
2983         /* PL_curlocales[LC_ALL_INDEX_] is updated as a side-effect of this
2984          * function for internal format. */
2985         Safefree(PL_curlocales[LC_ALL_INDEX_]);
2986         PL_curlocales[LC_ALL_INDEX_] = savepv(retval);
2987     }
2988
2989 #  endif
2990
2991     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2992                            "calculate_LC_ALL_string calculated '%s'\n",
2993                            retval));
2994
2995     if (returning == WANT_VOID) {
2996         if (free_if_void_return) {
2997             Safefree(retval);
2998         }
2999
3000         return NULL;
3001     }
3002
3003     return retval;
3004 }
3005
3006 #  if defined(WIN32) || (     defined(USE_POSIX_2008_LOCALE)        \
3007                          && ! defined(USE_QUERYLOCALE))
3008
3009 STATIC const char *
3010 S_find_locale_from_environment(pTHX_ const unsigned int index)
3011 {
3012     /* NB: This function may actually change the locale on Windows.  It
3013      * currently is designed to be called only from setting the locale on
3014      * Windows, and POSIX 2008
3015      *
3016      * This function returns the locale specified by the program's environment
3017      * for the category specified by our internal index number 'index'.  It
3018      * therefore simulates:
3019      *      setlocale(cat, "")
3020      * but, except for some cases in Windows, doesn't actually change the
3021      * locale; merely returns it.
3022      *
3023      * The return need not be freed by the caller.  This
3024      * promise relies on PerlEnv_getenv() returning a mortalized copy to us.
3025      *
3026      * The simulation is needed only on certain platforms; otherwise, libc is
3027      * called with "" to get the actual value(s).  The simulation is needed
3028      * for:
3029      *
3030      *  1)  On Windows systems, the concept of the POSIX ordering of
3031      *      environment variables is missing.  To increase portability of
3032      *      programs across platforms, the POSIX ordering is emulated on
3033      *      Windows.
3034      *
3035      *  2)  On POSIX 2008 systems without querylocale(), it is problematic
3036      *      getting the results of the POSIX 2008 equivalent of
3037      *
3038      *          setlocale(category, "")
3039      *
3040      *      To ensure that we know exactly what those values are, we do the
3041      *      setting ourselves, using the documented algorithm specified by the
3042      *      POSIX standard (assuming the platform follows the Standard) rather
3043      *      than use "" as the locale.  This will lead to results that differ
3044      *      from native behavior if the native behavior differs from the
3045      *      Standard's documented value, but khw believes it is better to know
3046      *      what's going on, even if different from native, than to just guess.
3047      *
3048      *      glibc systems differ from this standard in having a LANGUAGE
3049      *      environment variable used for just LC_MESSAGES.  This function does
3050      *      NOT handle that.
3051      *
3052      *      Another option for the POSIX 2008 case would be, in a critical
3053      *      section, to save the global locale's current value, and do a
3054      *      straight setlocale(LC_ALL, "").  That would return our desired
3055      *      values, destroying the global locale's, which we would then
3056      *      restore.  But that could cause races with any other thread that is
3057      *      using the global locale and isn't using the mutex.  And, the only
3058      *      reason someone would have done that is because they are calling a
3059      *      library function, like in gtk, that calls setlocale(), and which
3060      *      can't be changed to use the mutex.  That wouldn't be a problem if
3061      *      this were to be done before any threads had switched, say during
3062      *      perl construction time.  But this code would still be needed for
3063      *      the general case.
3064      *
3065      * The Windows and POSIX 2008 differ in that the ultimate fallback is "C"
3066      * in POSIX, and is the system default locale in Windows.  To get that
3067      * system default value, we actually have to call setlocale() on Windows.
3068      */
3069
3070     const char * const lc_all = PerlEnv_getenv("LC_ALL");
3071     const char * locale_names[LC_ALL_INDEX_] = { NULL };
3072
3073     /* Use any "LC_ALL" environment variable, as it overrides everything else.
3074      * */
3075     if (lc_all && strNE(lc_all, "")) {
3076         return lc_all;
3077     }
3078
3079     /* Here, no usable LC_ALL environment variable.  We have to handle each
3080      * category separately.  If all categories are desired, we loop through
3081      * them all.  If only an individual category is desired, to avoid
3082      * duplicating logic, we use the same loop, but set up the limits so it is
3083      * only executed once, for that particular category. */
3084     unsigned int lower, upper, offset;
3085     if (index == LC_ALL_INDEX_) {
3086         lower = 0;
3087         upper = LC_ALL_INDEX_ - 1;
3088         offset = 0;
3089     }
3090     else {
3091         lower = index;
3092         upper = index;
3093
3094         /* 'offset' is used so that the result of the single loop iteration is
3095          * stored into output[0] */
3096         offset = lower;
3097     }
3098
3099     /* When no LC_ALL environment variable, LANG is used as a default, but
3100      * overridden for individual categories that have corresponding environment
3101      * variables.  If no LANG exists, the default is "C" on POSIX 2008, or the
3102      * system default for the category on Windows. */
3103     const char * env_lang = NULL;
3104
3105     /* For each desired category, use any corresponding environment variable;
3106      * or the default if none such exists. */
3107     bool is_disparate = false;  /* Assume is uniform until proven otherwise */
3108     for (unsigned i = lower; i <= upper; i++) {
3109         const char * const env_override = PerlEnv_getenv(category_names[i]);
3110         unsigned int j = i - offset;
3111
3112         if (env_override && strNE(env_override, "")) {
3113             locale_names[j] = env_override;
3114         }
3115         else { /* Here, no corresponding environment variable, see if LANG
3116                   exists and is usable.  Done this way to avoid fetching LANG
3117                   unless it is actually needed */
3118             if (env_lang == NULL) {
3119                 env_lang = PerlEnv_getenv("LANG");
3120
3121                 /* If not usable, set it to a non-NULL illegal value so won't
3122                  * try to use it below */
3123                 if (env_lang == NULL || strEQ(env_lang, "")) {
3124                     env_lang = (const char *) 1;
3125                 }
3126             }
3127
3128             /* If a usable LANG exists, use it. */
3129             if (env_lang != NULL && env_lang != (const char *) 1) {
3130                 locale_names[j] = env_lang;
3131             }
3132             else {
3133
3134 #    ifdef WIN32
3135                 /* If no LANG, use the system default on Windows. */
3136                 locale_names[j] = wrap_wsetlocale(categories[i], ".ACP");
3137                 if (locale_names[j]) {
3138                     SAVEFREEPV(locale_names[j]);
3139                 }
3140                 else
3141 #    endif
3142                 {   /* If nothing was found or worked, use C */
3143                     locale_names[j] = "C";
3144                 }
3145             }
3146         }
3147
3148         if (j > 0 && ! is_disparate && strNE(locale_names[0], locale_names[j]))
3149         {
3150             is_disparate = true;
3151         }
3152
3153         DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3154                  "find_locale_from_environment i=%u, j=%u, name=%s,"
3155                  " locale=%s, locale of 0th category=%s, disparate=%d\n",
3156                  i, j, category_names[i],
3157                  locale_names[j], locale_names[0], is_disparate));
3158     }
3159
3160     if (! is_disparate) {
3161         return locale_names[0];
3162     }
3163
3164     return calculate_LC_ALL_string(locale_names, INTERNAL_FORMAT,
3165                                    WANT_TEMP_PV,
3166                                    __LINE__);
3167 }
3168
3169 #  endif
3170 #  if defined(DEBUGGING) || defined(USE_PERL_SWITCH_LOCALE_CONTEXT)
3171
3172 STATIC const char *
3173 S_get_LC_ALL_display(pTHX)
3174 {
3175     return calculate_LC_ALL_string(NULL, INTERNAL_FORMAT,
3176                                    WANT_TEMP_PV,
3177                                    __LINE__);
3178 }
3179
3180 #  endif
3181
3182 STATIC void
3183 S_setlocale_failure_panic_via_i(pTHX_
3184                                 const unsigned int cat_index,
3185                                 const char * current,
3186                                 const char * failed,
3187                                 const line_t proxy_caller_line,
3188                                 const line_t immediate_caller_line,
3189                                 const char * const higher_caller_file,
3190                                 const line_t higher_caller_line)
3191 {
3192     PERL_ARGS_ASSERT_SETLOCALE_FAILURE_PANIC_VIA_I;
3193
3194     /* Called to panic when a setlocale form unexpectedly failed for the
3195      * category determined by 'cat_index', and the locale that was in effect
3196      * (and likely still is) is 'current'.  'current' may be NULL, which causes
3197      * this function to query what it is.
3198      *
3199      * The extra caller information is used for when a function acts as a
3200      * stand-in for another function, which a typical reader would more likely
3201      * think would be the caller
3202      *
3203      * If a line number is 0, its stack (sort-of) frame is omitted; same if
3204      * it's the same line number as the next higher caller. */
3205
3206     const int cat = categories[cat_index];
3207     const char * name = category_names[cat_index];
3208
3209     dSAVE_ERRNO;
3210
3211     if (current == NULL) {
3212         current = querylocale_i(cat_index);
3213     }
3214
3215     const char * proxy_text = "";
3216     if (proxy_caller_line != 0 && proxy_caller_line != immediate_caller_line)
3217     {
3218         proxy_text = Perl_form(aTHX_ "\nCalled via %s: %" LINE_Tf,
3219                                       __FILE__, proxy_caller_line);
3220     }
3221     if (   strNE(__FILE__, higher_caller_file)
3222         || (   immediate_caller_line != 0
3223             && immediate_caller_line != higher_caller_line))
3224     {
3225         proxy_text = Perl_form(aTHX_ "%s\nCalled via %s: %" LINE_Tf,
3226                                       proxy_text, __FILE__,
3227                                       immediate_caller_line);
3228     }
3229
3230     /* 'false' in the get_displayable_string() calls makes it not think the
3231      * locale is UTF-8, so just dumps bytes.  Actually figuring it out can be
3232      * too complicated for a panic situation. */
3233     const char * msg = Perl_form(aTHX_
3234                             "Can't change locale for %s (%d) from '%s' to '%s'"
3235                             " %s",
3236                             name, cat,
3237                             get_displayable_string(current,
3238                                                    current + strlen(current),
3239                                                    false),
3240                             get_displayable_string(failed,
3241                                                    failed + strlen(failed),
3242                                                    false),
3243                             proxy_text);
3244     RESTORE_ERRNO;
3245
3246     Perl_locale_panic(msg, __LINE__, higher_caller_file, higher_caller_line);
3247     NOT_REACHED; /* NOTREACHED */
3248 }
3249
3250 /* Any of these will allow us to find the RADIX */
3251 #  if defined(USE_LOCALE_NUMERIC) && (   defined(HAS_SOME_LANGINFO)         \
3252                                       || defined(HAS_LOCALECONV)            \
3253                                       || defined(HAS_SNPRINTF))
3254 #    define CAN_CALCULATE_RADIX
3255 #  endif
3256 #  ifdef USE_LOCALE_NUMERIC
3257
3258 STATIC void
3259 S_new_numeric(pTHX_ const char *newnum, bool force)
3260 {
3261     PERL_ARGS_ASSERT_NEW_NUMERIC;
3262
3263     /* Called after each libc setlocale() or uselocale() call affecting
3264      * LC_NUMERIC, to tell core Perl this and that 'newnum' is the name of the
3265      * new locale, and we are switched into it.  It installs this locale as the
3266      * current underlying default, and then switches to the C locale, if
3267      * necessary, so that the code that has traditionally expected the radix
3268      * character to be a dot may continue to do so.
3269      *
3270      * The default locale and the C locale can be toggled between by use of the
3271      * set_numeric_underlying() and set_numeric_standard() functions, which
3272      * should probably not be called directly, but only via macros like
3273      * SET_NUMERIC_STANDARD() in perl.h.
3274      *
3275      * The toggling is necessary mainly so that a non-dot radix decimal point
3276      * character can be input and output, while allowing internal calculations
3277      * to use a dot.
3278      *
3279      * This sets several interpreter-level variables:
3280      * PL_numeric_name  The underlying locale's name: a copy of 'newnum'
3281      * PL_numeric_underlying   A boolean indicating if the toggled state is
3282      *                  such that the current locale is the program's
3283      *                  underlying locale
3284      * PL_numeric_standard   An int indicating if the toggled state is such
3285      *                  that the current locale is the C locale or
3286      *                  indistinguishable from the C locale.  If non-zero, it
3287      *                  is in C; if > 1, it means it may not be toggled away
3288      *                  from C.
3289      * PL_numeric_underlying_is_standard   A bool kept by this function
3290      *                  indicating that the underlying locale and the standard
3291      *                  C locale are indistinguishable for the purposes of
3292      *                  LC_NUMERIC.  This happens when both of the above two
3293      *                  variables are true at the same time.  (Toggling is a
3294      *                  no-op under these circumstances.)  This variable is
3295      *                  used to avoid having to recalculate.
3296      * PL_numeric_radix_sv   Contains the string that code should use for the
3297      *                  decimal point.  It is set to either a dot or the
3298      *                  program's underlying locale's radix character string,
3299      *                  depending on the situation.
3300      * PL_underlying_radix_sv   Contains the program's underlying locale's
3301      *                  radix character string.  This is copied into
3302      *                  PL_numeric_radix_sv when the situation warrants.  It
3303      *                  exists to avoid having to recalculate it when toggling.
3304      * PL_underlying_numeric_obj = (only on POSIX 2008 platforms)  An object
3305      *                  with everything set up properly so as to avoid work on
3306      *                  such platforms.
3307      */
3308
3309     DEBUG_L( PerlIO_printf(Perl_debug_log,
3310                            "Called new_numeric with %s, PL_numeric_name=%s\n",
3311                            newnum, PL_numeric_name));
3312
3313     /* If not forcing this procedure, and there isn't actually a change from
3314      * our records, do nothing.  (Our records can be wrong when sync'ing to the
3315      * locale set up by an external library, hence the 'force' parameter) */
3316     if (! force && strEQ(PL_numeric_name, newnum)) {
3317         return;
3318     }
3319
3320     Safefree(PL_numeric_name);
3321     PL_numeric_name = savepv(newnum);
3322
3323     /* Handle the trivial case.  Since this is called at process
3324      * initialization, be aware that this bit can't rely on much being
3325      * available. */
3326     if (isNAME_C_OR_POSIX(PL_numeric_name)) {
3327         PL_numeric_standard = TRUE;
3328         PL_numeric_underlying_is_standard = TRUE;
3329         PL_numeric_underlying = TRUE;
3330         sv_setpv(PL_numeric_radix_sv, C_decimal_point);
3331         SvUTF8_off(PL_numeric_radix_sv);
3332         sv_setpv(PL_underlying_radix_sv, C_decimal_point);
3333         SvUTF8_off(PL_underlying_radix_sv);
3334         return;
3335     }
3336
3337     /* We are in the underlying locale until changed at the end of this
3338      * function */
3339     PL_numeric_underlying = TRUE;
3340
3341 #    ifdef USE_POSIX_2008_LOCALE
3342
3343     /* We keep a special object for easy switching to.
3344      *
3345      * NOTE: This code may incorrectly show up as a leak under the address
3346      * sanitizer. We do not free this object under normal teardown, however
3347      * you can set PERL_DESTRUCT_LEVEL=2 to cause it to be freed.
3348      */
3349     PL_underlying_numeric_obj = newlocale(LC_NUMERIC_MASK,
3350                                           PL_numeric_name,
3351                                           PL_underlying_numeric_obj);
3352
3353 #      endif
3354
3355     char * radix = NULL;
3356     utf8ness_t utf8ness = UTF8NESS_IMMATERIAL;
3357
3358     /* Find and save this locale's radix character. */
3359     my_langinfo_c(RADIXCHAR, LC_NUMERIC, PL_numeric_name,
3360                   &radix, NULL, &utf8ness);
3361     sv_setpv(PL_underlying_radix_sv, radix);
3362
3363     if (utf8ness == UTF8NESS_YES) {
3364         SvUTF8_on(PL_underlying_radix_sv);
3365     }
3366     else {
3367         SvUTF8_off(PL_underlying_radix_sv);
3368     }
3369
3370     DEBUG_L(PerlIO_printf(Perl_debug_log,
3371                           "Locale radix is '%s', ?UTF-8=%d\n",
3372                           SvPVX(PL_underlying_radix_sv),
3373                           cBOOL(SvUTF8(PL_underlying_radix_sv))));
3374
3375     /* This locale is indistinguishable from C (for numeric purposes) if both
3376      * the radix character and the thousands separator are the same as C's.
3377      * Start with the radix. */
3378     PL_numeric_underlying_is_standard = strEQ(C_decimal_point, radix);
3379     Safefree(radix);
3380
3381 #    ifndef TS_W32_BROKEN_LOCALECONV
3382
3383     /* If the radix isn't the same as C's, we know it is distinguishable from
3384      * C; otherwise check the thousands separator too.  Only if both are the
3385      * same as C's is the locale indistinguishable from C.
3386      *
3387      * But on earlier Windows versions, there is a potential race.  This code
3388      * knows that localeconv() (elsewhere in this file) will be used to extract
3389      * the needed value, and localeconv() was buggy for quite a while, and that
3390      * code in this file hence uses a workaround.  And that workaround may have
3391      * an (unlikely) race.  Gathering the radix uses a different workaround on
3392      * Windows that doesn't involve a race.  It might be possible to do the
3393      * same for this (patches welcome).
3394      *
3395      * Until then khw doesn't think it's worth even the small risk of a race to
3396      * get this value, which doesn't appear to be used in any of the Microsoft
3397      * library routines anyway. */
3398
3399     char * scratch_buffer = NULL;
3400     if (PL_numeric_underlying_is_standard) {
3401         PL_numeric_underlying_is_standard = strEQ(C_thousands_sep,
3402                                              my_langinfo_c(THOUSEP, LC_NUMERIC,
3403                                                            PL_numeric_name,
3404                                                            &scratch_buffer,
3405                                                            NULL, NULL));
3406     }
3407     Safefree(scratch_buffer);
3408
3409 #    endif
3410
3411     PL_numeric_standard = PL_numeric_underlying_is_standard;
3412
3413     /* Keep LC_NUMERIC so that it has the C locale radix and thousands
3414      * separator.  This is for XS modules, so they don't have to worry about
3415      * the radix being a non-dot.  (Core operations that need the underlying
3416      * locale change to it temporarily). */
3417     if (! PL_numeric_standard) {
3418         set_numeric_standard(__FILE__, __LINE__);
3419     }
3420 }
3421
3422 #  endif
3423
3424 void
3425 Perl_set_numeric_standard(pTHX_ const char * const file, const line_t line)
3426 {
3427     PERL_ARGS_ASSERT_SET_NUMERIC_STANDARD;
3428     PERL_UNUSED_ARG(file);      /* Some Configurations ignore these */
3429     PERL_UNUSED_ARG(line);
3430
3431 #  ifdef USE_LOCALE_NUMERIC
3432
3433     /* Unconditionally toggle the LC_NUMERIC locale to the C locale
3434      *
3435      * Most code should use the macro SET_NUMERIC_STANDARD() in perl.h
3436      * instead of calling this directly.  The macro avoids calling this routine
3437      * if toggling isn't necessary according to our records (which could be
3438      * wrong if some XS code has changed the locale behind our back) */
3439
3440     DEBUG_L(PerlIO_printf(Perl_debug_log, "Setting LC_NUMERIC locale to"
3441                                           " standard C; called from %s: %"
3442                                           LINE_Tf "\n", file, line));
3443
3444     void_setlocale_c_with_caller(LC_NUMERIC, "C", file, line);
3445     PL_numeric_standard = TRUE;
3446     sv_setpv(PL_numeric_radix_sv, C_decimal_point);
3447     SvUTF8_off(PL_numeric_radix_sv);
3448
3449     PL_numeric_underlying = PL_numeric_underlying_is_standard;
3450
3451 #  endif /* USE_LOCALE_NUMERIC */
3452
3453 }
3454
3455 void
3456 Perl_set_numeric_underlying(pTHX_ const char * const file, const line_t line)
3457 {
3458     PERL_ARGS_ASSERT_SET_NUMERIC_UNDERLYING;
3459     PERL_UNUSED_ARG(file);      /* Some Configurations ignore these */
3460     PERL_UNUSED_ARG(line);
3461
3462 #  ifdef USE_LOCALE_NUMERIC
3463
3464     /* Unconditionally toggle the LC_NUMERIC locale to the current underlying
3465      * default.
3466      *
3467      * Most code should use the macro SET_NUMERIC_UNDERLYING() in perl.h
3468      * instead of calling this directly.  The macro avoids calling this routine
3469      * if toggling isn't necessary according to our records (which could be
3470      * wrong if some XS code has changed the locale behind our back) */
3471
3472     DEBUG_L(PerlIO_printf(Perl_debug_log, "Setting LC_NUMERIC locale to %s;"
3473                                           " called from %s: %" LINE_Tf "\n",
3474                                           PL_numeric_name, file, line));
3475     /* Maybe not in init? assert(PL_locale_mutex_depth > 0);*/
3476
3477     void_setlocale_c_with_caller(LC_NUMERIC, PL_numeric_name, file, line);
3478     PL_numeric_underlying = TRUE;
3479     sv_setsv_nomg(PL_numeric_radix_sv, PL_underlying_radix_sv);
3480
3481     PL_numeric_standard = PL_numeric_underlying_is_standard;
3482
3483 #  endif /* USE_LOCALE_NUMERIC */
3484
3485 }
3486
3487 #  ifdef USE_LOCALE_CTYPE
3488
3489 STATIC void
3490 S_new_ctype(pTHX_ const char *newctype, bool force)
3491 {
3492     PERL_ARGS_ASSERT_NEW_CTYPE;
3493     PERL_UNUSED_ARG(force);
3494
3495     /* Called after each libc setlocale() call affecting LC_CTYPE, to tell
3496      * core Perl this and that 'newctype' is the name of the new locale.
3497      *
3498      * This function sets up the folding arrays for all 256 bytes, assuming
3499      * that tofold() is tolc() since fold case is not a concept in POSIX,
3500      */
3501
3502     DEBUG_L(PerlIO_printf(Perl_debug_log, "Entering new_ctype(%s)\n",
3503                                           newctype));
3504
3505     /* No change means no-op */
3506     if (strEQ(PL_ctype_name, newctype)) {
3507         return;
3508     }
3509
3510     /* We will replace any bad locale warning with
3511      *  1)  nothing if the new one is ok; or
3512      *  2)  a new warning for the bad new locale */
3513     if (PL_warn_locale) {
3514         SvREFCNT_dec_NN(PL_warn_locale);
3515         PL_warn_locale = NULL;
3516     }
3517
3518     /* Clear cache */
3519     Safefree(PL_ctype_name);
3520     PL_ctype_name = "";
3521
3522     PL_in_utf8_turkic_locale = FALSE;
3523
3524     /* For the C locale, just use the standard folds, and we know there are no
3525      * glitches possible, so return early.  Since this is called at process
3526      * initialization, be aware that this bit can't rely on much being
3527      * available. */
3528     if (isNAME_C_OR_POSIX(newctype)) {
3529         Copy(PL_fold, PL_fold_locale, 256, U8);
3530         PL_ctype_name = savepv(newctype);
3531         PL_in_utf8_CTYPE_locale = FALSE;
3532         return;
3533     }
3534
3535     /* The cache being cleared signals the called function to compute a new
3536      * value */
3537     PL_in_utf8_CTYPE_locale = is_locale_utf8(newctype);
3538
3539     PL_ctype_name = savepv(newctype);
3540     bool maybe_utf8_turkic = FALSE;
3541
3542     /* Don't check for problems if we are suppressing the warnings */
3543     bool check_for_problems = ckWARN_d(WARN_LOCALE) || UNLIKELY(DEBUG_L_TEST);
3544
3545     if (PL_in_utf8_CTYPE_locale) {
3546
3547         /* A UTF-8 locale gets standard rules.  But note that code still has to
3548          * handle this specially because of the three problematic code points
3549          * */
3550         Copy(PL_fold_latin1, PL_fold_locale, 256, U8);
3551
3552         /* UTF-8 locales can have special handling for 'I' and 'i' if they are
3553          * Turkic.  Make sure these two are the only anomalies.  (We don't
3554          * require towupper and towlower because they aren't in C89.) */
3555
3556 #    if defined(HAS_TOWUPPER) && defined (HAS_TOWLOWER)
3557
3558         if (towupper('i') == 0x130 && towlower('I') == 0x131)
3559
3560 #    else
3561
3562         if (toU8_UPPER_LC('i') == 'i' && toU8_LOWER_LC('I') == 'I')
3563
3564 #    endif
3565
3566         {
3567             /* This is how we determine it really is Turkic */
3568             check_for_problems = TRUE;
3569             maybe_utf8_turkic = TRUE;
3570         }
3571     }
3572     else {  /* Not a canned locale we know the values for.  Compute them */
3573
3574 #    ifdef DEBUGGING
3575
3576         bool has_non_ascii_fold = FALSE;
3577         bool found_unexpected = FALSE;
3578
3579         /* Under -DLv, see if there are any folds outside the ASCII range.
3580          * This factoid is used below */
3581         if (DEBUG_Lv_TEST) {
3582             for (unsigned i = 128; i < 256; i++) {
3583                 int j = LATIN1_TO_NATIVE(i);
3584                 if (toU8_LOWER_LC(j) != j || toU8_UPPER_LC(j) != j) {
3585                     has_non_ascii_fold = TRUE;
3586                     break;
3587                 }
3588             }
3589         }
3590
3591 #    endif
3592
3593         for (unsigned i = 0; i < 256; i++) {
3594             if (isU8_UPPER_LC(i))
3595                 PL_fold_locale[i] = (U8) toU8_LOWER_LC(i);
3596             else if (isU8_LOWER_LC(i))
3597                 PL_fold_locale[i] = (U8) toU8_UPPER_LC(i);
3598             else
3599                 PL_fold_locale[i] = (U8) i;
3600
3601 #    ifdef DEBUGGING
3602
3603             /* Most locales these days are supersets of ASCII.  When debugging
3604              * with -DLv, it is helpful to know what the exceptions to that are
3605              * in this locale */
3606             if (DEBUG_Lv_TEST) {
3607                 bool unexpected = FALSE;
3608
3609                 if (isUPPER_L1(i)) {
3610                     if (isUPPER_A(i)) {
3611                         if (PL_fold_locale[i] != toLOWER_A(i)) {
3612                             unexpected = TRUE;
3613                         }
3614                     }
3615                     else if (has_non_ascii_fold) {
3616                         if (PL_fold_locale[i] != toLOWER_L1(i)) {
3617                             unexpected = TRUE;
3618                         }
3619                     }
3620                     else if (PL_fold_locale[i] != i) {
3621                         unexpected = TRUE;
3622                     }
3623                 }
3624                 else if (   isLOWER_L1(i)
3625                          && i != LATIN_SMALL_LETTER_SHARP_S
3626                          && i != MICRO_SIGN)
3627                 {
3628                     if (isLOWER_A(i)) {
3629                         if (PL_fold_locale[i] != toUPPER_A(i)) {
3630                             unexpected = TRUE;
3631                         }
3632                     }
3633                     else if (has_non_ascii_fold) {
3634                         if (PL_fold_locale[i] != toUPPER_LATIN1_MOD(i)) {
3635                             unexpected = TRUE;
3636                         }
3637                     }
3638                     else if (PL_fold_locale[i] != i) {
3639                         unexpected = TRUE;
3640                     }
3641                 }
3642                 else if (PL_fold_locale[i] != i) {
3643                     unexpected = TRUE;
3644                 }
3645
3646                 if (unexpected) {
3647                     found_unexpected = TRUE;
3648                     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3649                                            "For %s, fold of %02x is %02x\n",
3650                                            newctype, i, PL_fold_locale[i]));
3651                 }
3652             }
3653         }
3654
3655         if (found_unexpected) {
3656             DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3657                                "All bytes not mentioned above either fold to"
3658                                " themselves or are the expected ASCII or"
3659                                " Latin1 ones\n"));
3660         }
3661         else {
3662             DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3663                                    "No nonstandard folds were found\n"));
3664 #    endif
3665
3666         }
3667     }
3668
3669 #    ifdef MB_CUR_MAX
3670
3671     /* We only handle single-byte locales (outside of UTF-8 ones); so if this
3672      * locale requires more than one byte, there are going to be BIG problems.
3673      * */
3674
3675     if (MB_CUR_MAX > 1 && ! PL_in_utf8_CTYPE_locale
3676
3677             /* Some platforms return MB_CUR_MAX > 1 for even the "C" locale.
3678              * Just assume that the implementation for them (plus for POSIX) is
3679              * correct and the > 1 value is spurious.  (Since these are
3680              * specially handled to never be considered UTF-8 locales, as long
3681              * as this is the only problem, everything should work fine */
3682         && ! isNAME_C_OR_POSIX(newctype))
3683     {
3684         DEBUG_L(PerlIO_printf(Perl_debug_log,
3685                             "Unsupported, MB_CUR_MAX=%d\n", (int) MB_CUR_MAX));
3686
3687         Perl_ck_warner_d(aTHX_ packWARN(WARN_LOCALE),
3688                          "Locale '%s' is unsupported, and may crash the"
3689                          " interpreter",
3690                          newctype);
3691     }
3692
3693 #    endif
3694
3695     DEBUG_Lv(PerlIO_printf(Perl_debug_log, "check_for_problems=%d\n",
3696                                            check_for_problems));
3697
3698     /* We don't populate the other lists if a UTF-8 locale, but do check that
3699      * everything works as expected, unless checking turned off */
3700     if (check_for_problems) {
3701         /* Assume enough space for every character being bad.  4 spaces each
3702          * for the 94 printable characters that are output like "'x' "; and 5
3703          * spaces each for "'\\' ", "'\t' ", and "'\n' "; plus a terminating
3704          * NUL */
3705         char bad_chars_list[ (94 * 4) + (3 * 5) + 1 ] = { '\0' };
3706         unsigned int bad_count = 0;         /* Count of bad characters */
3707
3708         for (unsigned i = 0; i < 256; i++) {
3709
3710             /* If checking for locale problems, see if the native ASCII-range
3711              * printables plus \n and \t are in their expected categories in
3712              * the new locale.  If not, this could mean big trouble, upending
3713              * Perl's and most programs' assumptions, like having a
3714              * metacharacter with special meaning become a \w.  Fortunately,
3715              * it's very rare to find locales that aren't supersets of ASCII
3716              * nowadays.  It isn't a problem for most controls to be changed
3717              * into something else; we check only \n and \t, though perhaps \r
3718              * could be an issue as well. */
3719             if (isGRAPH_A(i) || isBLANK_A(i) || i == '\n') {
3720                 bool is_bad = FALSE;
3721                 char name[4] = { '\0' };
3722
3723                 /* Convert the name into a string */
3724                 if (isGRAPH_A(i)) {
3725                     name[0] = i;
3726                     name[1] = '\0';
3727                 }
3728                 else if (i == '\n') {
3729                     my_strlcpy(name, "\\n", sizeof(name));
3730                 }
3731                 else if (i == '\t') {
3732                     my_strlcpy(name, "\\t", sizeof(name));
3733                 }
3734                 else {
3735                     assert(i == ' ');
3736                     my_strlcpy(name, "' '", sizeof(name));
3737                 }
3738
3739                 /* Check each possibe class */
3740                 if (UNLIKELY(cBOOL(isU8_ALPHANUMERIC_LC(i)) !=
3741                                                     cBOOL(isALPHANUMERIC_A(i))))
3742                 {
3743                     is_bad = TRUE;
3744                     DEBUG_L(PerlIO_printf(Perl_debug_log,
3745                                         "isalnum('%s') unexpectedly is %x\n",
3746                                         name, cBOOL(isU8_ALPHANUMERIC_LC(i))));
3747                 }
3748                 if (UNLIKELY(cBOOL(isU8_ALPHA_LC(i)) != cBOOL(isALPHA_A(i))))  {
3749                     is_bad = TRUE;
3750                     DEBUG_L(PerlIO_printf(Perl_debug_log,
3751                                           "isalpha('%s') unexpectedly is %x\n",
3752                                           name, cBOOL(isU8_ALPHA_LC(i))));
3753                 }
3754                 if (UNLIKELY(cBOOL(isU8_DIGIT_LC(i)) != cBOOL(isDIGIT_A(i))))  {
3755                     is_bad = TRUE;
3756                     DEBUG_L(PerlIO_printf(Perl_debug_log,
3757                                           "isdigit('%s') unexpectedly is %x\n",
3758                                           name, cBOOL(isU8_DIGIT_LC(i))));
3759                 }
3760                 if (UNLIKELY(cBOOL(isU8_GRAPH_LC(i)) != cBOOL(isGRAPH_A(i))))  {
3761                     is_bad = TRUE;
3762                     DEBUG_L(PerlIO_printf(Perl_debug_log,
3763                                           "isgraph('%s') unexpectedly is %x\n",
3764                                           name, cBOOL(isU8_GRAPH_LC(i))));
3765                 }
3766                 if (UNLIKELY(cBOOL(isU8_LOWER_LC(i)) != cBOOL(isLOWER_A(i))))  {
3767                     is_bad = TRUE;
3768                     DEBUG_L(PerlIO_printf(Perl_debug_log,
3769                                           "islower('%s') unexpectedly is %x\n",
3770                                           name, cBOOL(isU8_LOWER_LC(i))));
3771                 }
3772                 if (UNLIKELY(cBOOL(isU8_PRINT_LC(i)) != cBOOL(isPRINT_A(i))))  {
3773                     is_bad = TRUE;
3774                     DEBUG_L(PerlIO_printf(Perl_debug_log,
3775                                           "isprint('%s') unexpectedly is %x\n",
3776                                           name, cBOOL(isU8_PRINT_LC(i))));
3777                 }
3778                 if (UNLIKELY(cBOOL(isU8_PUNCT_LC(i)) != cBOOL(isPUNCT_A(i))))  {
3779                     is_bad = TRUE;
3780                     DEBUG_L(PerlIO_printf(Perl_debug_log,
3781                                           "ispunct('%s') unexpectedly is %x\n",
3782                                           name, cBOOL(isU8_PUNCT_LC(i))));
3783                 }
3784                 if (UNLIKELY(cBOOL(isU8_SPACE_LC(i)) != cBOOL(isSPACE_A(i))))  {
3785                     is_bad = TRUE;
3786                     DEBUG_L(PerlIO_printf(Perl_debug_log,
3787                                           "isspace('%s') unexpectedly is %x\n",
3788                                           name, cBOOL(isU8_SPACE_LC(i))));
3789                 }
3790                 if (UNLIKELY(cBOOL(isU8_UPPER_LC(i)) != cBOOL(isUPPER_A(i))))  {
3791                     is_bad = TRUE;
3792                     DEBUG_L(PerlIO_printf(Perl_debug_log,
3793                                           "isupper('%s') unexpectedly is %x\n",
3794                                           name, cBOOL(isU8_UPPER_LC(i))));
3795                 }
3796                 if (UNLIKELY(cBOOL(isU8_XDIGIT_LC(i))!= cBOOL(isXDIGIT_A(i)))) {
3797                     is_bad = TRUE;
3798                     DEBUG_L(PerlIO_printf(Perl_debug_log,
3799                                           "isxdigit('%s') unexpectedly is %x\n",
3800                                           name, cBOOL(isU8_XDIGIT_LC(i))));
3801                 }
3802                 if (UNLIKELY(toU8_LOWER_LC(i) != (int) toLOWER_A(i))) {
3803                     is_bad = TRUE;
3804                     DEBUG_L(PerlIO_printf(Perl_debug_log,
3805                             "tolower('%s')=0x%x instead of the expected 0x%x\n",
3806                             name, toU8_LOWER_LC(i), (int) toLOWER_A(i)));
3807                 }
3808                 if (UNLIKELY(toU8_UPPER_LC(i) != (int) toUPPER_A(i))) {
3809                     is_bad = TRUE;
3810                     DEBUG_L(PerlIO_printf(Perl_debug_log,
3811                             "toupper('%s')=0x%x instead of the expected 0x%x\n",
3812                             name, toU8_UPPER_LC(i), (int) toUPPER_A(i)));
3813                 }
3814                 if (UNLIKELY((i == '\n' && ! isCNTRL_LC(i))))  {
3815                     is_bad = TRUE;
3816                     DEBUG_L(PerlIO_printf(Perl_debug_log,
3817                                 "'\\n' (=%02X) is not a control\n", (int) i));
3818                 }
3819
3820                 /* Add to the list;  Separate multiple entries with a blank */
3821                 if (is_bad) {
3822                     if (bad_count) {
3823                         my_strlcat(bad_chars_list, " ", sizeof(bad_chars_list));
3824                     }
3825                     my_strlcat(bad_chars_list, name, sizeof(bad_chars_list));
3826                     bad_count++;
3827                 }
3828             }
3829         }
3830
3831         if (bad_count == 2 && maybe_utf8_turkic) {
3832             bad_count = 0;
3833             *bad_chars_list = '\0';
3834
3835             /* The casts are because otherwise some compilers warn:
3836                 gcc.gnu.org/bugzilla/show_bug.cgi?id=99950
3837                 gcc.gnu.org/bugzilla/show_bug.cgi?id=94182
3838              */
3839             PL_fold_locale[ (U8) 'I' ] = 'I';
3840             PL_fold_locale[ (U8) 'i' ] = 'i';
3841             PL_in_utf8_turkic_locale = TRUE;
3842             DEBUG_L(PerlIO_printf(Perl_debug_log, "%s is turkic\n", newctype));
3843         }
3844
3845         /* If we found problems and we want them output, do so */
3846         if (   (UNLIKELY(bad_count))
3847             && (LIKELY(ckWARN_d(WARN_LOCALE)) || UNLIKELY(DEBUG_L_TEST)))
3848         {
3849             /* WARNING.  If you change the wording of these; be sure to update
3850              * t/loc_tools.pl correspondingly */
3851
3852             if (PL_in_utf8_CTYPE_locale) {
3853                 PL_warn_locale = Perl_newSVpvf(aTHX_
3854                      "Locale '%s' contains (at least) the following characters"
3855                      " which have\nunexpected meanings: %s\nThe Perl program"
3856                      " will use the expected meanings",
3857                       newctype, bad_chars_list);
3858             }
3859             else {
3860                 PL_warn_locale =
3861                     Perl_newSVpvf(aTHX_
3862                                   "\nThe following characters (and maybe"
3863                                   " others) may not have the same meaning as"
3864                                   " the Perl program expects: %s\n",
3865                                   bad_chars_list
3866                             );
3867             }
3868
3869 #    if defined(HAS_SOME_LANGINFO) || defined(WIN32)
3870
3871             char * scratch_buffer = NULL;
3872             Perl_sv_catpvf(aTHX_ PL_warn_locale, "; codeset=%s",
3873                                  my_langinfo_c(CODESET, LC_CTYPE,
3874                                                newctype,
3875                                                &scratch_buffer, NULL,
3876                                                NULL));
3877             Safefree(scratch_buffer);
3878
3879 #    endif
3880
3881             Perl_sv_catpvf(aTHX_ PL_warn_locale, "\n");
3882
3883             /* If we are actually in the scope of the locale or are debugging,
3884              * output the message now.  If not in that scope, we save the
3885              * message to be output at the first operation using this locale,
3886              * if that actually happens.  Most programs don't use locales, so
3887              * they are immune to bad ones.  */
3888             if (IN_LC(LC_CTYPE) || UNLIKELY(DEBUG_L_TEST)) {
3889
3890                 /* The '0' below suppresses a bogus gcc compiler warning */
3891                 Perl_warner(aTHX_ packWARN(WARN_LOCALE), SvPVX(PL_warn_locale),
3892                                                                             0);
3893                 if (IN_LC(LC_CTYPE)) {
3894                     SvREFCNT_dec_NN(PL_warn_locale);
3895                     PL_warn_locale = NULL;
3896                 }
3897             }
3898         }
3899     }
3900 }
3901
3902 void
3903 Perl_warn_problematic_locale()
3904 {
3905     dTHX;
3906
3907     /* Core-only function that outputs the message in PL_warn_locale,
3908      * and then NULLS it.  Should be called only through the macro
3909      * CHECK_AND_WARN_PROBLEMATIC_LOCALE_ */
3910
3911     if (PL_warn_locale) {
3912         Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
3913                              SvPVX(PL_warn_locale),
3914                              0 /* dummy to avoid compiler warning */ );
3915         SvREFCNT_dec_NN(PL_warn_locale);
3916         PL_warn_locale = NULL;
3917     }
3918 }
3919
3920 #  endif /* USE_LOCALE_CTYPE */
3921
3922 STATIC void
3923
3924 #  ifdef LC_ALL
3925
3926 S_new_LC_ALL(pTHX_ const char *lc_all, bool force)
3927
3928 #  else
3929
3930 S_new_LC_ALL(pTHX_ const char ** individ_locales, bool force)
3931
3932 #  endif
3933
3934 {
3935     PERL_ARGS_ASSERT_NEW_LC_ALL;
3936
3937     /* new_LC_ALL() updates all the things we care about.  Note that this is
3938      * called just after a change, so uses the actual underlying locale just
3939      * set, and not the nominal one (should they differ, as they may in
3940      * LC_NUMERIC). */
3941
3942 #  ifdef LC_ALL
3943
3944     const char * individ_locales[LC_ALL_INDEX_] = { NULL };
3945
3946     switch (parse_LC_ALL_string(lc_all,
3947                                 individ_locales,
3948                                 override_if_ignored,   /* Override any ignored
3949                                                           categories */
3950                                 true,   /* Always fill array */
3951                                 true,   /* Panic if fails, as to get here it
3952                                            earlier had to have succeeded */
3953                                 __LINE__))
3954     {
3955         case invalid:
3956         case no_array:
3957         case only_element_0:
3958         locale_panic_("Unexpected return from parse_LC_ALL_string");
3959
3960         case full_array:
3961         break;
3962     }
3963
3964 #  endif
3965
3966     for (unsigned int i = 0; i < LC_ALL_INDEX_; i++) {
3967         if (update_functions[i]) {
3968             const char * this_locale = individ_locales[i];
3969             update_functions[i](aTHX_ this_locale, force);
3970         }
3971
3972 #  ifdef LC_ALL
3973
3974         Safefree(individ_locales[i]);
3975
3976 #  endif
3977
3978     }
3979 }
3980
3981 #  ifdef USE_LOCALE_COLLATE
3982
3983 STATIC void
3984 S_new_collate(pTHX_ const char *newcoll, bool force)
3985 {
3986     PERL_ARGS_ASSERT_NEW_COLLATE;
3987     PERL_UNUSED_ARG(force);
3988
3989     /* Called after each libc setlocale() call affecting LC_COLLATE, to tell
3990      * core Perl this and that 'newcoll' is the name of the new locale.
3991      *
3992      * The design of locale collation is that every locale change is given an
3993      * index 'PL_collation_ix'.  The first time a string participates in an
3994      * operation that requires collation while locale collation is active, it
3995      * is given PERL_MAGIC_collxfrm magic (via sv_collxfrm_flags()).  That
3996      * magic includes the collation index, and the transformation of the string
3997      * by strxfrm(), q.v.  That transformation is used when doing comparisons,
3998      * instead of the string itself.  If a string changes, the magic is
3999      * cleared.  The next time the locale changes, the index is incremented,
4000      * and so we know during a comparison that the transformation is not
4001      * necessarily still valid, and so is recomputed.  Note that if the locale
4002      * changes enough times, the index could wrap, and it is possible that a
4003      * transformation would improperly be considered valid, leading to an
4004      * unlikely bug.  The value is declared to the widest possible type on this
4005      * platform. */
4006
4007     /* Return if the locale isn't changing */
4008     if (strEQ(PL_collation_name, newcoll)) {
4009         return;
4010     }
4011
4012     Safefree(PL_collation_name);
4013     PL_collation_name = savepv(newcoll);
4014     ++PL_collation_ix;
4015
4016     /* Set the new one up if trivial.  Since this is called at process
4017      * initialization, be aware that this bit can't rely on much being
4018      * available. */
4019     PL_collation_standard = isNAME_C_OR_POSIX(newcoll);
4020     if (PL_collation_standard) {
4021         DEBUG_Lv(PerlIO_printf(Perl_debug_log,
4022                                "Setting PL_collation name='%s'\n",
4023                                PL_collation_name));
4024         PL_collxfrm_base = 0;
4025         PL_collxfrm_mult = 2;
4026         PL_in_utf8_COLLATE_locale = FALSE;
4027         PL_strxfrm_NUL_replacement = '\0';
4028         PL_strxfrm_max_cp = 0;
4029         return;
4030     }
4031
4032     /* Flag that the remainder of the set up is being deferred until first
4033      * need. */
4034     PL_collxfrm_mult = 0;
4035     PL_collxfrm_base = 0;
4036
4037 }
4038
4039 #  endif /* USE_LOCALE_COLLATE */
4040
4041 #  ifdef WIN32
4042
4043 STATIC wchar_t *
4044 S_Win_byte_string_to_wstring(const UINT code_page, const char * byte_string)
4045 {
4046     /* Caller must arrange to free the returned string */
4047
4048     int req_size = MultiByteToWideChar(code_page, 0, byte_string, -1, NULL, 0);
4049     if (! req_size) {
4050         SET_EINVAL;
4051         return NULL;
4052     }
4053
4054     wchar_t *wstring;
4055     Newx(wstring, req_size, wchar_t);
4056
4057     if (! MultiByteToWideChar(code_page, 0, byte_string, -1, wstring, req_size))
4058     {
4059         Safefree(wstring);
4060         SET_EINVAL;
4061         return NULL;
4062     }
4063
4064     return wstring;
4065 }
4066
4067 #    define Win_utf8_string_to_wstring(s)                                   \
4068                                     Win_byte_string_to_wstring(CP_UTF8, (s))
4069
4070 STATIC char *
4071 S_Win_wstring_to_byte_string(const UINT code_page, const wchar_t * wstring)
4072 {
4073     /* Caller must arrange to free the returned string */
4074
4075     int req_size =
4076             WideCharToMultiByte(code_page, 0, wstring, -1, NULL, 0, NULL, NULL);
4077
4078     char *byte_string;
4079     Newx(byte_string, req_size, char);
4080
4081     if (! WideCharToMultiByte(code_page, 0, wstring, -1, byte_string,
4082                                                          req_size, NULL, NULL))
4083     {
4084         Safefree(byte_string);
4085         SET_EINVAL;
4086         return NULL;
4087     }
4088
4089     return byte_string;
4090 }
4091
4092 #    define Win_wstring_to_utf8_string(ws)                                  \
4093                                    Win_wstring_to_byte_string(CP_UTF8, (ws))
4094
4095 STATIC const char *
4096 S_wrap_wsetlocale(pTHX_ const int category, const char *locale)
4097 {
4098     PERL_ARGS_ASSERT_WRAP_WSETLOCALE;
4099
4100     /* Calls _wsetlocale(), converting the parameters/return to/from
4101      * Perl-expected forms as if plain setlocale() were being called instead.
4102      *
4103      * Caller must arrange for the returned PV to be freed.
4104      */
4105
4106     const wchar_t * wlocale = NULL;
4107
4108     if (locale) {
4109         wlocale = Win_utf8_string_to_wstring(locale);
4110         if (! wlocale) {
4111             return NULL;
4112         }
4113     }
4114
4115     WSETLOCALE_LOCK;
4116     const wchar_t * wresult = _wsetlocale(category, wlocale);
4117
4118     if (! wresult) {
4119         WSETLOCALE_UNLOCK;
4120         Safefree(wlocale);
4121         return NULL;
4122     }
4123
4124     const char * result = Win_wstring_to_utf8_string(wresult);
4125     WSETLOCALE_UNLOCK;
4126
4127     Safefree(wlocale);
4128     return result;
4129 }
4130
4131 STATIC const char *
4132 S_win32_setlocale(pTHX_ int category, const char* locale)
4133 {
4134     /* This, for Windows, emulates POSIX setlocale() behavior.  There is no
4135      * difference between the two unless the input locale is "", which normally
4136      * means on Windows to get the machine default, which is set via the
4137      * computer's "Regional and Language Options" (or its current equivalent).
4138      * In POSIX, it instead means to find the locale from the user's
4139      * environment.  This routine changes the Windows behavior to try the POSIX
4140      * behavior first.  Further details are in the called function
4141      * find_locale_from_environment().
4142      */
4143
4144     if (locale != NULL && strEQ(locale, "")) {
4145         /* Note this function may change the locale, but that's ok because we
4146          * are about to change it anyway */
4147         locale = find_locale_from_environment(get_category_index(category));
4148         if (locale == NULL) {
4149             SET_EINVAL;
4150             return NULL;
4151         }
4152     }
4153
4154     const char * result = wrap_wsetlocale(category, locale);
4155     DEBUG_L(PerlIO_printf(Perl_debug_log, "%s\n",
4156                           setlocale_debug_string_r(category, locale, result)));
4157
4158     if (! result) {
4159         SET_EINVAL;
4160         return NULL;
4161     }
4162
4163     save_to_buffer(result, &PL_setlocale_buf, &PL_setlocale_bufsize);
4164
4165 #    ifndef USE_PL_CUR_LC_ALL
4166
4167     Safefree(result);
4168
4169 #  else
4170
4171     /* Here, we need to keep track of LC_ALL, so store the new value.  but if
4172      * the input locale is NULL, we were just querying, so the original value
4173      * hasn't changed */
4174     if (locale == NULL) {
4175         Safefree(result);
4176     }
4177     else {
4178
4179         /* If we set LC_ALL directly above, we already know its new value; but
4180          * if we changed just an individual category, find the new LC_ALL */
4181         if (category != LC_ALL) {
4182             Safefree(result);
4183             result = wrap_wsetlocale(LC_ALL, NULL);
4184         }
4185
4186         Safefree(PL_cur_LC_ALL);
4187         PL_cur_LC_ALL = result;
4188     }
4189
4190     DEBUG_L(PerlIO_printf(Perl_debug_log, "new PL_cur_LC_ALL=%s\n",
4191                                           PL_cur_LC_ALL));
4192 #    endif
4193
4194     return PL_setlocale_buf;
4195 }
4196
4197 #  endif
4198
4199 STATIC const char *
4200 S_native_querylocale_i(pTHX_ const unsigned int cat_index)
4201 {
4202     /* Determine the current locale and return it in the form the platform's
4203      * native locale handling understands.  This is different only from our
4204      * internal form for the LC_ALL category, as platforms differ in how they
4205      * represent that.
4206      *
4207      * This is only called from Perl_setlocale().  As such it returns in
4208      * PL_setlocale_buf */
4209
4210 #  ifdef USE_LOCALE_NUMERIC
4211
4212     /* We have the LC_NUMERIC name saved, because we are normally switched into
4213      * the C locale (or equivalent) for it. */
4214     if (cat_index == LC_NUMERIC_INDEX_) {
4215
4216         /* We don't have to copy this return value, as it is a per-thread
4217          * variable, and won't change until a future setlocale */
4218         return PL_numeric_name;
4219     }
4220
4221 #  endif
4222 #  ifdef LC_ALL
4223
4224     if (cat_index != LC_ALL_INDEX_)
4225
4226 #  endif
4227
4228     {
4229         /* Here, not LC_ALL, and not LC_NUMERIC: the actual and native values
4230          * match */
4231
4232 #  ifdef setlocale_i    /* Can shortcut if this is defined */
4233
4234         return setlocale_i(cat_index, NULL);
4235
4236 #  else
4237
4238         return save_to_buffer(querylocale_i(cat_index),
4239                               &PL_setlocale_buf, &PL_setlocale_bufsize);
4240 #  endif
4241
4242     }
4243
4244     /* Below, querying LC_ALL */
4245
4246 #  ifdef LC_ALL
4247 #    ifdef USE_PL_CURLOCALES
4248 #      define LC_ALL_ARG  PL_curlocales
4249 #    else
4250 #      define LC_ALL_ARG  NULL  /* Causes calculate_LC_ALL_string() to find the
4251                                    locale using a querylocale function */
4252 #    endif
4253
4254     return calculate_LC_ALL_string(LC_ALL_ARG, EXTERNAL_FORMAT_FOR_QUERY,
4255                                    WANT_PL_setlocale_buf,
4256                                    __LINE__);
4257 #    undef LC_ALL_ARG
4258 #  endif    /* has LC_ALL */
4259
4260 }
4261
4262 #endif      /* USE_LOCALE */
4263
4264 /*
4265 =for apidoc Perl_setlocale
4266
4267 This is an (almost) drop-in replacement for the system L<C<setlocale(3)>>,
4268 taking the same parameters, and returning the same information, except that it
4269 returns the correct underlying C<LC_NUMERIC> locale.  Regular C<setlocale> will
4270 instead return C<C> if the underlying locale has a non-dot decimal point
4271 character, or a non-empty thousands separator for displaying floating point
4272 numbers.  This is because perl keeps that locale category such that it has a
4273 dot and empty separator, changing the locale briefly during the operations
4274 where the underlying one is required. C<Perl_setlocale> knows about this, and
4275 compensates; regular C<setlocale> doesn't.
4276
4277 Another reason it isn't completely a drop-in replacement is that it is
4278 declared to return S<C<const char *>>, whereas the system setlocale omits the
4279 C<const> (presumably because its API was specified long ago, and can't be
4280 updated; it is illegal to change the information C<setlocale> returns; doing
4281 so leads to segfaults.)
4282
4283 Finally, C<Perl_setlocale> works under all circumstances, whereas plain
4284 C<setlocale> can be completely ineffective on some platforms under some
4285 configurations.
4286
4287 Changing the locale is not a good idea when more than one thread is running,
4288 except on systems where the predefined variable C<${^SAFE_LOCALES}> is
4289 non-zero.  This is because on such systems the locale is global to the whole
4290 process and not local to just the thread calling the function.  So changing it
4291 in one thread instantaneously changes it in all.  On some such systems, the
4292 system C<setlocale()> is ineffective, returning the wrong information, and
4293 failing to actually change the locale.  z/OS refuses to try to change the
4294 locale once a second thread is created.  C<Perl_setlocale>, should give you
4295 accurate results of what actually happened on these problematic platforms,
4296 returning NULL if the system forbade the locale change.
4297
4298 The return points to a per-thread static buffer, which is overwritten the next
4299 time C<Perl_setlocale> is called from the same thread.
4300
4301 =cut
4302
4303 */
4304
4305 const char *
4306 Perl_setlocale(const int category, const char * locale)
4307 {
4308     /* This wraps POSIX::setlocale() */
4309
4310 #ifndef USE_LOCALE
4311
4312     PERL_UNUSED_ARG(category);
4313     PERL_UNUSED_ARG(locale);
4314
4315     return "C";
4316
4317 #else
4318
4319     dTHX;
4320
4321     DEBUG_L(PerlIO_printf(Perl_debug_log,
4322                           "Entering Perl_setlocale(%d, \"%s\")\n",
4323                           category, locale));
4324
4325     bool valid_category;
4326     unsigned int cat_index = get_category_index_helper(category,
4327                                                        &valid_category,
4328                                                        __LINE__);
4329     if (! valid_category) {
4330         if (ckWARN(WARN_LOCALE)) {
4331             const char * conditional_warn_text;
4332             if (locale == NULL) {
4333                 conditional_warn_text = "";
4334                 locale = "";
4335             }
4336             else {
4337                 conditional_warn_text = "; can't set it to ";
4338             }
4339
4340             /* diag_listed_as: Unknown locale category %d; can't set it to %s */
4341             Perl_warner(aTHX_
4342                            packWARN(WARN_LOCALE),
4343                            "Unknown locale category %d%s%s",
4344                            category, conditional_warn_text, locale);
4345         }
4346
4347         SET_EINVAL;
4348         return NULL;
4349     }
4350
4351 #  ifdef setlocale_i
4352
4353     /* setlocale_i() gets defined only on Configurations that use setlocale()
4354      * in a simple manner that adequately handles all cases.  If this category
4355      * doesn't have any perl complications, just do that. */
4356     if (! update_functions[cat_index]) {
4357         return setlocale_i(cat_index, locale);
4358     }
4359
4360 #  endif
4361
4362     /* Get current locale */
4363     const char * current_locale = native_querylocale_i(cat_index);
4364
4365     /* A NULL locale means only query what the current one is. */
4366     if (locale == NULL) {
4367         return current_locale;
4368     }
4369
4370     if (strEQ(current_locale, locale)) {
4371         DEBUG_L(PerlIO_printf(Perl_debug_log,
4372                              "Already in requested locale: no action taken\n"));
4373         return current_locale;
4374     }
4375
4376     /* Here, an actual change is being requested.  Do it */
4377     if (! bool_setlocale_i(cat_index, locale)) {
4378         DEBUG_L(PerlIO_printf(Perl_debug_log, "%s\n",
4379                           setlocale_debug_string_i(cat_index, locale, "NULL")));
4380         return NULL;
4381     }
4382
4383     /* At this point, the locale has been changed based on the requested value,
4384      * and the querylocale_i() will return the actual new value that the system
4385      * has for the category.  That may not be the same as the input, as libc
4386      * may have returned a synonymous locale name instead of the input one; or,
4387      * if there are locale categories that we are compiled to ignore, any
4388      * attempt to change them away from "C" is overruled */
4389     current_locale = querylocale_i(cat_index);
4390
4391     /* But certain categories need further work.  For example we may need to
4392      * calculate new folding or collation rules.  And for LC_NUMERIC, we have
4393      * to switch into a locale that has a dot radix. */
4394     if (update_functions[cat_index]) {
4395         update_functions[cat_index](aTHX_ current_locale,
4396                                           /* No need to force recalculation, as
4397                                            * aren't coming from a situation
4398                                            * where Perl hasn't been controlling
4399                                            * the locale, so has accurate
4400                                            * records. */
4401                                           false);
4402     }
4403
4404     /* Make sure the result is in a stable buffer for the caller's use, and is
4405      * in the expected format */
4406     current_locale = native_querylocale_i(cat_index);
4407
4408     DEBUG_L(PerlIO_printf(Perl_debug_log, "returning '%s'\n", current_locale));
4409
4410     return current_locale;
4411
4412 #endif
4413
4414 }
4415
4416 #if defined(USE_LOCALE) || defined(HAS_SOME_LANGINFO) || defined(HAS_LOCALECONV)
4417
4418 STATIC utf8ness_t
4419 S_get_locale_string_utf8ness_i(pTHX_ const char * string,
4420                                      const locale_utf8ness_t known_utf8,
4421                                      const char * locale,
4422                                      const unsigned cat_index)
4423 {
4424     PERL_ARGS_ASSERT_GET_LOCALE_STRING_UTF8NESS_I;
4425
4426 #  ifndef USE_LOCALE
4427
4428     return UTF8NESS_NO;
4429     PERL_UNUSED_ARG(string);
4430     PERL_UNUSED_ARG(known_utf8);
4431     PERL_UNUSED_ARG(locale);
4432     PERL_UNUSED_ARG(cat_index);
4433
4434 #  else
4435
4436     assert(cat_index <= LC_ALL_INDEX_);
4437
4438     /* Return to indicate if 'string' in the locale given by the input
4439      * arguments should be considered UTF-8 or not.
4440      *
4441      * If the input 'locale' is not NULL, use that for the locale; otherwise
4442      * use the current locale for the category specified by 'cat_index'.
4443      */
4444
4445     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
4446                            "Entering get_locale_string_utf8ness_i; locale=%s,"
4447                            " index=%u(%s), string=%s, known_utf8=%d\n",
4448                            locale, cat_index, category_names[cat_index],
4449                            ((string)
4450                             ?  _byte_dump_string((U8 *) string,
4451                                                  strlen(string),
4452                                                  0)
4453                             : "nil"),
4454                            known_utf8));
4455     if (string == NULL) {
4456         return UTF8NESS_IMMATERIAL;
4457     }
4458
4459     if (IN_BYTES) { /* respect 'use bytes' */
4460         return UTF8NESS_NO;
4461     }
4462
4463     Size_t len = strlen(string);
4464
4465     /* UTF8ness is immaterial if the representation doesn't vary */
4466     const U8 * first_variant = NULL;
4467     if (is_utf8_invariant_string_loc((U8 *) string, len, &first_variant)) {
4468         return UTF8NESS_IMMATERIAL;
4469     }
4470
4471     /* Can't be UTF-8 if invalid */
4472     if (! is_utf8_string((U8 *) first_variant,
4473                          len - ((char *) first_variant - string)))
4474     {
4475         return UTF8NESS_NO;
4476     }
4477
4478     /* Here and below, we know the string is legal UTF-8, containing at least
4479      * one character requiring a sequence of two or more bytes.  It is quite
4480      * likely to be UTF-8.  But it pays to be paranoid and do further checking.
4481      *
4482      * If we already know the UTF-8ness of the locale, then we immediately know
4483      * what the string is */
4484     if (UNLIKELY(known_utf8 != LOCALE_UTF8NESS_UNKNOWN)) {
4485         if (known_utf8 == LOCALE_IS_UTF8) {
4486             return UTF8NESS_YES;
4487         }
4488         else {
4489             return UTF8NESS_NO;
4490         }
4491     }
4492
4493 #    ifdef HAS_RELIABLE_UTF8NESS_DETERMINATION
4494
4495     /* Here, we have available the libc functions that can be used to
4496      * accurately determine the UTF8ness of the underlying locale.  If it is a
4497      * UTF-8 locale, the string is UTF-8;  otherwise it was coincidental that
4498      * the string is legal UTF-8
4499      *
4500      * However, if the perl is compiled to not pay attention to the category
4501      * being passed in, you might think that that locale is essentially always
4502      * the C locale, so it would make sense to say it isn't UTF-8.  But to get
4503      * here, the string has to contain characters unknown in the C locale.  And
4504      * in fact, Windows boxes are compiled without LC_MESSAGES, as their
4505      * message catalog isn't really a part of the locale system.  But those
4506      * messages really could be UTF-8, and given that the odds are rather small
4507      * of something not being UTF-8 but being syntactically valid UTF-8, khw
4508      * has decided to call such strings as UTF-8. */
4509
4510     if (locale == NULL) {
4511         locale = querylocale_i(cat_index);
4512     }
4513
4514     if (is_locale_utf8(locale)) {
4515         return UTF8NESS_YES;
4516     }
4517
4518     return UTF8NESS_NO;
4519
4520 #    else
4521
4522     /* Here, we have a valid UTF-8 string containing non-ASCII characters, and
4523      * don't have access to functions to check if the locale is UTF-8 or not.
4524      * Assume that it is.  khw tried adding a check that the string is entirely
4525      * in a single Unicode script, but discovered the strftime() timezone is
4526      * user-settable through the environment, which may be in a different
4527      * script than the locale-expected value. */
4528     PERL_UNUSED_ARG(locale);
4529     PERL_UNUSED_ARG(cat_index);
4530
4531     return UTF8NESS_YES;
4532
4533 #    endif
4534 #  endif
4535
4536 }
4537
4538 STATIC bool
4539 S_is_locale_utf8(pTHX_ const char * locale)
4540 {
4541     /* Returns TRUE if the locale 'locale' is UTF-8; FALSE otherwise.  It uses
4542      * my_langinfo(), which employs various methods to get this information
4543      * if nl_langinfo() isn't available, using heuristics as a last resort, in
4544      * which case, the result will very likely be correct for locales for
4545      * languages that have commonly used non-ASCII characters, but for notably
4546      * English, it comes down to if the locale's name ends in something like
4547      * "UTF-8".  It errs on the side of not being a UTF-8 locale.
4548      *
4549      * Systems conforming to C99 should have the needed libc calls to give us a
4550      * completely reliable result. */
4551
4552 #  if ! defined(USE_LOCALE)                                                   \
4553    || ! defined(USE_LOCALE_CTYPE)                                             \
4554    ||   defined(EBCDIC) /* There aren't any real UTF-8 locales at this time */
4555
4556     PERL_UNUSED_ARG(locale);
4557
4558     return FALSE;
4559
4560 #  else
4561
4562     char * scratch_buffer = NULL;
4563     const char * codeset;
4564     bool retval;
4565
4566     PERL_ARGS_ASSERT_IS_LOCALE_UTF8;
4567
4568     if (strEQ(locale, PL_ctype_name)) {
4569         return PL_in_utf8_CTYPE_locale;
4570     }
4571
4572     codeset = my_langinfo_c(CODESET, LC_CTYPE, locale,
4573                             &scratch_buffer, NULL, NULL);
4574     retval = is_codeset_name_UTF8(codeset);
4575
4576     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
4577                            "found codeset=%s, is_utf8=%d\n", codeset, retval));
4578
4579     Safefree(scratch_buffer);
4580
4581     DEBUG_Lv(PerlIO_printf(Perl_debug_log, "is_locale_utf8(%s) returning %d\n",
4582                                                             locale, retval));
4583     return retval;
4584
4585 #  endif
4586
4587 }
4588
4589 #endif
4590 #ifdef USE_LOCALE
4591
4592 STATIC void
4593 S_set_save_buffer_min_size(pTHX_ Size_t min_len,
4594                                  char **buf,
4595                                  Size_t * buf_cursize)
4596 {
4597     /* Make sure the buffer pointed to by *buf is at least as large 'min_len';
4598      * *buf_cursize is the size of 'buf' upon entry; it will be updated to the
4599      * new size on exit.  'buf_cursize' being NULL is to be used when this is a
4600      * single use buffer, which will shortly be freed by the caller. */
4601
4602     if (buf_cursize == NULL) {
4603         Newx(*buf, min_len, char);
4604     }
4605     else if (*buf_cursize == 0) {
4606         Newx(*buf, min_len, char);
4607         *buf_cursize = min_len;
4608     }
4609     else if (min_len > *buf_cursize) {
4610         Renew(*buf, min_len, char);
4611         *buf_cursize = min_len;
4612     }
4613 }
4614
4615 STATIC const char *
4616 S_save_to_buffer(pTHX_ const char * string, char **buf, Size_t *buf_size)
4617 {
4618     PERL_ARGS_ASSERT_SAVE_TO_BUFFER;
4619
4620     /* Copy the NUL-terminated 'string' to a buffer whose address before this
4621      * call began at *buf, and whose available length before this call was
4622      * *buf_size.
4623      *
4624      * If the length of 'string' is greater than the space available, the
4625      * buffer is grown accordingly, which may mean that it gets relocated.
4626      * *buf and *buf_size will be updated to reflect this.
4627      *
4628      * Regardless, the function returns a pointer to where 'string' is now
4629      * stored.
4630      *
4631      * 'string' may be NULL, which means no action gets taken, and NULL is
4632      * returned.
4633      *
4634      * 'buf_size' being NULL is to be used when this is a single use buffer,
4635      * which will shortly be freed by the caller.
4636      *
4637      * If *buf or 'buf_size' are NULL or *buf_size is 0, the buffer is assumed
4638      * empty, and memory is malloc'd.
4639      */
4640
4641     if (! string) {
4642         return NULL;
4643     }
4644
4645     /* No-op to copy over oneself */
4646     if (string == *buf) {
4647         return string;
4648     }
4649
4650     Size_t string_size = strlen(string) + 1;
4651     set_save_buffer_min_size(string_size, buf, buf_size);
4652
4653 #    ifdef DEBUGGING
4654
4655     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
4656                          "Copying '%s' to %p\n",
4657                          ((is_utf8_string((U8 *) string, 0))
4658                           ? string
4659                           :_byte_dump_string((U8 *) string, strlen(string), 0)),
4660                           *buf));
4661
4662     /* Catch glitches.  Usually this is because LC_CTYPE needs to be the same
4663      * locale as whatever is being worked on */
4664     if (UNLIKELY(instr(string, REPLACEMENT_CHARACTER_UTF8))) {
4665         locale_panic_(Perl_form(aTHX_
4666                                 "Unexpected REPLACEMENT_CHARACTER in '%s'\n%s",
4667                                 string, get_LC_ALL_display()));
4668     }
4669
4670 #  endif
4671
4672     Copy(string, *buf, string_size, char);
4673     return *buf;
4674 }
4675
4676 #  ifdef WIN32
4677
4678 bool
4679 Perl_get_win32_message_utf8ness(pTHX_ const char * string)
4680 {
4681     /* This is because Windows doesn't have LC_MESSAGES. */
4682
4683 #    ifdef USE_LOCALE_CTYPE
4684
4685     return get_locale_string_utf8ness_i(string, LOCALE_IS_UTF8,
4686                                         NULL, LC_CTYPE_INDEX_);
4687 #    else
4688
4689     return false;
4690
4691 #    endif
4692
4693 }
4694
4695 #  endif
4696 #endif  /* USE_LOCALE */
4697
4698 int
4699 Perl_mbtowc_(pTHX_ const wchar_t * pwc, const char * s, const Size_t len)
4700 {
4701
4702 #if ! defined(HAS_MBRTOWC) && ! defined(HAS_MBTOWC)
4703
4704     PERL_UNUSED_ARG(pwc);
4705     PERL_UNUSED_ARG(s);
4706     PERL_UNUSED_ARG(len);
4707     return -1;
4708
4709 #else   /* Below we have some form of mbtowc() */
4710 #  if defined(HAS_MBRTOWC)                                      \
4711    && (defined(USE_LOCALE_THREADS) || ! defined(HAS_MBTOWC))
4712 #    define USE_MBRTOWC
4713 #  else
4714 #    undef USE_MBRTOWC
4715 #  endif
4716
4717     int retval = -1;
4718
4719     if (s == NULL) { /* Initialize the shift state to all zeros in
4720                         PL_mbrtowc_ps. */
4721
4722 #  if defined(USE_MBRTOWC)
4723
4724         memzero(&PL_mbrtowc_ps, sizeof(PL_mbrtowc_ps));
4725         return 0;
4726
4727 #  else
4728
4729         SETERRNO(0, 0);
4730         MBTOWC_LOCK_;
4731         retval = mbtowc(NULL, NULL, 0);
4732         MBTOWC_UNLOCK_;
4733         return retval;
4734
4735 #  endif
4736
4737     }
4738
4739 #  if defined(USE_MBRTOWC)
4740
4741     SETERRNO(0, 0);
4742     MBRTOWC_LOCK_;
4743     retval = (SSize_t) mbrtowc((wchar_t *) pwc, s, len, &PL_mbrtowc_ps);
4744     MBRTOWC_UNLOCK_;
4745
4746 #  else
4747
4748     /* Locking prevents races, but locales can be switched out without locking,
4749      * so this isn't a cure all */
4750     SETERRNO(0, 0);
4751     MBTOWC_LOCK_;
4752     retval = mbtowc((wchar_t *) pwc, s, len);
4753     MBTOWC_UNLOCK_;
4754
4755 #  endif
4756
4757     return retval;
4758
4759 #endif
4760
4761 }
4762
4763 /*
4764 =for apidoc Perl_localeconv
4765
4766 This is a thread-safe version of the libc L<localeconv(3)>.  It is the same as
4767 L<POSIX::localeconv|POSIX/localeconv> (returning a hash of the C<localeconv()>
4768 fields), but directly callable from XS code.
4769
4770 =cut
4771 */
4772
4773 HV *
4774 Perl_localeconv(pTHX)
4775 {
4776
4777 #if  ! defined(HAS_LOCALECONV)
4778
4779     return newHV();
4780
4781 #else
4782
4783     return my_localeconv(0);
4784
4785 #endif
4786
4787 }
4788
4789 #if  defined(HAS_LOCALECONV)
4790
4791 HV *
4792 S_my_localeconv(pTHX_ const int item)
4793 {
4794     PERL_ARGS_ASSERT_MY_LOCALECONV;
4795
4796     /* This returns a mortalized hash containing all or certain elements
4797      * returned by localeconv().  It is used by Perl_localeconv() and
4798      * POSIX::localeconv() and is thread-safe.
4799      *
4800      * There are two use cases:
4801      * 1) Called from POSIX::locale_conv().  This returns the lconv structure
4802      *    copied to a hash, based on the current underlying locales for
4803      *    LC_NUMERIC and LC_MONETARY. An input item==0 signifies this case, or
4804      *    on many platforms it is the only use case compiled.
4805      * 2) Certain items that nl_langinfo() provides are also derivable from
4806      *    the return of localeconv().  Windows notably doesn't have
4807      *    nl_langinfo(), so on that, and actually any platform lacking it,
4808      *    my_localeconv() is used also to emulate it for those particular
4809      *    items.  The code to do this is compiled only on such platforms.
4810      *    Rather than going to the expense of creating a full hash when only
4811      *    one item is needed, the returned hash has just the desired item in
4812      *    it.
4813      *
4814      * To access all the localeconv() struct lconv fields, there is a data
4815      * structure that contains every commonly documented field in it.  (Maybe
4816      * some minority platforms have extra fields.  Those could be added here
4817      * without harm; they would just be ignored on platforms lacking them.)
4818      *
4819      * Our structure is compiled to make looping through the fields easier by
4820      * pointing each name to its value's offset within lconv, e.g.,
4821         { "thousands_sep", STRUCT_OFFSET(struct lconv, thousands_sep) }
4822      */
4823 #  define LCONV_ENTRY(name)                                                 \
4824                        {STRINGIFY(name), STRUCT_OFFSET(struct lconv, name)}
4825
4826     /* These synonyms are just for clarity, and to make it easier in case
4827      * something needs to change in the future */
4828 #  define LCONV_NUMERIC_ENTRY(name)  LCONV_ENTRY(name)
4829 #  define LCONV_MONETARY_ENTRY(name) LCONV_ENTRY(name)
4830
4831     /* There are just a few fields for NUMERIC strings */
4832     const lconv_offset_t lconv_numeric_strings[] = {
4833 #  ifndef NO_LOCALECONV_GROUPING
4834         LCONV_NUMERIC_ENTRY(grouping),
4835 #   endif
4836         LCONV_NUMERIC_ENTRY(thousands_sep),
4837         LCONV_NUMERIC_ENTRY(decimal_point),
4838         {NULL, 0}
4839     };
4840
4841     /* When used to implement nl_langinfo(), we save time by only populating
4842      * the hash with the field(s) needed.  Thus we would need a data structure
4843      * of just:
4844      *  LCONV_NUMERIC_ENTRY(decimal_point),
4845      *  {NULL, 0}
4846      *
4847      * By placing the decimal_point field last in the full structure, we can
4848      * use just the tail for this bit of it, saving space.  This macro yields
4849      * the address of the sub structure. */
4850 #  define DECIMAL_POINT_ADDRESS                                             \
4851         &lconv_numeric_strings[(C_ARRAY_LENGTH(lconv_numeric_strings) - 2)]
4852
4853     /* And the MONETARY string fields */
4854     const lconv_offset_t lconv_monetary_strings[] = {
4855         LCONV_MONETARY_ENTRY(int_curr_symbol),
4856         LCONV_MONETARY_ENTRY(mon_decimal_point),
4857 #  ifndef NO_LOCALECONV_MON_THOUSANDS_SEP
4858         LCONV_MONETARY_ENTRY(mon_thousands_sep),
4859 #  endif
4860 #  ifndef NO_LOCALECONV_MON_GROUPING
4861         LCONV_MONETARY_ENTRY(mon_grouping),
4862 #  endif
4863         LCONV_MONETARY_ENTRY(positive_sign),
4864         LCONV_MONETARY_ENTRY(negative_sign),
4865         LCONV_MONETARY_ENTRY(currency_symbol),
4866         {NULL, 0}
4867     };
4868
4869     /* Like above, this field being last can be used as a sub structure */
4870 #  define CURRENCY_SYMBOL_ADDRESS                                            \
4871       &lconv_monetary_strings[(C_ARRAY_LENGTH(lconv_monetary_strings) - 2)]
4872
4873     /* Finally there are integer fields, all are for monetary purposes */
4874     const lconv_offset_t lconv_integers[] = {
4875         LCONV_ENTRY(int_frac_digits),
4876         LCONV_ENTRY(frac_digits),
4877         LCONV_ENTRY(p_sep_by_space),
4878         LCONV_ENTRY(n_cs_precedes),
4879         LCONV_ENTRY(n_sep_by_space),
4880         LCONV_ENTRY(p_sign_posn),
4881         LCONV_ENTRY(n_sign_posn),
4882 #  ifdef HAS_LC_MONETARY_2008
4883         LCONV_ENTRY(int_p_cs_precedes),
4884         LCONV_ENTRY(int_p_sep_by_space),
4885         LCONV_ENTRY(int_n_cs_precedes),
4886         LCONV_ENTRY(int_n_sep_by_space),
4887         LCONV_ENTRY(int_p_sign_posn),
4888         LCONV_ENTRY(int_n_sign_posn),
4889 #  endif
4890         LCONV_ENTRY(p_cs_precedes),
4891         {NULL, 0}
4892     };
4893
4894     /* Like above, this field being last can be used as a sub structure */
4895 #  define P_CS_PRECEDES_ADDRESS                                       \
4896       &lconv_integers[(C_ARRAY_LENGTH(lconv_integers) - 2)]
4897
4898     /* If we aren't paying attention to a given category, use LC_CTYPE instead;
4899      * If not paying attention to that either, the code below should end up not
4900      * using this.  Make sure that things blow up if that avoidance gets lost,
4901      * by setting the category to an out-of-bounds value */
4902     unsigned int numeric_index;
4903     unsigned int monetary_index;
4904
4905 #  ifdef USE_LOCALE_NUMERIC
4906     numeric_index = LC_NUMERIC_INDEX_;
4907 #  elif defined(USE_LOCALE_CTYPE)
4908     numeric_index = LC_CTYPE_INDEX_;
4909 #  else
4910     numeric_index = (unsigned) -1;
4911 #  endif
4912 #  ifdef USE_LOCALE_MONETARY
4913     monetary_index = LC_MONETARY_INDEX_;
4914 #  elif defined(USE_LOCALE_CTYPE)
4915     monetary_index = LC_CTYPE_INDEX_;
4916 #  else
4917     monetary_index = (unsigned) -1;
4918 #  endif
4919
4920     /* Some platforms, for correct non-mojibake results, require LC_CTYPE's
4921      * locale to match LC_NUMERIC's for the numeric fields, and LC_MONETARY's
4922      * for the monetary ones.  What happens if LC_NUMERIC and LC_MONETARY
4923      * aren't compatible?  Wrong results.  To avoid that, we call localeconv()
4924      * twice, once for each locale, setting LC_CTYPE to match the category.
4925      * But if the locales of both categories are the same, there is no need for
4926      * a second call.  Assume this is the case unless overridden below */
4927     bool requires_2nd_localeconv = false;
4928
4929     /* The actual hash populating is done by S_populate_hash_from_localeconv().
4930      * It gets passed an array of length two containing the data structure it
4931      * is supposed to use to get the key names to fill the hash with.  One
4932      * element is always for the NUMERIC strings (or NULL if none to use), and
4933      * the other element similarly for the MONETARY ones. */
4934 #  define NUMERIC_STRING_OFFSET   0
4935 #  define MONETARY_STRING_OFFSET  1
4936     const lconv_offset_t * strings[2] = { NULL, NULL };
4937
4938     /* This is a mask, with one bit to tell S_populate_hash_from_localeconv to
4939      * populate the NUMERIC items; another bit for the MONETARY ones.  This way
4940      * it can choose which (or both) to populate from */
4941     U32 index_bits = 0;
4942
4943     /* This converts from a locale index to its bit position in the above mask.
4944      * */
4945 #  define INDEX_TO_BIT(i)  (1 << (i))
4946
4947     /* The two categories can have disparate locales.  Initialize them to C and
4948      * override later whichever one(s) we pay attention to */
4949     const char * numeric_locale = "C";
4950     const char * monetary_locale = "C";
4951
4952     /* This will be either 'numeric_locale' or 'monetary_locale' depending on
4953      * what we are working on at the moment */
4954     const char * locale;
4955
4956     /* The LC_MONETARY category also has some integer-valued fields, whose
4957      * information is kept in a separate list */
4958     const lconv_offset_t * integers;
4959
4960 #  ifdef HAS_SOME_LANGINFO
4961
4962     /* If the only use-case for this is the full localeconv(), the 'item'
4963      * parameter is ignored. */
4964     PERL_UNUSED_ARG(item);
4965
4966 #  else
4967
4968     /* This only gets compiled for the use-case of using localeconv() to
4969      * emulate an nl_langinfo() missing from the platform. */
4970
4971 #    ifdef USE_LOCALE_NUMERIC
4972
4973     /* We need this substructure to only return this field for the THOUSEP
4974      * item.  The other items also need substructures, but they were handled
4975      * above by placing the substructure's item at the end of the full one, so
4976      * the data structure could do double duty.  However, both this and
4977      * RADIXCHAR would need to be in the final position of the same full
4978      * structure; an impossibility.  So make this into a separate structure */
4979     const lconv_offset_t  thousands_sep_string[] = {
4980         LCONV_NUMERIC_ENTRY(thousands_sep),
4981         {NULL, 0}
4982     };
4983
4984 #    endif
4985
4986     /* End of all the initialization of data structures.  Now for actual code.
4987      *
4988      * Without nl_langinfo(), the call to my_localeconv() could be for just one
4989      * of the following 3 items to emulate nl_langinfo().  This is compiled
4990      * only when using perl_langinfo.h, which we control, and it has been
4991      * constructed so that no item is numbered 0.
4992      *
4993      * For each, set up the appropriate parameters for the call below to
4994      * S_populate_hash_from_localeconv() */
4995     if (item != 0) switch (item) {
4996       default:
4997         locale_panic_(Perl_form(aTHX_
4998                     "Unexpected item passed to my_localeconv: %d", item));
4999         break;
5000
5001 #    ifdef USE_LOCALE_NUMERIC
5002
5003       case RADIXCHAR:
5004         locale = numeric_locale = PL_numeric_name;
5005         index_bits = INDEX_TO_BIT(LC_NUMERIC_INDEX_);
5006         strings[NUMERIC_STRING_OFFSET] = DECIMAL_POINT_ADDRESS;
5007         integers = NULL;
5008         break;
5009
5010       case THOUSEP:
5011         index_bits = INDEX_TO_BIT(LC_NUMERIC_INDEX_);
5012         locale = numeric_locale = PL_numeric_name;
5013         strings[NUMERIC_STRING_OFFSET] = thousands_sep_string;
5014         integers = NULL;
5015         break;
5016
5017 #    endif
5018 #    ifdef USE_LOCALE_MONETARY
5019
5020       case CRNCYSTR:
5021         index_bits = INDEX_TO_BIT(LC_MONETARY_INDEX_);
5022         locale = monetary_locale = querylocale_i(LC_MONETARY_INDEX_);
5023
5024         /* This item needs the values for both the currency symbol, and another
5025          * one used to construct the nl_langino()-compatible return */
5026         strings[MONETARY_STRING_OFFSET] = CURRENCY_SYMBOL_ADDRESS;
5027         integers = P_CS_PRECEDES_ADDRESS;
5028         break;
5029
5030 #    endif
5031
5032     } /* End of switch() */
5033
5034     else    /* End of for just one item to emulate nl_langinfo() */
5035
5036 #  endif
5037
5038     {   /* Here, the call is for all of localeconv().  It has a bunch of
5039          * items.  As in the individual item case, set up the parameters for
5040          * S_populate_hash_from_localeconv(); */
5041
5042 #  ifdef USE_LOCALE_NUMERIC
5043         numeric_locale = PL_numeric_name;
5044 #  elif defined(USE_LOCALE_CTYPE)
5045         numeric_locale = querylocale_i(numeric_index);
5046 #  endif
5047 #  if defined(USE_LOCALE_MONETARY) || defined(USE_LOCALE_CTYPE)
5048         monetary_locale = querylocale_i(monetary_index);
5049 #  endif
5050
5051         /* The first call to S_populate_hash_from_localeconv() will be for the
5052          * MONETARY values */
5053         index_bits = INDEX_TO_BIT(monetary_index);
5054         locale = monetary_locale;
5055
5056         /* And if the locales for the two categories are the same, we can also
5057          * do the NUMERIC values in the same call */
5058         if (strEQ(numeric_locale, monetary_locale)) {
5059             index_bits |= INDEX_TO_BIT(numeric_index);
5060         }
5061         else {
5062             requires_2nd_localeconv = true;
5063         }
5064
5065         /* We always pass both sets of strings. 'index_bits' tells
5066          * S_populate_hash_from_localeconv which to actually look at */
5067         strings[NUMERIC_STRING_OFFSET] = lconv_numeric_strings;
5068         strings[MONETARY_STRING_OFFSET] = lconv_monetary_strings;
5069
5070         /* And pass the integer values to populate; again 'index_bits' will
5071          * say to use them or not */
5072         integers = lconv_integers;
5073
5074     }   /* End of call is for localeconv() */
5075
5076     /* The code above has determined the parameters to
5077        S_populate_hash_from_localeconv() for both cases of an individual item
5078        and for the entire structure.  Below is code common to both */
5079
5080     HV * hv = newHV();      /* The returned hash, initially empty */
5081     sv_2mortal((SV*)hv);
5082
5083     /* Call localeconv() and copy its results into the hash.  All the
5084      * parameters have been initialized above */
5085     populate_hash_from_localeconv(hv,
5086                                   locale,
5087                                   index_bits,
5088                                   strings,
5089                                   integers
5090                                  );
5091
5092     /* The above call may have done all the hash fields, but not always, as
5093      * already explained.  If we need a second call it is always for the
5094      * NUMERIC fields */
5095     if (requires_2nd_localeconv) {
5096         populate_hash_from_localeconv(hv,
5097                                       numeric_locale,
5098                                       INDEX_TO_BIT(numeric_index),
5099                                       strings,
5100                                       NULL      /* There are no NUMERIC integer
5101                                                    fields */
5102                                      );
5103     }
5104
5105     /* Here, the hash has been completely populated.
5106      *
5107      * Now go through all the items and:
5108      *  a) For string items, see if they should be marked as UTF-8 or not.
5109      *     This would have been more convenient and faster to do while
5110      *     populating the hash in the first place, but that operation has to be
5111      *     done within a critical section, keeping other threads from
5112      *     executing, so only the minimal amount of work necessary is done at
5113      *     that time.
5114      *  b) For integer items, convert the C CHAR_MAX value into -1.  Again,
5115      *     this could have been done in the critical section, but was deferred
5116      *     to here to keep to the bare minimum amount the time spent owning the
5117      *     processor. CHAR_MAX is a C concept for an 8-bit character type.
5118      *     Perl has no such type; the closest fit is a -1.
5119      *
5120      * XXX On unthreaded perls, this code could be #ifdef'd out, and the
5121      * corrections determined at hash population time, at an extra maintenance
5122      * cost which khw doesn't think is worth it
5123      */
5124     for (unsigned int i = 0; i < 2; i++) {  /* Try both types of strings */
5125         if (! strings[i]) {     /* Skip if no strings of this type */
5126             continue;
5127         }
5128
5129         locale = (i == NUMERIC_STRING_OFFSET)
5130                  ? numeric_locale
5131                  : monetary_locale;
5132
5133         locale_utf8ness_t locale_is_utf8 = LOCALE_UTF8NESS_UNKNOWN;
5134
5135 #  ifdef HAS_RELIABLE_UTF8NESS_DETERMINATION
5136
5137         /* It saves time in the loop below to have predetermined the UTF8ness
5138          * of the locale.  But only do so if the platform reliably has this
5139          * information; otherwise it's better to do it only it should become
5140          * necessary, which happens on a per-element basis in the loop. */
5141
5142         locale_is_utf8 = (is_locale_utf8(locale))
5143                          ? LOCALE_IS_UTF8
5144                          : LOCALE_NOT_UTF8;
5145
5146         if (locale_is_utf8 == LOCALE_NOT_UTF8) {
5147             continue;   /* No string can be UTF-8 if the locale isn't */
5148         }
5149
5150 #  endif
5151
5152         /* Examine each string */
5153         while (1) {
5154             const char * name = strings[i]->name;
5155
5156             if (! name) {   /* Reached the end */
5157                 break;
5158             }
5159
5160             /* 'value' will contain the string that may need to be marked as
5161              * UTF-8 */
5162             SV ** value = hv_fetch(hv, name, strlen(name), true);
5163             if (! value) {
5164                 continue;
5165             }
5166
5167             /* Determine if the string should be marked as UTF-8. */
5168             if (UTF8NESS_YES == (get_locale_string_utf8ness_i(SvPVX(*value),
5169                                                               locale_is_utf8,
5170                                                               NULL, 0)))
5171             {
5172                 SvUTF8_on(*value);
5173             }
5174
5175             strings[i]++;   /* Iterate */
5176         }
5177     }   /* End of fixing up UTF8ness */
5178
5179
5180     /* Examine each integer */
5181     if (integers) while (1) {
5182         const char * name = integers->name;
5183
5184         if (! name) {   /* Reached the end */
5185             break;
5186         }
5187
5188         SV ** value = hv_fetch(hv, name, strlen(name), true);
5189         if (! value) {
5190             continue;
5191         }
5192
5193         /* Change CHAR_MAX to -1 */
5194         if (SvIV(*value) == CHAR_MAX) {
5195             sv_setiv(*value, -1);
5196         }
5197
5198         integers++;   /* Iterate */
5199     }
5200
5201     return hv;
5202 }
5203
5204 STATIC void
5205 S_populate_hash_from_localeconv(pTHX_ HV * hv,
5206
5207                                       /* Switch to this locale to run
5208                                        * localeconv() from */
5209                                       const char * locale,
5210
5211                                       /* bit mask of which categories to
5212                                        * populate */
5213                                       const U32 which_mask,
5214
5215                                       /* strings[0] points to the numeric
5216                                        * string fields; [1] to the monetary */
5217                                       const lconv_offset_t * strings[2],
5218
5219                                       /* And to the monetary integer fields */
5220                                       const lconv_offset_t * integers)
5221 {
5222     PERL_ARGS_ASSERT_POPULATE_HASH_FROM_LOCALECONV;
5223     PERL_UNUSED_ARG(which_mask);    /* Some configurations don't use this;
5224                                        complicated to figure out which */
5225 #  ifndef USE_LOCALE
5226     PERL_UNUSED_ARG(locale);
5227 #  endif
5228
5229     /* Run localeconv() and copy some or all of its results to the input 'hv'
5230      * hash.  Most localeconv() implementations return the values in a global
5231      * static buffer, so the operation must be performed in a critical section,
5232      * ending only after the copy is completed.  There are so many locks
5233      * because localeconv() deals with two categories, and returns in a single
5234      * global static buffer.  Some locks might be no-ops on this platform, but
5235      * not others.  We need to lock if any one isn't a no-op. */
5236
5237 #  ifdef USE_LOCALE_CTYPE
5238
5239     /* Some platforms require LC_CTYPE to be congruent with the category we are
5240      * looking for */
5241     const char * orig_CTYPE_locale = toggle_locale_c(LC_CTYPE, locale);
5242
5243 #  endif
5244 #  ifdef USE_LOCALE_NUMERIC
5245
5246     /* We need to toggle to the underlying NUMERIC locale if we are getting
5247      * NUMERIC strings */
5248     const char * orig_NUMERIC_locale = NULL;
5249     if (which_mask & INDEX_TO_BIT(LC_NUMERIC_INDEX_)) {
5250         LC_NUMERIC_LOCK(0);
5251
5252 #    if defined(WIN32)
5253
5254         /* There is a bug in Windows in which setting LC_CTYPE after the others
5255          * doesn't actually take effect for localeconv().  See commit
5256          * 418efacd1950763f74ed3cc22f8cf9206661b892 for details.  Thus we have
5257          * to make sure that the locale we want is set after LC_CTYPE.  We
5258          * unconditionally toggle away from and back to the current locale
5259          * prior to calling localeconv().
5260          *
5261          * This code will have no effect if we already are in C, but khw
5262          * hasn't seen any cases where this causes problems when we are in the
5263          * C locale. */
5264         orig_NUMERIC_locale = toggle_locale_i(LC_NUMERIC_INDEX_, "C");
5265         toggle_locale_i(LC_NUMERIC_INDEX_, locale);
5266
5267 #    else
5268
5269         /* No need for the extra toggle when not on Windows */
5270         orig_NUMERIC_locale = toggle_locale_i(LC_NUMERIC_INDEX_, locale);
5271
5272 #    endif
5273
5274     }
5275
5276 #  endif
5277 #  if defined(USE_LOCALE_MONETARY) && defined(WIN32)
5278
5279     /* Same Windows bug as described just above for NUMERIC.  Otherwise, no
5280      * need to toggle LC_MONETARY, as it is kept in the underlying locale */
5281     const char * orig_MONETARY_locale = NULL;
5282     if (which_mask & INDEX_TO_BIT(LC_MONETARY_INDEX_)) {
5283         orig_MONETARY_locale = toggle_locale_i(LC_MONETARY_INDEX_, "C");
5284         toggle_locale_i(LC_MONETARY_INDEX_, locale);
5285     }
5286
5287 #  endif
5288
5289     /* Finally ready to do the actual localeconv().  Lock to prevent other
5290      * accesses until we have made a copy of its returned static buffer */
5291     gwLOCALE_LOCK;
5292
5293 #  if defined(TS_W32_BROKEN_LOCALECONV) && defined(USE_THREAD_SAFE_LOCALE)
5294
5295     /* This is a workaround for another bug in Windows.  localeconv() was
5296      * broken with thread-safe locales prior to VS 15.  It looks at the global
5297      * locale instead of the thread one.  As a work-around, we toggle to the
5298      * global locale; populate the return; then toggle back.  We have to use
5299      * LC_ALL instead of the individual categories because of yet another bug
5300      * in Windows.  And this all has to be done in a critical section.
5301      *
5302      * This introduces a potential race with any other thread that has also
5303      * converted to use the global locale, and doesn't protect its locale calls
5304      * with mutexes.  khw can't think of any reason for a thread to do so on
5305      * Windows, as the locale API is the same regardless of thread-safety,
5306      * except if the code is ported from working on another platform where
5307      * there might be some reason to do this.  But this is typically due to
5308      * some alien-to-Perl library that thinks it owns locale setting.  Such a
5309      * library isn't likely to exist on Windows, so such an application is
5310      * unlikely to be run on Windows
5311      */
5312     bool restore_per_thread = FALSE;
5313
5314     /* Save the per-thread locale state */
5315     const char * save_thread = querylocale_c(LC_ALL);
5316
5317     /* Change to the global locale, and note if we already were there */
5318     int config_return = _configthreadlocale(_DISABLE_PER_THREAD_LOCALE);
5319     if (config_return != _DISABLE_PER_THREAD_LOCALE) {
5320         if (config_return == -1) {
5321             locale_panic_("_configthreadlocale returned an error");
5322         }
5323
5324         restore_per_thread = TRUE;
5325     }
5326
5327     /* Save the state of the global locale; then convert to our desired
5328      * state.  */
5329     const char * save_global = querylocale_c(LC_ALL);
5330     void_setlocale_c(LC_ALL, save_thread);
5331
5332 #  endif  /* TS_W32_BROKEN_LOCALECONV */
5333
5334     /* Finally, do the actual localeconv */
5335     const char *lcbuf_as_string = (const char *) localeconv();
5336
5337     /* Fill in the string fields of the HV* */
5338     for (unsigned int i = 0; i < 2; i++) {
5339
5340         /* One iteration is only for the numeric string fields.  Skip these
5341          * unless we are compiled to care about those fields and the input
5342          * parameters indicate we want their values */
5343         if (   i == NUMERIC_STRING_OFFSET
5344
5345 #  ifdef USE_LOCALE_NUMERIC
5346
5347             && (which_mask & INDEX_TO_BIT(LC_NUMERIC_INDEX_)) == 0
5348
5349 #  endif
5350
5351         ) {
5352             continue;
5353         }
5354
5355         /* The other iteration is only for the monetary string fields.  Again
5356          * skip it unless we want those values */
5357         if (   i == MONETARY_STRING_OFFSET
5358
5359 #  ifdef USE_LOCALE_MONETARY
5360
5361             && (which_mask & INDEX_TO_BIT(LC_MONETARY_INDEX_)) == 0
5362
5363 #  endif
5364         ) {
5365
5366             continue;
5367         }
5368
5369         /* For each field for the given category ... */
5370         const lconv_offset_t * category_strings = strings[i];
5371         while (1) {
5372             const char * name = category_strings->name;
5373             if (! name) {   /* Quit at the end */
5374                 break;
5375             }
5376
5377             /* we have set things up so that we know where in the returned
5378              * structure, when viewed as a string, the corresponding value is.
5379              * */
5380             const char *value = *((const char **)(  lcbuf_as_string
5381                                                   + category_strings->offset));
5382
5383             /* Set to get next string on next iteration */
5384             category_strings++;
5385
5386             /* Skip if this platform doesn't have this field. */
5387             if (! value) {
5388                 continue;
5389             }
5390
5391             /* Copy to the hash */
5392             (void) hv_store(hv,
5393                             name, strlen(name),
5394                             newSVpv(value, strlen(value)),
5395                             0);
5396         }
5397
5398         /* Add any int fields to the HV* */
5399         if (i == MONETARY_STRING_OFFSET && integers) {
5400             while (integers->name) {
5401                 const char value = *((const char *)(  lcbuf_as_string
5402                                                     + integers->offset));
5403                 (void) hv_store(hv, integers->name,
5404                                 strlen(integers->name), newSViv(value), 0);
5405                 integers++;
5406             }
5407         }
5408     }   /* End of loop through the fields */
5409
5410     /* Done with copying to the hash.  Can unwind the critical section locks */
5411
5412 #  if defined(TS_W32_BROKEN_LOCALECONV) && defined(USE_THREAD_SAFE_LOCALE)
5413
5414     /* Restore the global locale's prior state */
5415     void_setlocale_c(LC_ALL, save_global);
5416
5417     /* And back to per-thread locales */
5418     if (restore_per_thread) {
5419         if (_configthreadlocale(_ENABLE_PER_THREAD_LOCALE) == -1) {
5420             locale_panic_("_configthreadlocale returned an error");
5421         }
5422     }
5423
5424     /* Restore the per-thread locale state */
5425     void_setlocale_c(LC_ALL, save_thread);
5426
5427 #  endif  /* TS_W32_BROKEN_LOCALECONV */
5428
5429     gwLOCALE_UNLOCK;    /* Finished with the critical section of a
5430                            globally-accessible buffer */
5431
5432 #  if defined(USE_LOCALE_MONETARY) && defined(WIN32)
5433
5434     restore_toggled_locale_i(LC_MONETARY_INDEX_, orig_MONETARY_locale);
5435
5436 #  endif
5437 #  ifdef USE_LOCALE_NUMERIC
5438
5439     restore_toggled_locale_i(LC_NUMERIC_INDEX_, orig_NUMERIC_locale);
5440     if (which_mask & INDEX_TO_BIT(LC_NUMERIC_INDEX_)) {
5441         LC_NUMERIC_UNLOCK;
5442     }
5443
5444 #  endif
5445 #  ifdef USE_LOCALE_CTYPE
5446
5447     restore_toggled_locale_c(LC_CTYPE, orig_CTYPE_locale);
5448
5449 #  endif
5450
5451 }
5452
5453 #endif /* defined(HAS_LOCALECONV) */
5454 #ifndef HAS_SOME_LANGINFO
5455
5456 typedef int nl_item;    /* Substitute 'int' for emulated nl_langinfo() */
5457
5458 #endif
5459
5460 /*
5461
5462 =for apidoc      Perl_langinfo
5463 =for apidoc_item Perl_langinfo8
5464
5465 C<Perl_langinfo> is an (almost) drop-in replacement for the system
5466 C<L<nl_langinfo(3)>>, taking the same C<item> parameter values, and returning
5467 the same information.  But it is more thread-safe than regular
5468 C<nl_langinfo()>, and hides the quirks of Perl's locale handling from your
5469 code, and can be used on systems that lack a native C<nl_langinfo>.
5470
5471 However, you should instead use the improved version of this:
5472 L</Perl_langinfo8>, which behaves identically except for an additional
5473 parameter, a pointer to a variable declared as L</C<utf8ness_t>>, into which it
5474 returns to you how you should treat the returned string with regards to it
5475 being encoded in UTF-8 or not.
5476
5477 Concerning the differences between these and plain C<nl_langinfo()>:
5478
5479 =over
5480
5481 =item a.
5482
5483 C<Perl_langinfo8> has an extra parameter, described above.  Besides this, the
5484 other reason they aren't quite a drop-in replacement is actually an advantage.
5485 The C<const>ness of the return allows the compiler to catch attempts to write
5486 into the returned buffer, which is illegal and could cause run-time crashes.
5487
5488 =item b.
5489
5490 They deliver the correct results for the C<RADIXCHAR> and C<THOUSEP> items,
5491 without you having to write extra code.  The reason for the extra code would be
5492 because these are from the C<LC_NUMERIC> locale category, which is normally
5493 kept set by Perl so that the radix is a dot, and the separator is the empty
5494 string, no matter what the underlying locale is supposed to be, and so to get
5495 the expected results, you have to temporarily toggle into the underlying
5496 locale, and later toggle back.  (You could use plain C<nl_langinfo> and
5497 C<L</STORE_LC_NUMERIC_FORCE_TO_UNDERLYING>> for this but then you wouldn't get
5498 the other advantages of C<Perl_langinfo()>; not keeping C<LC_NUMERIC> in the C
5499 (or equivalent) locale would break a lot of CPAN, which is expecting the radix
5500 (decimal point) character to be a dot.)
5501
5502 =item c.
5503
5504 The system function they replace can have its static return buffer trashed,
5505 not only by a subsequent call to that function, but by a C<freelocale>,
5506 C<setlocale>, or other locale change.  The returned buffer of these functions
5507 is not changed until the next call to one or the other, so the buffer is never
5508 in a trashed state.
5509
5510 =item d.
5511
5512 The return buffer is per-thread, so it also is never overwritten by a call to
5513 these functions from another thread;  unlike the function it replaces.
5514
5515 =item e.
5516
5517 But most importantly, they work on systems that don't have C<nl_langinfo>, such
5518 as Windows, hence making your code more portable.  Of the fifty-some possible
5519 items specified by the POSIX 2008 standard,
5520 L<http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/langinfo.h.html>,
5521 only one is completely unimplemented, though on non-Windows platforms, another
5522 significant one is not fully implemented).  They use various techniques to
5523 recover the other items, including calling C<L<localeconv(3)>>, and
5524 C<L<strftime(3)>>, both of which are specified in C89, so should be always be
5525 available.  Later C<strftime()> versions have additional capabilities.
5526 If an item is not available on your system, this returns either the value
5527 associated with the C locale, or simply C<"">, whichever is more appropriate.
5528
5529 It is important to note that, when called with an item that is recovered by
5530 using C<localeconv>, the buffer from any previous explicit call to
5531 C<L<localeconv(3)>> will be overwritten.  But you shouldn't be using
5532 C<localeconv> anyway because it is is very much not thread-safe, and suffers
5533 from the same problems outlined in item 'b.' above for the fields it returns
5534 that are controlled by the LC_NUMERIC locale category.  Instead, avoid all of
5535 those problems by calling L</Perl_localeconv>, which is thread-safe; or by
5536 using the methods given in L<perlcall>  to call
5537 L<C<POSIX::localeconv()>|POSIX/localeconv>, which is also thread-safe.
5538
5539 =back
5540
5541 The details for those items which may deviate from what this emulation returns
5542 and what a native C<nl_langinfo()> would return are specified in
5543 L<I18N::Langinfo>.
5544
5545 When using C<Perl_langinfo8> (or plain C<Perl_langinfo>) on systems that don't
5546 have a native C<nl_langinfo()>, you must
5547
5548  #include "perl_langinfo.h"
5549
5550 before the C<perl.h> C<#include>.  You can replace your F<langinfo.h>
5551 C<#include> with this one.  (Doing it this way keeps out the symbols that plain
5552 F<langinfo.h> would try to import into the namespace for code that doesn't need
5553 it.)
5554
5555 =cut
5556
5557 */
5558
5559 const char *
5560 Perl_langinfo(const nl_item item)
5561 {
5562     return Perl_langinfo8(item, NULL);
5563 }
5564
5565 const char *
5566 Perl_langinfo8(const nl_item item, utf8ness_t * utf8ness)
5567 {
5568     dTHX;
5569     unsigned cat_index;
5570
5571     PERL_ARGS_ASSERT_PERL_LANGINFO8;
5572
5573     if (utf8ness) {     /* Assume for now */
5574         *utf8ness = UTF8NESS_IMMATERIAL;
5575     }
5576
5577     /* Find the locale category that controls the input 'item'.  If we are not
5578      * paying attention to that category, instead return a default value.  Also
5579      * return the default value if there is no way for us to figure out the
5580      * correct value.  If we have some form of nl_langinfo(), we can always
5581      * figure it out, but lacking that, there may be alternative methods that
5582      * can be used to recover most of the possible items.  Some of those
5583      * methods need libc functions, which may or may not be available.  If
5584      * unavailable, we can't compute the correct value, so must here return the
5585      * default. */
5586     switch (item) {
5587
5588       case CODESET:
5589
5590 #ifdef USE_LOCALE_CTYPE
5591
5592         cat_index = LC_CTYPE_INDEX_;
5593         break;
5594
5595 #else
5596         return C_codeset;
5597 #endif
5598 #if defined(USE_LOCALE_MESSAGES) && defined(HAS_SOME_LANGINFO)
5599
5600       case YESEXPR: case YESSTR: case NOEXPR: case NOSTR:
5601         cat_index = LC_MESSAGES_INDEX_;
5602         break;
5603 #else
5604       case YESEXPR:   return "^[+1yY]";
5605       case YESSTR:    return "yes";
5606       case NOEXPR:    return "^[-0nN]";
5607       case NOSTR:     return "no";
5608 #endif
5609
5610       case CRNCYSTR:
5611
5612 #if  defined(USE_LOCALE_MONETARY)                                   \
5613  && (defined(HAS_SOME_LANGINFO) || defined(HAS_LOCALECONV))
5614
5615         cat_index = LC_MONETARY_INDEX_;
5616         break;
5617 #else
5618         return "-";
5619 #endif
5620
5621       case RADIXCHAR:
5622
5623 #ifdef CAN_CALCULATE_RADIX
5624
5625         cat_index = LC_NUMERIC_INDEX_;
5626         break;
5627 #else
5628         return C_decimal_point;
5629 #endif
5630
5631       case THOUSEP:
5632
5633 #if  defined(USE_LOCALE_NUMERIC)                                    \
5634  && (defined(HAS_SOME_LANGINFO) || defined(HAS_LOCALECONV))
5635
5636         cat_index = LC_NUMERIC_INDEX_;
5637         break;
5638 #else
5639         return C_thousands_sep;
5640 #endif
5641
5642 /* The other possible items are all in LC_TIME. */
5643 #ifdef USE_LOCALE_TIME
5644
5645       default:
5646         cat_index = LC_TIME_INDEX_;
5647         break;
5648
5649 #endif
5650 #if ! defined(USE_LOCALE_TIME) || ! defined(HAS_SOME_LANGINFO)
5651
5652     /* If not using LC_TIME, hard code the rest.  Or, if there is no
5653      * nl_langinfo(), we use strftime() as an alternative, and it is missing
5654      * functionality to get every single one, so hard-code those */
5655
5656       case ERA: return "";  /* Unimplemented; for use with strftime() %E
5657                                modifier */
5658
5659       /* These formats are defined by C89, so we assume that strftime supports
5660        * them, and so are returned unconditionally; they may not be what the
5661        * locale actually says, but should give good enough results for someone
5662        * using them as formats (as opposed to trying to parse them to figure
5663        * out what the locale says).  The other format items are actually tested
5664        * to verify they work on the platform */
5665       case D_FMT:         return "%x";
5666       case T_FMT:         return "%X";
5667       case D_T_FMT:       return "%c";
5668
5669 #  if defined(WIN32) || ! defined(USE_LOCALE_TIME)
5670
5671       /* strftime() on Windows doesn't have the POSIX (beyond C89) extensions
5672        * that would allow it to recover these */
5673       case ERA_D_FMT:     return "%x";
5674       case ERA_T_FMT:     return "%X";
5675       case ERA_D_T_FMT:   return "%c";
5676       case ALT_DIGITS:    return "0";
5677
5678 #  endif
5679 #  ifndef USE_LOCALE_TIME
5680
5681       case T_FMT_AMPM:    return "%r";
5682       case ABDAY_1:       return "Sun";
5683       case ABDAY_2:       return "Mon";
5684       case ABDAY_3:       return "Tue";
5685       case ABDAY_4:       return "Wed";
5686       case ABDAY_5:       return "Thu";
5687       case ABDAY_6:       return "Fri";
5688       case ABDAY_7:       return "Sat";
5689       case AM_STR:        return "AM";
5690       case PM_STR:        return "PM";
5691       case ABMON_1:       return "Jan";
5692       case ABMON_2:       return "Feb";
5693       case ABMON_3:       return "Mar";
5694       case ABMON_4:       return "Apr";
5695       case ABMON_5:       return "May";
5696       case ABMON_6:       return "Jun";
5697       case ABMON_7:       return "Jul";
5698       case ABMON_8:       return "Aug";
5699       case ABMON_9:       return "Sep";
5700       case ABMON_10:      return "Oct";
5701       case ABMON_11:      return "Nov";
5702       case ABMON_12:      return "Dec";
5703       case DAY_1:         return "Sunday";
5704       case DAY_2:         return "Monday";
5705       case DAY_3:         return "Tuesday";
5706       case DAY_4:         return "Wednesday";
5707       case DAY_5:         return "Thursday";
5708       case DAY_6:         return "Friday";
5709       case DAY_7:         return "Saturday";
5710       case MON_1:         return "January";
5711       case MON_2:         return "February";
5712       case MON_3:         return "March";
5713       case MON_4:         return "April";
5714       case MON_5:         return "May";
5715       case MON_6:         return "June";
5716       case MON_7:         return "July";
5717       case MON_8:         return "August";
5718       case MON_9:         return "September";
5719       case MON_10:        return "October";
5720       case MON_11:        return "November";
5721       case MON_12:        return "December";
5722
5723 #  endif
5724 #endif
5725
5726     } /* End of switch on item */
5727
5728 #ifndef USE_LOCALE
5729
5730     Perl_croak_nocontext("panic: Unexpected nl_langinfo() item %d", item);
5731     NOT_REACHED; /* NOTREACHED */
5732     PERL_UNUSED_VAR(cat_index);
5733
5734 #else
5735
5736     return my_langinfo_i(item, cat_index, query_nominal_locale_i(cat_index),
5737                          &PL_langinfo_buf, &PL_langinfo_bufsize, utf8ness);
5738 #endif
5739
5740 }
5741
5742 char *
5743 Perl_my_strftime(pTHX_ const char *fmt, int sec, int min, int hour,
5744                        int mday, int mon, int year, int wday, int yday,
5745                        int isdst)
5746 {   /* Documented above */
5747     PERL_ARGS_ASSERT_MY_STRFTIME;
5748
5749     struct tm  mytm;
5750     ints_to_tm(&mytm, sec, min, hour, mday, mon, year, wday, yday, isdst);
5751     char * ret = strftime_tm(fmt, &mytm);
5752     return ret;
5753 }
5754
5755 SV *
5756 Perl_sv_strftime_tm(pTHX_ SV * fmt, const struct tm * mytm)
5757 {   /* Documented above */
5758     PERL_ARGS_ASSERT_SV_STRFTIME_TM;
5759
5760     utf8ness_t fmt_utf8ness = (SvUTF8(fmt) && LIKELY(! IN_BYTES))
5761                               ? UTF8NESS_YES
5762                               : UTF8NESS_UNKNOWN;
5763
5764     utf8ness_t result_utf8ness;
5765     char * retval = strftime8(SvPV_nolen(fmt),
5766                               mytm,
5767                               fmt_utf8ness,
5768                               &result_utf8ness,
5769                               true  /* calling from sv_strftime */
5770                              );
5771     SV * sv = NULL;
5772     if (retval) {
5773         STRLEN len = strlen(retval);
5774         sv = newSV(len);
5775         sv_usepvn_flags(sv, retval, len, SV_HAS_TRAILING_NUL);
5776
5777         if (result_utf8ness == UTF8NESS_YES) {
5778             SvUTF8_on(sv);
5779         }
5780     }
5781
5782     return sv;
5783 }
5784
5785 SV *
5786 Perl_sv_strftime_ints(pTHX_ SV * fmt, int sec, int min, int hour,
5787                             int mday, int mon, int year, int wday,
5788                             int yday, int isdst)
5789 {   /* Documented above */
5790     PERL_ARGS_ASSERT_SV_STRFTIME_INTS;
5791
5792     struct tm  mytm;
5793     ints_to_tm(&mytm, sec, min, hour, mday, mon, year, wday, yday, isdst);
5794     SV * ret = sv_strftime_tm(fmt, &mytm);
5795     return ret;
5796 }
5797
5798 #ifdef USE_LOCALE
5799
5800 /* There are several implementations of my_langinfo, depending on the
5801  * Configuration.  They all share the same beginning of the function */
5802 STATIC const char *
5803 S_my_langinfo_i(pTHX_
5804                 const nl_item item,           /* The item to look up */
5805                 const unsigned int cat_index, /* The locale category that
5806                                                  controls it */
5807                 /* The locale to look up 'item' in. */
5808                 const char * locale,
5809
5810                 /* Where to store the result, and where the size of that buffer
5811                  * is stored, updated on exit. retbuf_sizep may be NULL for an
5812                  * empty-on-entry, single use buffer whose size we don't need
5813                  * to keep track of */
5814                 char ** retbufp,
5815                 Size_t * retbuf_sizep,
5816
5817                 /* If not NULL, the location to store the UTF8-ness of 'item's
5818                  * value, as documented */
5819                 utf8ness_t * utf8ness)
5820 {
5821     const char * retval = NULL;
5822
5823     PERL_ARGS_ASSERT_MY_LANGINFO_I;
5824     assert(cat_index < LC_ALL_INDEX_);
5825
5826     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
5827                            "Entering my_langinfo item=%ld, using locale %s\n",
5828                            (long) item, locale));
5829 /*--------------------------------------------------------------------------*/
5830 /* Above is the common beginning to all the implementations of my_langinfo().
5831  * Below are the various completions.
5832  *
5833  * Some platforms don't deal well with non-ASCII strings in locale X when
5834  * LC_CTYPE is not in X.  (Actually it is probably when X is UTF-8 and LC_CTYPE
5835  * isn't, or vice versa).  There is explicit code to bring the categories into
5836  * sync.  This doesn't seem to be a problem with nl_langinfo(), so that
5837  * implementation doesn't currently worry about it.  But it is a problem on
5838  * Windows boxes, which don't have nl_langinfo(). */
5839
5840 /*--------------------------------------------------------------------------*/
5841 #  if defined(HAS_NL_LANGINFO) /* nl_langinfo() is available.  */
5842 #    ifdef USE_LOCALE_CTYPE
5843
5844     /* This function sorts out if things actually have to be switched or not,
5845      * for both save and restore. */
5846     const char * orig_CTYPE_locale = toggle_locale_c(LC_CTYPE, locale);
5847
5848 #    endif
5849
5850     const char * orig_switched_locale = toggle_locale_i(cat_index, locale);
5851
5852     gwLOCALE_LOCK;
5853     retval = save_to_buffer(nl_langinfo(item), retbufp, retbuf_sizep);
5854     gwLOCALE_UNLOCK;
5855
5856     if (utf8ness) {
5857         *utf8ness = get_locale_string_utf8ness_i(retval,
5858                                                  LOCALE_UTF8NESS_UNKNOWN,
5859                                                  locale, cat_index);
5860     }
5861
5862     restore_toggled_locale_i(cat_index, orig_switched_locale);
5863
5864 #    ifdef USE_LOCALE_CTYPE
5865
5866     restore_toggled_locale_c(LC_CTYPE, orig_CTYPE_locale);
5867
5868 #    endif
5869
5870     return retval;
5871 /*--------------------------------------------------------------------------*/
5872 #  else   /* Below, emulate nl_langinfo as best we can */
5873
5874     /* The other completion is where we have to emulate nl_langinfo().  There
5875      * are various possibilities depending on the Configuration */
5876
5877 #    ifdef USE_LOCALE_CTYPE
5878
5879     const char * orig_CTYPE_locale = toggle_locale_c(LC_CTYPE, locale);
5880
5881 #    endif
5882
5883     const char * orig_switched_locale = toggle_locale_i(cat_index, locale);
5884
5885     /* Here, we are in the locale we want information about */
5886
5887     /* Almost all the items will have ASCII return values.  Set that here, and
5888      * override if necessary */
5889     utf8ness_t is_utf8 = UTF8NESS_IMMATERIAL;
5890
5891     switch (item) {
5892       default:
5893         assert(item < 0);   /* Make sure using perl_langinfo.h */
5894         retval = "";
5895         break;
5896
5897       case RADIXCHAR:
5898
5899 #    if      defined(HAS_SNPRINTF)                                          \
5900        && (! defined(HAS_LOCALECONV) || defined(TS_W32_BROKEN_LOCALECONV))
5901
5902         {
5903             /* snprintf() can be used to find the radix character by outputting
5904              * a known simple floating point number to a buffer, and parsing
5905              * it, inferring the radix as the bytes separating the integer and
5906              * fractional parts.  But localeconv() is more direct, not
5907              * requiring inference, so use it instead of the code just below,
5908              * if (likely) it is available and works ok */
5909
5910             char * floatbuf = NULL;
5911             const Size_t initial_size = 10;
5912
5913             Newx(floatbuf, initial_size, char);
5914
5915             /* 1.5 is exactly representable on binary computers */
5916             Size_t needed_size = snprintf(floatbuf, initial_size, "%.1f", 1.5);
5917
5918             /* If our guess wasn't big enough, increase and try again, based on
5919              * the real number that snprintf() is supposed to return */
5920             if (UNLIKELY(needed_size >= initial_size)) {
5921                 needed_size++;  /* insurance */
5922                 Renew(floatbuf, needed_size, char);
5923                 Size_t new_needed = snprintf(floatbuf, needed_size, "%.1f", 1.5);
5924                 assert(new_needed <= needed_size);
5925                 needed_size = new_needed;
5926             }
5927
5928             char * s = floatbuf;
5929             char * e = floatbuf + needed_size;
5930
5931             /* Find the '1' */
5932             while (s < e && *s != '1') {
5933                 s++;
5934             }
5935
5936             if (LIKELY(s < e)) {
5937                 s++;
5938             }
5939
5940             /* Find the '5' */
5941             char * item_start = s;
5942             while (s < e && *s != '5') {
5943                 s++;
5944             }
5945
5946             /* Everything in between is the radix string */
5947             if (LIKELY(s < e)) {
5948                 *s = '\0';
5949                 retval = save_to_buffer(item_start, retbufp, retbuf_sizep);
5950                 Safefree(floatbuf);
5951
5952                 if (utf8ness) {
5953                     is_utf8 = get_locale_string_utf8ness_i(retval,
5954                                                         LOCALE_UTF8NESS_UNKNOWN,
5955                                                         locale, cat_index);
5956                 }
5957
5958                 break;
5959             }
5960
5961             Safefree(floatbuf);
5962         }
5963
5964 #      ifdef HAS_LOCALECONV /* snprintf() failed; drop down to use
5965                                localeconv() */
5966
5967         /* FALLTHROUGH */
5968
5969 #      else                      /* snprintf() failed and no localeconv() */
5970
5971         retval = C_decimal_point;
5972         break;
5973
5974 #      endif
5975 #    endif
5976 #    ifdef HAS_LOCALECONV
5977
5978     /* These items are available from localeconv().  (To avoid using
5979      * TS_W32_BROKEN_LOCALECONV, one could use GetNumberFormat and
5980      * GetCurrencyFormat; patches welcome) */
5981
5982 #      define P_CS_PRECEDES    "p_cs_precedes"
5983 #      define CURRENCY_SYMBOL  "currency_symbol"
5984
5985    /* case RADIXCHAR:   // May drop down to here in some configurations */
5986       case THOUSEP:
5987       case CRNCYSTR:
5988        {
5989
5990         /* The hash gets populated with just the field(s) related to 'item'. */
5991         HV * result_hv = my_localeconv(item);
5992
5993         SV* string;
5994         if (item != CRNCYSTR) {
5995
5996             /* These items have been populated with just one key => value */
5997             (void) hv_iterinit(result_hv);
5998             HE * entry = hv_iternext(result_hv);
5999             string = hv_iterval(result_hv, entry);
6000         }
6001         else {
6002
6003             /* But CRNCYSTR localeconv() returns a slightly different value
6004              * than the nl_langinfo() API calls for, so have to modify this one
6005              * to conform.  We need another value from localeconv() to know
6006              * what to change it to.  my_localeconv() has populated the hash
6007              * with exactly both fields.  Delete this one, leaving just the
6008              * CRNCYSTR one in the hash */
6009             SV* precedes = hv_delete(result_hv,
6010                                      P_CS_PRECEDES, STRLENs(P_CS_PRECEDES),
6011                                      0);
6012             if (! precedes) {
6013                 locale_panic_("my_localeconv() unexpectedly didn't return"
6014                               " a value for " P_CS_PRECEDES);
6015             }
6016
6017             /* The modification is to prefix the localeconv() return with a
6018              * single byte, calculated as follows: */
6019             char prefix = (LIKELY(SvIV(precedes) != -1))
6020                           ? ((precedes != 0) ?  '-' : '+')
6021
6022                             /* khw couldn't find any documentation that
6023                              * CHAR_MAX (which we modify to -1) is the signal,
6024                              * but cygwin uses it thusly, and it makes sense
6025                              * given that CHAR_MAX indicates the value isn't
6026                              * used, so it neither precedes nor succeeds */
6027                           : '.';
6028
6029             /* Now get CRNCYSTR */
6030             (void) hv_iterinit(result_hv);
6031             HE * entry = hv_iternext(result_hv);
6032             string = hv_iterval(result_hv, entry);
6033
6034             /* And perform the modification */
6035             Perl_sv_setpvf(aTHX_ string, "%c%s", prefix, SvPV_nolen(string));
6036         }
6037
6038         /* Here, 'string' contains the value we want to return */
6039         retval = save_to_buffer(SvPV_nolen(string), retbufp, retbuf_sizep);
6040
6041         if (utf8ness) {
6042             is_utf8 = (SvUTF8(string))
6043                       ? UTF8NESS_YES
6044                       : (is_utf8_invariant_string( (U8 *) retval,
6045                                                   strlen(retval)))
6046                         ? UTF8NESS_IMMATERIAL
6047                         : UTF8NESS_NO;
6048         }
6049
6050         break;
6051
6052        }
6053
6054 #    endif  /* Some form of localeconv */
6055 #    ifdef HAS_STRFTIME
6056
6057       /* These formats are only available in later strftime's */
6058       case ERA_D_FMT: case ERA_T_FMT: case ERA_D_T_FMT: case T_FMT_AMPM:
6059
6060       /* The rest can be gotten from most versions of strftime(). */
6061       case ABDAY_1: case ABDAY_2: case ABDAY_3:
6062       case ABDAY_4: case ABDAY_5: case ABDAY_6: case ABDAY_7:
6063       case ALT_DIGITS:
6064       case AM_STR: case PM_STR:
6065       case ABMON_1: case ABMON_2: case ABMON_3: case ABMON_4:
6066       case ABMON_5: case ABMON_6: case ABMON_7: case ABMON_8:
6067       case ABMON_9: case ABMON_10: case ABMON_11: case ABMON_12:
6068       case DAY_1: case DAY_2: case DAY_3: case DAY_4:
6069       case DAY_5: case DAY_6: case DAY_7:
6070       case MON_1: case MON_2: case MON_3: case MON_4:
6071       case MON_5: case MON_6: case MON_7: case MON_8:
6072       case MON_9: case MON_10: case MON_11: case MON_12:
6073         {
6074             const char * format;
6075             bool return_format = FALSE;
6076             int mon = 0;
6077             int mday = 1;
6078             int hour = 6;
6079
6080             GCC_DIAG_IGNORE_STMT(-Wimplicit-fallthrough);
6081
6082             switch (item) {
6083               default:
6084                 locale_panic_(Perl_form(aTHX_ "switch case: %d problem", item));
6085                 NOT_REACHED; /* NOTREACHED */
6086
6087               case PM_STR: hour = 18;
6088               case AM_STR:
6089                 format = "%p";
6090                 break;
6091               case ABDAY_7: mday++;
6092               case ABDAY_6: mday++;
6093               case ABDAY_5: mday++;
6094               case ABDAY_4: mday++;
6095               case ABDAY_3: mday++;
6096               case ABDAY_2: mday++;
6097               case ABDAY_1:
6098                 format = "%a";
6099                 break;
6100               case DAY_7: mday++;
6101               case DAY_6: mday++;
6102               case DAY_5: mday++;
6103               case DAY_4: mday++;
6104               case DAY_3: mday++;
6105               case DAY_2: mday++;
6106               case DAY_1:
6107                 format = "%A";
6108                 break;
6109               case ABMON_12: mon++;
6110               case ABMON_11: mon++;
6111               case ABMON_10: mon++;
6112               case ABMON_9:  mon++;
6113               case ABMON_8:  mon++;
6114               case ABMON_7:  mon++;
6115               case ABMON_6:  mon++;
6116               case ABMON_5:  mon++;
6117               case ABMON_4:  mon++;
6118               case ABMON_3:  mon++;
6119               case ABMON_2:  mon++;
6120               case ABMON_1:
6121                 format = "%b";
6122                 break;
6123               case MON_12: mon++;
6124               case MON_11: mon++;
6125               case MON_10: mon++;
6126               case MON_9:  mon++;
6127               case MON_8:  mon++;
6128               case MON_7:  mon++;
6129               case MON_6:  mon++;
6130               case MON_5:  mon++;
6131               case MON_4:  mon++;
6132               case MON_3:  mon++;
6133               case MON_2:  mon++;
6134               case MON_1:
6135                 format = "%B";
6136                 break;
6137               case T_FMT_AMPM:
6138                 format = "%r";
6139                 return_format = TRUE;
6140                 break;
6141               case ERA_D_FMT:
6142                 format = "%Ex";
6143                 return_format = TRUE;
6144                 break;
6145               case ERA_T_FMT:
6146                 format = "%EX";
6147                 return_format = TRUE;
6148                 break;
6149               case ERA_D_T_FMT:
6150                 format = "%Ec";
6151                 return_format = TRUE;
6152                 break;
6153               case ALT_DIGITS:
6154                 format = "%Ow"; /* Find the alternate digit for 0 */
6155                 break;
6156             }
6157
6158             GCC_DIAG_RESTORE_STMT;
6159
6160             /* The year was deliberately chosen so that January 1 is on the
6161              * first day of the week.  Since we're only getting one thing at a
6162              * time, it all works */
6163             struct tm  mytm;
6164             ints_to_tm(&mytm, 30, 30, hour, mday, mon, 2011, 0, 0, 0);
6165             char * temp;
6166             if (utf8ness) {
6167                 temp = strftime8(format,
6168                                  &mytm,
6169                                  UTF8NESS_IMMATERIAL, /* All possible formats
6170                                                          specified above are
6171                                                          entirely ASCII */
6172                                  &is_utf8,
6173                                  false      /* not calling from sv_strftime */
6174                                 );
6175             }
6176             else {
6177                 temp = strftime_tm(format, &mytm);
6178             }
6179
6180             retval = save_to_buffer(temp, retbufp, retbuf_sizep);
6181             Safefree(temp);
6182
6183             /* If the item is 'ALT_DIGITS', '*retbuf' contains the alternate
6184              * format for wday 0.  If the value is the same as the normal 0,
6185              * there isn't an alternate, so clear the buffer.
6186              *
6187              * (wday was chosen because its range is all a single digit.
6188              * Things like tm_sec have two digits as the minimum: '00'.) */
6189             if (item == ALT_DIGITS && strEQ(*retbufp, "0")) {
6190                 retval = "";
6191                 break;
6192             }
6193
6194             /* ALT_DIGITS is problematic.  Experiments on it showed that
6195              * strftime() did not always work properly when going from alt-9 to
6196              * alt-10.  Only a few locales have this item defined, and in all
6197              * of them on Linux that khw was able to find, nl_langinfo() merely
6198              * returned the alt-0 character, possibly doubled.  Most Unicode
6199              * digits are in blocks of 10 consecutive code points, so that is
6200              * sufficient information for such scripts, as we can infer alt-1,
6201              * alt-2, ....  But for a Japanese locale, a CJK ideographic 0 is
6202              * returned, and the CJK digits are not in code point order, so you
6203              * can't really infer anything.  The localedef for this locale did
6204              * specify the succeeding digits, so that strftime() works properly
6205              * on them, without needing to infer anything.  But the
6206              * nl_langinfo() return did not give sufficient information for the
6207              * caller to understand what's going on.  So until there is
6208              * evidence that it should work differently, this returns the alt-0
6209              * string for ALT_DIGITS. */
6210
6211             if (return_format) {
6212
6213                 /* If to return the format, not the value, overwrite the buffer
6214                  * with it.  But some strftime()s will keep the original format
6215                  * if illegal, so change those to "" */
6216                 if (strEQ(*retbufp, format)) {
6217                     retval = "";
6218                 }
6219                 else {
6220                     retval = format;
6221                 }
6222
6223                 /* A format is always in ASCII */
6224                 is_utf8 = UTF8NESS_IMMATERIAL;
6225             }
6226
6227             break;
6228         }
6229
6230 #    endif
6231 #    ifdef USE_LOCALE_CTYPE
6232
6233       case CODESET:
6234
6235         /* The trivial case */
6236         if (isNAME_C_OR_POSIX(locale)) {
6237             retval = C_codeset;
6238             break;
6239         }
6240
6241 #      ifdef WIN32
6242
6243         /* This function retrieves the code page.  It is subject to change, but
6244          * is documented and has been stable for many releases */
6245         UINT ___lc_codepage_func(void);
6246
6247 #        ifndef WIN32_USE_FAKE_OLD_MINGW_LOCALES
6248
6249         retval = save_to_buffer(Perl_form(aTHX_ "%d", ___lc_codepage_func()),
6250                                 retbufp, retbuf_sizep);
6251 #        else
6252
6253         retval = save_to_buffer(nl_langinfo(CODESET),
6254                                 retbufp, retbuf_sizep);
6255 #        endif
6256
6257         DEBUG_Lv(PerlIO_printf(Perl_debug_log, "locale='%s' cp=%s\n",
6258                                                locale, retval));
6259         break;
6260
6261 #      else
6262
6263         /* The codeset is important, but khw did not figure out a way for it to
6264          * be retrieved on non-Windows boxes without nl_langinfo().  But even
6265          * if we can't get it directly, we can usually determine if it is a
6266          * UTF-8 locale or not.  If it is UTF-8, we (correctly) use that for
6267          * the code set. */
6268
6269 #        if defined(HAS_MBTOWC) || defined(HAS_MBRTOWC)
6270
6271         /* If libc mbtowc() evaluates the bytes that form the REPLACEMENT
6272          * CHARACTER as that Unicode code point, this has to be a UTF-8 locale.
6273          * */
6274         wchar_t wc = 0;
6275         (void) Perl_mbtowc_(aTHX_ NULL, NULL, 0);/* Reset shift state */
6276         int mbtowc_ret = Perl_mbtowc_(aTHX_ &wc,
6277                                       STR_WITH_LEN(REPLACEMENT_CHARACTER_UTF8));
6278         if (mbtowc_ret >= 0 && wc == UNICODE_REPLACEMENT) {
6279             DEBUG_Lv(PerlIO_printf(Perl_debug_log,
6280                                    "mbtowc returned REPLACEMENT\n"));
6281             retval = "UTF-8";
6282             break;
6283         }
6284
6285         /* Here, it isn't a UTF-8 locale. */
6286
6287 #        else   /* mbtowc() is not available.  The chances of this code getting
6288                    compiled are very small, as it is a C99 required function,
6289                    and we are now requiring C99; perhaps if it is a defective
6290                    implementation.  But if so, there are other libc functions
6291                    that could be used instead. */
6292
6293         /* Sling together several possibilities, depending on platform
6294          * capabilities and what we found.
6295          *
6296          * For non-English locales or non-dollar currency locales, we likely
6297          * will find out whether a locale is UTF-8 or not */
6298
6299         utf8ness_t is_utf8 = UTF8NESS_UNKNOWN;
6300         const char * scratch_buf = NULL;
6301
6302 #          if defined(USE_LOCALE_MONETARY) && defined(HAS_LOCALECONV)
6303 #            define LANGINFO_RECURSED_MONETARY  0x1
6304 #            define LANGINFO_RECURSED_TIME      0x2
6305
6306         /* Can't use this method unless localeconv() is available, as that's
6307          * the way we find out the currency symbol.
6308          *
6309          * First try looking at the currency symbol (via a recursive call) to
6310          * see if it disambiguates things.  Often that will be in the native
6311          * script, and if the symbol isn't legal UTF-8, we know that the locale
6312          * isn't either.
6313          *
6314          * The recursion calls my_localeconv() to find CRNCYSTR, and that can
6315          * call is_locale_utf8() which will call my_langinfo(CODESET) which
6316          * will get to here again, ad infinitum.  The guard prevents that.
6317          */
6318         if ((PL_langinfo_recursed & LANGINFO_RECURSED_MONETARY) == 0) {
6319             PL_langinfo_recursed |= LANGINFO_RECURSED_MONETARY;
6320             (void) my_langinfo_c(CRNCYSTR, LC_MONETARY, locale, &scratch_buf,
6321                                  NULL, &is_utf8);
6322             PL_langinfo_recursed &= ~LANGINFO_RECURSED_MONETARY;
6323         }
6324
6325         Safefree(scratch_buf);
6326
6327 #          endif
6328 #          ifdef USE_LOCALE_TIME
6329
6330         /* If we have ruled out being UTF-8, no point in checking further. */
6331         if (   is_utf8 != UTF8NESS_NO
6332             && (PL_langinfo_recursed & LANGINFO_RECURSED_TIME) == 0)
6333         {
6334             /* But otherwise do check more.  This is done even if the currency
6335              * symbol looks to be UTF-8, just in case that's a false positive.
6336              *
6337              * Look at the LC_TIME entries, like the names of the months or
6338              * weekdays.  We quit at the first one that is illegal UTF-8
6339              *
6340              * The recursion guard is because the recursed my_langinfo_c() will
6341              * call strftime8() to find the LC_TIME value passed to it, and
6342              * that will call my_langinfo(CODESET) for non-ASCII returns,
6343              * which will get here again, ad infinitum
6344              */
6345
6346             utf8ness_t this_is_utf8 = UTF8NESS_UNKNOWN;
6347             const int times[] = {
6348                 DAY_1, DAY_2, DAY_3, DAY_4, DAY_5, DAY_6, DAY_7,
6349                 MON_1, MON_2, MON_3, MON_4, MON_5, MON_6, MON_7, MON_8,
6350                                             MON_9, MON_10, MON_11, MON_12,
6351                 ALT_DIGITS, AM_STR, PM_STR,
6352                 ABDAY_1, ABDAY_2, ABDAY_3, ABDAY_4, ABDAY_5, ABDAY_6,
6353                                                              ABDAY_7,
6354                 ABMON_1, ABMON_2, ABMON_3, ABMON_4, ABMON_5, ABMON_6,
6355                 ABMON_7, ABMON_8, ABMON_9, ABMON_10, ABMON_11, ABMON_12
6356             };
6357
6358             /* The code in the recursive call can handle switching the locales,
6359              * but by doing it here, we avoid switching each iteration of the
6360              * loop */
6361             const char * orig_TIME_locale = toggle_locale_c(LC_TIME, locale);
6362
6363             PL_langinfo_recursed |= LANGINFO_RECURSED_TIME;
6364             for (PERL_UINT_FAST8_T i = 0; i < C_ARRAY_LENGTH(times); i++) {
6365                 scratch_buf = NULL;
6366                 (void) my_langinfo_c(times[i], LC_TIME, locale, &scratch_buf,
6367                                      NULL, &this_is_utf8);
6368                 Safefree(scratch_buf);
6369                 if (this_is_utf8 == UTF8NESS_NO) {
6370                     is_utf8 = UTF8NESS_NO;
6371                     break;
6372                 }
6373
6374                 if (this_is_utf8 == UTF8NESS_YES) {
6375                     is_utf8 = UTF8NESS_YES;
6376                 }
6377             }
6378             PL_langinfo_recursed &= ~LANGINFO_RECURSED_TIME;
6379
6380             /* Here we have gone through all the LC_TIME elements.  is_utf8 has
6381              * been set as follows:
6382              *      UTF8NESS_NO           If at least one isn't legal UTF-8
6383              *      UTF8NESS_IMMMATERIAL  If all are ASCII
6384              *      UTF8NESS_YES          If all are legal UTF-8 (including
6385              *                            ASCII), and at least one isn't
6386              *                            ASCII. */
6387
6388             restore_toggled_locale_c(LC_TIME, orig_TIME_locale);
6389         }
6390
6391 #          endif    /* LC_TIME */
6392
6393         /* If nothing examined above rules out it being UTF-8, and at least one
6394          * thing fits as UTF-8 (and not plain ASCII), assume the codeset is
6395          * UTF-8. */
6396         if (is_utf8 == UTF8NESS_YES) {
6397             retval = "UTF-8";
6398             break;
6399         }
6400
6401         /* Here, nothing examined indicates that the codeset is UTF-8.  But
6402          * what is it?  The other locale categories are not likely to be of
6403          * further help:
6404          *
6405          * LC_NUMERIC   Only a few locales in the world have a non-ASCII radix
6406          *              or group separator.
6407          * LC_CTYPE     This code wouldn't be compiled if mbtowc() existed and
6408          *              was reliable.  This is unlikely in C99.  There are
6409          *              other functions that could be used instead, but are
6410          *              they going to exist, and be able to distinguish between
6411          *              UTF-8 and 8859-1?  Deal with this only if it becomes
6412          *              necessary.
6413          * LC_MESSAGES  The strings returned from strerror() would seem likely
6414          *              candidates, but experience has shown that many systems
6415          *              don't actually have translations installed for them.
6416          *              They are instead always in English, so everything in
6417          *              them is ASCII, which is of no help to us.  A Configure
6418          *              probe could possibly be written to see if this platform
6419          *              has non-ASCII error messages.  But again, wait until it
6420          *              turns out to be an actual problem. */
6421
6422 #        endif    /* ! mbtowc() */
6423
6424         /* Rejoin the mbtowc available/not-available cases.
6425          *
6426          * We got here only because we haven't been able to find the codeset.
6427          * The only other option khw could think of is to see if the codeset is
6428          * part of the locale name.  This is very less than ideal; often there
6429          * is no code set in the name; and at other times they even lie.
6430          *
6431          * But there is an XPG standard syntax, which many locales follow:
6432          *
6433          * language[_territory[.codeset]][@modifier]
6434          *
6435          * So we take the part between the dot and any '@' */
6436         retval = (const char *) strchr(locale, '.');
6437         if (! retval) {
6438             retval = "";  /* Alas, no dot */
6439             break;
6440         }
6441
6442         /* Don't include the dot */
6443         retval++;
6444
6445         /* And stop before any '@' */
6446         const char * modifier = strchr(retval, '@');
6447         if (modifier) {
6448             char * code_set_name;
6449             const Size_t name_len = modifier - retval;
6450             Newx(code_set_name, name_len + 1, char);         /* +1 for NUL */
6451             my_strlcpy(code_set_name, retval, name_len + 1);
6452             SAVEFREEPV(code_set_name);
6453             retval = code_set_name;
6454         }
6455
6456 #        if defined(HAS_MBTOWC) || defined(HAS_MBRTOWC)
6457
6458         /* When these functions, are available, they were tried earlier and
6459          * indicated that the locale did not act like a proper UTF-8 one.  So
6460          * if it claims to be UTF-8, it is a lie */
6461         if (is_codeset_name_UTF8(retval)) {
6462             retval = "";
6463             break;
6464         }
6465
6466 #        endif
6467
6468         /* Otherwise the code set name is considered to be everything between
6469          * the dot and the '@' */
6470         retval = save_to_buffer(retval, retbufp, retbuf_sizep);
6471
6472         break;
6473
6474 #      endif    /* ! WIN32 */
6475 #    endif      /* USE_LOCALE_CTYPE */
6476
6477     } /* Giant switch() of nl_langinfo() items */
6478
6479     restore_toggled_locale_i(cat_index, orig_switched_locale);
6480
6481 #    ifdef USE_LOCALE_CTYPE
6482     restore_toggled_locale_c(LC_CTYPE, orig_CTYPE_locale);
6483 #    endif
6484
6485     if (utf8ness) {
6486         *utf8ness = is_utf8;
6487     }
6488
6489     return retval;
6490
6491 #  endif    /* All the implementations of my_langinfo() */
6492
6493 /*--------------------------------------------------------------------------*/
6494
6495 }   /* my_langinfo() */
6496
6497 #endif      /* USE_LOCALE */
6498
6499 /*
6500 =for apidoc_section $time
6501 =for apidoc      sv_strftime_tm
6502 =for apidoc_item sv_strftime_ints
6503 =for apidoc_item my_strftime
6504
6505 These implement the libc strftime(), but with a different API so that the return
6506 value is a pointer to the formatted result (which MUST be arranged to be FREED
6507 BY THE CALLER).  This allows these functions to increase the buffer size as
6508 needed, so that the caller doesn't have to worry about that.
6509
6510 On failure they return NULL, and set errno to C<EINVAL>.
6511
6512 C<sv_strftime_tm> and C<sv_strftime_ints> are preferred, as they transparently
6513 handle the UTF-8ness of the current locale, the input C<fmt>, and the returned
6514 result.  Only if the current C<LC_TIME> locale is a UTF-8 one (and S<C<use
6515 bytes>> is not in effect) will the result be marked as UTF-8.  These differ
6516 only in the form of their inputs.  C<sv_strftime_tm> takes a filled-in
6517 S<C<struct tm>> parameter.  C<sv_strftime_ints> takes a bunch of integer
6518 parameters that together completely define a given time.
6519
6520 C<my_strftime> is kept for backwards compatibility.  Knowing if the result
6521 should be considered UTF-8 or not requires significant extra logic.
6522
6523 Note that C<yday> and C<wday> effectively are ignored by C<sv_strftime_ints>
6524 and C<my_strftime>, as mini_mktime() overwrites them
6525
6526 Also note that all three functions are always executed in the underlying
6527 C<LC_TIME> locale of the program, giving results based on that locale.
6528
6529 =cut
6530  */
6531
6532 STATIC void
6533 S_ints_to_tm(pTHX_ struct tm * mytm,
6534                    int sec, int min, int hour, int mday, int mon, int year,
6535                    int wday, int yday, int isdst)
6536 {
6537     /* Create a struct tm structure from the input time-related integer
6538      * variables */
6539
6540     /* Override with the passed-in values */
6541     mytm->tm_sec = sec;
6542     mytm->tm_min = min;
6543     mytm->tm_hour = hour;
6544     mytm->tm_mday = mday;
6545     mytm->tm_mon = mon;
6546     mytm->tm_year = year;
6547     mytm->tm_wday = wday;
6548     mytm->tm_yday = yday;
6549     mytm->tm_isdst = isdst;
6550     mini_mktime(mytm);
6551
6552     /* use libc to get the values for tm_gmtoff and tm_zone on platforms that
6553      * have them [perl #18238] */
6554 #if  defined(HAS_MKTIME)                                      \
6555  && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
6556     struct tm mytm2 = *mytm;
6557     MKTIME_LOCK;
6558     mktime(&mytm2);
6559     MKTIME_UNLOCK;
6560 #  ifdef HAS_TM_TM_GMTOFF
6561     mytm->tm_gmtoff = mytm2.tm_gmtoff;
6562 #  endif
6563 #  ifdef HAS_TM_TM_ZONE
6564     mytm->tm_zone = mytm2.tm_zone;
6565 #  endif
6566 #endif
6567
6568     return;
6569 }
6570
6571 STATIC char *
6572 S_strftime_tm(pTHX_ const char *fmt, const struct tm *mytm)
6573 {
6574     PERL_ARGS_ASSERT_STRFTIME_TM;
6575
6576     /* Execute strftime() based on the input struct tm */
6577
6578     /* An empty format yields an empty result */
6579     const int fmtlen = strlen(fmt);
6580     if (fmtlen == 0) {
6581         char *ret;
6582         Newxz (ret, 1, char);
6583         return ret;
6584     }
6585
6586 #ifndef HAS_STRFTIME
6587     Perl_croak(aTHX_ "panic: no strftime");
6588 #else
6589 #  if defined(USE_LOCALE_CTYPE) && defined(USE_LOCALE_TIME)
6590
6591     const char * orig_CTYPE_LOCALE = toggle_locale_c(LC_CTYPE,
6592                                                      querylocale_c(LC_TIME));
6593 #  endif
6594
6595     /* Guess an initial size for the returned string based on an expansion
6596      * factor of the input format, but with a minimum that should handle most
6597      * common cases.  If this guess is too small, we will try again with a
6598      * larger one */
6599     int bufsize = MAX(fmtlen * 2, 64);
6600
6601     char *buf = NULL;   /* Makes Renew() act as Newx() on the first iteration */
6602     do {
6603         Renew(buf, bufsize, char);
6604
6605         /* allowing user-supplied (rather than literal) formats is normally
6606          * frowned upon as a potential security risk; but this is part of the
6607          * API so we have to allow it (and the available formats have a much
6608          * lower chance of doing something bad than the ones for printf etc. */
6609         GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
6610
6611         STRFTIME_LOCK;
6612         int len = strftime(buf, bufsize, fmt, mytm);
6613         STRFTIME_UNLOCK;
6614
6615         GCC_DIAG_RESTORE_STMT;
6616
6617         /* A non-zero return indicates success.  But to make sure we're not
6618          * dealing with some rogue strftime that returns how much space it
6619          * needs instead of 0 when there isn't enough, check that the return
6620          * indicates we have at least one byte of spare space (which will be
6621          * used for the terminating NUL). */
6622         if (inRANGE(len, 1, bufsize - 1)) {
6623             goto strftime_return;
6624         }
6625
6626         /* There are several possible reasons for a 0 return code for a
6627          * non-empty format, and they are not trivial to tease apart.  This
6628          * issue is a known bug in the strftime() API.  What we do to cope is
6629          * to assume that the reason is not enough space in the buffer, so
6630          * increase it and try again. */
6631         bufsize *= 2;
6632
6633         /* But don't just keep increasing the size indefinitely.  Stop when it
6634          * becomes obvious that the reason for failure is something besides not
6635          * enough space.  The most likely largest expanding format is %c.  On
6636          * khw's Linux box, the maximum result of this is 67 characters, in the
6637          * km_KH locale.  If a new script comes along that uses 4 UTF-8 bytes
6638          * per character, and with a similar expansion factor, that would be a
6639          * 268:2 byte ratio, or a bit more than 128:1 = 2**7:1.  Some strftime
6640          * implementations allow you to say %1000c to pad to 1000 bytes.  This
6641          * shows that it is impossible to implement this without a heuristic
6642          * (which can fail).  But it indicates we need to be generous in the
6643          * upper limit before failing.  The previous heuristic used was too
6644          * stingy.  Since the size doubles per iteration, it doesn't take many
6645          * to reach the limit */
6646     } while (bufsize < ((1 << 11) + 1) * fmtlen);
6647
6648     /* Here, strftime() returned 0, and it likely wasn't for lack of space.
6649      * There are two possible reasons:
6650      *
6651      * First is that the result is legitimately 0 length.  This can happen
6652      * when the format is precisely "%p".  That is the only documented format
6653      * that can have an empty result. */
6654     if (strEQ(fmt, "%p")) {
6655         Renew(buf, 1, char);
6656         *buf = '\0';
6657         goto strftime_return;
6658     }
6659
6660     /* The other reason is that the format string is malformed.  Probably it is
6661      * that the string is syntactically invalid for the locale.  On some
6662      * platforms an invalid conversion specifier '%?' (for all illegal '?') is
6663      * treated as a literal, but others may fail when '?' is illegal */
6664     Safefree(buf);
6665     SET_EINVAL;
6666     buf = NULL;
6667
6668   strftime_return:
6669
6670 #  if defined(USE_LOCALE_CTYPE) && defined(USE_LOCALE_TIME)
6671
6672     restore_toggled_locale_c(LC_CTYPE, orig_CTYPE_LOCALE);
6673
6674 #  endif
6675
6676     return buf;
6677
6678 #endif
6679
6680 }
6681
6682 STATIC char *
6683 S_strftime8(pTHX_ const char * fmt,
6684                   const struct tm * mytm,
6685                   const utf8ness_t fmt_utf8ness,
6686                   utf8ness_t * result_utf8ness,
6687                   const bool came_from_sv)
6688 {
6689     PERL_ARGS_ASSERT_STRFTIME8;
6690
6691     /* Wrap strftime_tm, taking into account the input and output UTF-8ness */
6692
6693 #ifdef USE_LOCALE_TIME
6694 #  define INDEX_TO_USE  LC_TIME_INDEX_
6695
6696     const char * locale = querylocale_c(LC_TIME);
6697     locale_utf8ness_t locale_utf8ness = LOCALE_UTF8NESS_UNKNOWN;
6698
6699 #else
6700 #  define INDEX_TO_USE  LC_ALL_INDEX_   /* Effectively out of bounds */
6701
6702     const char * locale = "C";
6703     locale_utf8ness_t locale_utf8ness = LOCALE_NOT_UTF8;
6704
6705 #endif
6706
6707     switch (fmt_utf8ness) {
6708       case UTF8NESS_IMMATERIAL:
6709         break;
6710
6711       case UTF8NESS_NO: /* Known not to be UTF-8; must not be UTF-8 locale */
6712         if (is_locale_utf8(locale)) {
6713             SET_EINVAL;
6714             return NULL;
6715         }
6716
6717         locale_utf8ness = LOCALE_NOT_UTF8;
6718         break;
6719
6720       case UTF8NESS_YES:    /* Known to be UTF-8; must be UTF-8 locale if can't
6721                                downgrade.  But downgrading assumes the locale
6722                                is latin 1.  Maybe just fail XXX */
6723         if (! is_locale_utf8(locale)) {
6724             locale_utf8ness = LOCALE_NOT_UTF8;
6725
6726             bool is_utf8 = true;
6727             Size_t fmt_len = strlen(fmt);
6728             fmt = (char *) bytes_from_utf8((U8 *) fmt, &fmt_len, &is_utf8);
6729             if (is_utf8) {
6730                 SET_EINVAL;
6731                 return NULL;
6732             }
6733
6734             SAVEFREEPV(fmt);
6735         }
6736         else {
6737             locale_utf8ness = LOCALE_IS_UTF8;
6738         }
6739
6740         break;
6741
6742       case UTF8NESS_UNKNOWN:
6743         if (! is_locale_utf8(locale)) {
6744             locale_utf8ness = LOCALE_NOT_UTF8;
6745         }
6746         else {
6747             locale_utf8ness = LOCALE_IS_UTF8;
6748             if (came_from_sv) {
6749
6750                 /* Upgrade 'fmt' to UTF-8 for a UTF-8 locale.  Otherwise the
6751                  * locale would find any UTF-8 variant characters to be
6752                  * malformed */
6753                 Size_t fmt_len = strlen(fmt);
6754                 fmt = (char *) bytes_to_utf8((U8 *) fmt, &fmt_len);
6755                 SAVEFREEPV(fmt);
6756             }
6757         }
6758
6759         break;
6760     }
6761
6762     char * retval = strftime_tm(fmt, mytm);
6763     *result_utf8ness = get_locale_string_utf8ness_i(retval,
6764                                                     locale_utf8ness,
6765                                                     locale,
6766                                                     INDEX_TO_USE);
6767     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
6768                           "fmt=%s, retval=%s; utf8ness=%d",
6769                           fmt,
6770                           ((is_utf8_string((U8 *) retval, 0))
6771                            ? retval
6772                            :_byte_dump_string((U8 *) retval, strlen(retval),0)),
6773                           *result_utf8ness));
6774     return retval;
6775
6776 #undef INDEX_TO_USE
6777
6778 }
6779
6780 #ifdef USE_LOCALE
6781
6782 STATIC void
6783 S_give_perl_locale_control(pTHX_
6784 #  ifdef LC_ALL
6785                            const char * lc_all_string,
6786 #  else
6787                            const char ** locales,
6788 #  endif
6789                            const line_t caller_line)
6790 {
6791     PERL_UNUSED_ARG(caller_line);
6792
6793     /* This is called when the program is in the global locale and are
6794      * switching to per-thread (if available).  And it is called at
6795      * initialization time to do the same.
6796      */
6797
6798 #  if defined(WIN32) && defined(USE_THREAD_SAFE_LOCALE)
6799
6800     /* On Windows, convert to per-thread behavior.  This isn't necessary in
6801      * POSIX 2008, as the conversion gets done automatically in the
6802      * void_setlocale_i() calls below. */
6803     if (_configthreadlocale(_ENABLE_PER_THREAD_LOCALE) == -1) {
6804         locale_panic_("_configthreadlocale returned an error");
6805     }
6806
6807 #  endif
6808 #  if ! defined(USE_THREAD_SAFE_LOCALE)                               \
6809    && ! defined(USE_POSIX_2008_LOCALE)
6810 #    if defined(LC_ALL)
6811     PERL_UNUSED_ARG(lc_all_string);
6812 #    else
6813     PERL_UNUSED_ARG(locales);
6814 #    endif
6815 #  else
6816
6817     /* This platform has per-thread locale handling.  Do the conversion. */
6818
6819 #    if defined(LC_ALL)
6820
6821     void_setlocale_c_with_caller(LC_ALL, lc_all_string, __FILE__, caller_line);
6822
6823 #    else
6824
6825     for (unsigned int i = 0; i < LC_ALL_INDEX_; i++) {
6826         void_setlocale_i_with_caller(i, locales[i], __FILE__, caller_line);
6827     }
6828
6829 #    endif
6830 #  endif
6831
6832     /* Finally, update our remaining records.  'true' => force recalculation.
6833      * This is needed because we don't know what's happened while Perl hasn't
6834      * had control, so we need to figure out the current state */
6835
6836 #  if defined(LC_ALL)
6837
6838     new_LC_ALL(lc_all_string, true);
6839
6840 #    else
6841
6842     new_LC_ALL(locales, true);
6843
6844 #    endif
6845 }
6846
6847 STATIC void
6848 S_output_check_environment_warning(pTHX_ const char * const language,
6849                                          const char * const lc_all,
6850                                          const char * const lang)
6851 {
6852     PerlIO_printf(Perl_error_log,
6853                   "perl: warning: Please check that your locale settings:\n");
6854
6855 #  ifdef __GLIBC__
6856
6857     PerlIO_printf(Perl_error_log, "\tLANGUAGE = %c%s%c,\n",
6858                                   language ? '"' : '(',
6859                                   language ? language : "unset",
6860                                   language ? '"' : ')');
6861 #  else
6862     PERL_UNUSED_ARG(language);
6863 #  endif
6864
6865     PerlIO_printf(Perl_error_log, "\tLC_ALL = %c%s%c,\n",
6866                                   lc_all ? '"' : '(',
6867                                   lc_all ? lc_all : "unset",
6868                                   lc_all ? '"' : ')');
6869
6870     for (unsigned int i = 0; i < LC_ALL_INDEX_; i++) {
6871         const char * value = PerlEnv_getenv(category_names[i]);
6872         PerlIO_printf(Perl_error_log,
6873                       "\t%s = %c%s%c,\n",
6874                       category_names[i],
6875                       value ? '"' : '(',
6876                       value ? value : "unset",
6877                       value ? '"' : ')');
6878     }
6879
6880     PerlIO_printf(Perl_error_log, "\tLANG = %c%s%c\n",
6881                                   lang ? '"' : '(',
6882                                   lang ? lang : "unset",
6883                                   lang ? '"' : ')');
6884     PerlIO_printf(Perl_error_log,
6885                   "    are supported and installed on your system.\n");
6886 }
6887
6888 #endif
6889
6890 /* A helper macro for the next function.  Needed because would be called in two
6891  * places.  Knows about the internal workings of the function */
6892 #define GET_DESCRIPTION(trial, name)                                    \
6893     ((isNAME_C_OR_POSIX(name))                                          \
6894      ? "the standard locale"                                            \
6895      : ((trial == (system_default_trial)                                \
6896                   ? "the system default locale"                         \
6897                   : "a fallback locale")))
6898
6899 /*
6900  * Initialize locale awareness.
6901  */
6902 int
6903 Perl_init_i18nl10n(pTHX_ int printwarn)
6904 {
6905     /* printwarn is:
6906      *    0 if not to output warning when setup locale is bad
6907      *    1 if to output warning based on value of PERL_BADLANG
6908      *    >1 if to output regardless of PERL_BADLANG
6909      *
6910      * returns
6911      *    1 = set ok or not applicable,
6912      *    0 = fallback to a locale of lower priority
6913      *   -1 = fallback to all locales failed, not even to the C locale
6914      *
6915      * Under -DDEBUGGING, if the environment variable PERL_DEBUG_LOCALE_INIT is
6916      * set, debugging information is output.
6917      *
6918      * This routine effectively does the following in most cases:
6919      *
6920      *      basic initialization;
6921      *      asserts that the compiled tables are consistent;
6922      *      initialize data structures;
6923      *      make sure we are in the global locale;
6924      *      setlocale(LC_ALL, "");
6925      *      switch to per-thread locale if applicable;
6926      *
6927      * The "" causes the locale to be set to what the environment variables at
6928      * the time say it should be.
6929      *
6930      * To handle possible failures, the setlocale is expanded to be like:
6931      *
6932      *      trial_locale = pre-first-trial;
6933      *      while (has_another_trial()) {
6934      *          trial_locale = next_trial();
6935      *          if setlocale(LC_ALL, trial_locale) {
6936      *              ok = true;
6937      *              break;
6938      *          }
6939      *
6940      *          had_failure = true;
6941      *          warn();
6942      *      }
6943      *
6944      *      if (had_failure) {
6945      *          warn_even_more();
6946      *          if (! ok) warn_still_more();
6947      *      }
6948      *
6949      * The first trial is either:
6950      *      ""      to examine the environment variables for the locale
6951      *      NULL    to use the values already set for the locale by the program
6952      *              embedding this perl instantiation.
6953      *
6954      * Something is wrong if this trial fails, but there is a sequence of
6955      * fallbacks to try should that happen.  They are given in the enum below.
6956
6957      * If there is no LC_ALL defined on the system, the setlocale() above is
6958      * replaced by a loop setting each individual category separately.
6959      *
6960      * In a non-embeded environment, this code is executed exactly once.  It
6961      * sets up the global locale environment.  At the end, if some sort of
6962      * thread-safety is in effect, it will turn thread 0 into using that, with
6963      * the same locale as the global initially.  thread 0 can then change its
6964      * locale at will without affecting the global one.
6965      *
6966      * At destruction time, thread 0 will revert to the global locale as the
6967      * other threads die.
6968      *
6969      * Care must be taken in an embedded environment.  This code will be
6970      * executed for each instantiation.  Since it changes the global locale, it
6971      * could clash with another running instantiation that isn't using
6972      * per-thread locales.  perlembed suggests having the controlling program
6973      * set each instantiation's locale and set PERL_SKIP_LOCALE_INIT so this
6974      * code uses that without actually changing anything.  Then the onus is on
6975      * the controlling program to prevent any races.  The code below does
6976      * enough locking so as to prevent system calls from overwriting data
6977      * before it is safely copied here, but that isn't a general solution.
6978      */
6979
6980 #ifndef USE_LOCALE
6981
6982     PERL_UNUSED_ARG(printwarn);
6983     const int ok = 1;
6984
6985 #else  /* USE_LOCALE to near the end of the routine */
6986
6987     int ok = 0;
6988
6989 #  ifdef __GLIBC__
6990
6991     const char * const language = PerlEnv_getenv("LANGUAGE");
6992
6993 #  else
6994     const char * const language = NULL;     /* Unused placeholder */
6995 #  endif
6996
6997     /* A later getenv() could zap this, so only use here */
6998     const char * const bad_lang_use_once = PerlEnv_getenv("PERL_BADLANG");
6999
7000     const bool locwarn = (printwarn > 1
7001                           || (          printwarn
7002                               && (    ! bad_lang_use_once
7003                                   || (
7004                                          /* disallow with "" or "0" */
7005                                          *bad_lang_use_once
7006                                        && strNE("0", bad_lang_use_once)))));
7007
7008 #  ifndef DEBUGGING
7009 #    define DEBUG_LOCALE_INIT(a,b,c)
7010 #  else
7011
7012     DEBUG_INITIALIZATION_set(cBOOL(PerlEnv_getenv("PERL_DEBUG_LOCALE_INIT")));
7013
7014 #    define DEBUG_LOCALE_INIT(cat_index, locale, result)                    \
7015         DEBUG_L(PerlIO_printf(Perl_debug_log, "%s\n",                       \
7016                     setlocale_debug_string_i(cat_index, locale, result)));
7017
7018 #    ifdef LC_ALL
7019     assert(categories[LC_ALL_INDEX_] == LC_ALL);
7020     assert(strEQ(category_names[LC_ALL_INDEX_], "LC_ALL"));
7021 #      ifdef USE_POSIX_2008_LOCALE
7022     assert(category_masks[LC_ALL_INDEX_] == LC_ALL_MASK);
7023 #      endif
7024 #    endif
7025
7026     for (unsigned int i = 0; i < LC_ALL_INDEX_; i++) {
7027         assert(category_name_lengths[i] == strlen(category_names[i]));
7028     }
7029
7030 #  endif    /* DEBUGGING */
7031
7032     /* Initialize the per-thread mbrFOO() state variables.  See POSIX.xs for
7033      * why these particular incantations are used. */
7034 #  ifdef HAS_MBRLEN
7035     memzero(&PL_mbrlen_ps, sizeof(PL_mbrlen_ps));
7036 #  endif
7037 #  ifdef HAS_MBRTOWC
7038     memzero(&PL_mbrtowc_ps, sizeof(PL_mbrtowc_ps));
7039 #  endif
7040 #  ifdef HAS_WCTOMBR
7041     wcrtomb(NULL, L'\0', &PL_wcrtomb_ps);
7042 #  endif
7043 #  ifdef USE_PL_CURLOCALES
7044
7045     for (unsigned int i = 0; i <= LC_ALL_INDEX_; i++) {
7046         PL_curlocales[i] = savepv("C");
7047     }
7048
7049 #  endif
7050 #  ifdef USE_PL_CUR_LC_ALL
7051
7052     PL_cur_LC_ALL = savepv("C");
7053
7054 #  endif
7055 #  if ! defined(PERL_LC_ALL_USES_NAME_VALUE_PAIRS) && defined(LC_ALL)
7056
7057     LOCALE_LOCK;
7058
7059     /* If we haven't done so already, translate the LC_ALL positions of
7060      * categories into our internal indices. */
7061     if (map_LC_ALL_position_to_index[0] == PERL_UINT_MAX) {
7062
7063         /* Use this array, initialized by a config.h constant */
7064         int lc_all_category_positions[] = PERL_LC_ALL_CATEGORY_POSITIONS_INIT;
7065         STATIC_ASSERT_STMT(   C_ARRAY_LENGTH(lc_all_category_positions)
7066                            == LC_ALL_INDEX_);
7067
7068         for (unsigned int i = 0;
7069              i < C_ARRAY_LENGTH(lc_all_category_positions);
7070              i++)
7071         {
7072             map_LC_ALL_position_to_index[i] =
7073                               get_category_index(lc_all_category_positions[i]);
7074         }
7075     }
7076
7077     LOCALE_UNLOCK;
7078
7079 #  endif
7080 #  ifdef USE_POSIX_2008_LOCALE
7081
7082     /* This is a global, so be sure to keep another instance from zapping it */
7083     LOCALE_LOCK;
7084     if (PL_C_locale_obj) {
7085         LOCALE_UNLOCK;
7086     }
7087     else {
7088         PL_C_locale_obj = newlocale(LC_ALL_MASK, "C", (locale_t) 0);
7089         if (! PL_C_locale_obj) {
7090             LOCALE_UNLOCK;
7091             locale_panic_(Perl_form(aTHX_
7092                                 "Cannot create POSIX 2008 C locale object"));
7093         }
7094         LOCALE_UNLOCK;
7095
7096         DEBUG_Lv(PerlIO_printf(Perl_debug_log, "created C object %p\n",
7097                                                PL_C_locale_obj));
7098     }
7099
7100     /* Switch to using the POSIX 2008 interface now.  This would happen below
7101      * anyway, but deferring it can lead to leaks of memory that would also get
7102      * malloc'd in the interim.  We arbitrarily switch to the C locale,
7103      * overridden below  */
7104     if (! uselocale(PL_C_locale_obj)) {
7105         locale_panic_(Perl_form(aTHX_
7106                                 "Can't uselocale(%p), LC_ALL supposed to"
7107                                 " be 'C'",
7108                                 PL_C_locale_obj));
7109     }
7110
7111 #    ifdef MULTIPLICITY
7112
7113     PL_cur_locale_obj = PL_C_locale_obj;
7114
7115 #    endif
7116 #    ifdef USE_LOCALE_NUMERIC
7117
7118     PL_underlying_numeric_obj = duplocale(PL_C_locale_obj);
7119
7120 #    endif
7121 #  endif
7122
7123     /* Now initialize some data structures.  This is entirely so that
7124      * later-executed code doesn't have to concern itself with things not being
7125      * initialized.  Arbitrarily use the C locale (which we know has to exist
7126      * on the system). */
7127
7128 #  ifdef USE_LOCALE_NUMERIC
7129
7130     PL_numeric_radix_sv    = newSV(1);
7131     PL_underlying_radix_sv = newSV(1);
7132     Newxz(PL_numeric_name, 1, char);    /* Single NUL character */
7133
7134 #  endif
7135 #  ifdef USE_LOCALE_COLLATE
7136
7137     Newxz(PL_collation_name, 1, char);
7138
7139 #  endif
7140 #  ifdef USE_LOCALE_CTYPE
7141
7142     Newxz(PL_ctype_name, 1, char);
7143
7144 #  endif
7145
7146     new_LC_ALL("C", true /* Don't shortcut */);
7147
7148 /*===========================================================================*/
7149
7150     /* Now ready to override the initialization with the values that the user
7151      * wants.  This is done in the global locale as explained in the
7152      * introductory comments to this function */
7153     switch_to_global_locale();
7154
7155     const char * const lc_all     = PerlEnv_getenv("LC_ALL");
7156     const char * const lang       = PerlEnv_getenv("LANG");
7157
7158     /* We try each locale in the enum, in order, until we get one that works,
7159      * or exhaust the list.  Normally the loop is executed just once.
7160      *
7161      * Each enum value is +1 from the previous */
7162     typedef enum {
7163             dummy_trial       = -1,
7164             environment_trial =  0,     /* "" or NULL; code below assumes value
7165                                            0 is the first real trial */
7166             LC_ALL_trial,               /* ENV{LC_ALL} */
7167             LANG_trial,                 /* ENV{LANG} */
7168             system_default_trial,       /* Windows .ACP */
7169             C_trial,                    /* C locale */
7170             beyond_final_trial,
7171     } trials;
7172
7173     trials trial;
7174     SSize_t already_checked = 0;
7175     const char * checked[C_trial];
7176
7177 #  ifdef LC_ALL
7178     const char * lc_all_string;
7179 #  else
7180     const char * curlocales[LC_ALL_INDEX_];
7181 #  endif
7182
7183     /* Loop through the initial setting and all the possible fallbacks,
7184      * breaking out of the loop on success */
7185     trial = dummy_trial;
7186     while (trial != beyond_final_trial) {
7187
7188         /* Each time through compute the next trial to use based on the one in
7189          * the previous iteration and switch to the new one.  This enforces the
7190          * order in which the fallbacks are applied */
7191       next_trial:
7192         trial = (trials) ((int) trial + 1);     /* Casts are needed for g++ */
7193
7194         const char * locale = NULL;
7195
7196         /* Set up the parameters for this trial */
7197         switch (trial) {
7198           case dummy_trial:
7199             locale_panic_("Unexpectedly got 'dummy_trial");
7200             break;
7201
7202           case environment_trial:
7203             /* This is either "" to get the values from the environment, or
7204              * NULL if the calling program has initialized the values already.
7205              * */
7206             locale = (PerlEnv_getenv("PERL_SKIP_LOCALE_INIT"))
7207                      ? NULL
7208                      : "";
7209             break;
7210
7211           case LC_ALL_trial:
7212             if (! lc_all || strEQ(lc_all, "")) {
7213                 continue;   /* No-op */
7214             }
7215
7216             locale = lc_all;
7217             break;
7218
7219           case LANG_trial:
7220             if (! lang || strEQ(lang, "")) {
7221                 continue;   /* No-op */
7222             }
7223
7224             locale = lang;
7225             break;
7226
7227           case system_default_trial:
7228
7229 #  if ! defined(WIN32) || ! defined(LC_ALL)
7230
7231             continue;   /* No-op */
7232
7233 #  else
7234             /* For Windows, we also try the system default locale before "C".
7235              * (If there exists a Windows without LC_ALL we skip this because
7236              * it gets too complicated.  For those, "C" is the next fallback
7237              * possibility). */
7238             locale = ".ACP";
7239 #  endif
7240             break;
7241
7242           case C_trial:
7243             locale = "C";
7244             break;
7245
7246           case beyond_final_trial:
7247             continue;     /* No-op, causes loop to exit */
7248         }
7249
7250         /* If the locale is a substantive name, don't try the same locale
7251          * twice. */
7252         if (locale && strNE(locale, "")) {
7253             for (unsigned int i = 0; i < already_checked; i++) {
7254                 if (strEQ(checked[i], locale)) {
7255                     goto next_trial;
7256                 }
7257             }
7258
7259             /* And, for future iterations, indicate we've tried this locale */
7260             checked[already_checked] = savepv(locale);
7261             SAVEFREEPV(checked[already_checked]);
7262             already_checked++;
7263         }
7264
7265 #  ifdef LC_ALL
7266
7267         STDIZED_SETLOCALE_LOCK;
7268         lc_all_string = savepv(stdized_setlocale(LC_ALL, locale));
7269         STDIZED_SETLOCALE_UNLOCK;
7270
7271         DEBUG_LOCALE_INIT(LC_ALL_INDEX_, locale, lc_all_string);
7272
7273         if (LIKELY(lc_all_string)) {     /* Succeeded */
7274             ok = 1;
7275             break;
7276         }
7277
7278         if (trial == 0 && locwarn) {
7279             PerlIO_printf(Perl_error_log,
7280                                   "perl: warning: Setting locale failed.\n");
7281             output_check_environment_warning(language, lc_all, lang);
7282         }
7283
7284 #  else /* Below is ! LC_ALL */
7285
7286         bool setlocale_failure = FALSE;  /* This trial hasn't failed so far */
7287         bool dowarn = trial == 0 && locwarn;
7288
7289         for (unsigned int j = 0; j < LC_ALL_INDEX_; j++) {
7290             STDIZED_SETLOCALE_LOCK;
7291             curlocales[j] = savepv(stdized_setlocale(categories[j], locale));
7292             STDIZED_SETLOCALE_UNLOCK;
7293
7294             DEBUG_LOCALE_INIT(j, locale, curlocales[j]);
7295
7296             if (UNLIKELY(! curlocales[j])) {
7297                 setlocale_failure = TRUE;
7298
7299                 /* If are going to warn below, continue to loop so all failures
7300                  * are included in the message */
7301                 if (! dowarn) {
7302                     break;
7303                 }
7304             }
7305         }
7306
7307         if (LIKELY(! setlocale_failure)) {  /* All succeeded */
7308             ok = 1;
7309             break;  /* Exit trial_locales loop */
7310         }
7311
7312         /* Here, this trial failed */
7313
7314         if (dowarn) {
7315             PerlIO_printf(Perl_error_log,
7316                 "perl: warning: Setting locale failed for the categories:\n");
7317
7318             for (unsigned int j = 0; j < LC_ALL_INDEX_; j++) {
7319                 if (! curlocales[j]) {
7320                     PerlIO_printf(Perl_error_log, "\t%s\n", category_names[j]);
7321                 }
7322             }
7323
7324             output_check_environment_warning(language, lc_all, lang);
7325         }   /* end of warning on first failure */
7326
7327 #  endif /* LC_ALL */
7328
7329     }   /* end of looping through the trial locales */
7330
7331     /* If we had to do more than the first trial, it means that one failed, and
7332      * we may need to output a warning, and, if none worked, do more */
7333     if (UNLIKELY(trial != 0)) {
7334         if (locwarn) {
7335             const char * description = "a fallback locale";
7336             const char * name = NULL;;
7337
7338             /* If we didn't find a good fallback, list all we tried */
7339             if (! ok && already_checked > 0) {
7340                 PerlIO_printf(Perl_error_log, "perl: warning: Failed to fall"
7341                                               " back to ");
7342                 if (already_checked > 1) {  /* more than one was tried */
7343                     PerlIO_printf(Perl_error_log, "any of:\n");
7344                 }
7345
7346                 while (already_checked > 0) {
7347                     name = checked[--already_checked];
7348                     description = GET_DESCRIPTION(trial, name);
7349                     PerlIO_printf(Perl_error_log, "%s (\"%s\")\n",
7350                                                   description, name);
7351                 }
7352             }
7353
7354             if (ok) {
7355
7356                 /* Here, a fallback worked.  So we have saved its name, and the
7357                  * trial that succeeded is still valid */
7358 #  ifdef LC_ALL
7359                 const char * individ_locales[LC_ALL_INDEX_] = { NULL };
7360
7361                 /* Even though we know the valid string for LC_ALL that worked,
7362                  * translate it into our internal format, which is the
7363                  * name=value pairs notation.  This is easier for a human to
7364                  * decipher than the positional notation.  Some platforms
7365                  * can return "C C C C C C" for LC_ALL.  This code also
7366                  * standardizes that result into plain "C". */
7367                 switch (parse_LC_ALL_string(lc_all_string,
7368                                             (const char **) &individ_locales,
7369                                             no_override,
7370                                             false,   /* Return only [0] if
7371                                                         suffices */
7372                                             false,   /* Don't panic on error */
7373                                             __LINE__))
7374                 {
7375                   case invalid:
7376
7377                     /* Here, the parse failed, which shouldn't happen, but if
7378                      * it does, we have an easy fallback that allows us to keep
7379                      * going. */
7380                     name = lc_all_string;
7381                     break;
7382
7383                   case no_array:    /* The original is a single locale */
7384                     name = lc_all_string;
7385                     break;
7386
7387                   case only_element_0:  /* element[0] is a single locale valid
7388                                            for all categories */
7389                     SAVEFREEPV(individ_locales[0]);
7390                     name = individ_locales[0];
7391                     break;
7392
7393                   case full_array:
7394                     name = calculate_LC_ALL_string(individ_locales,
7395                                                    INTERNAL_FORMAT,
7396                                                    WANT_TEMP_PV,
7397                                                    __LINE__);
7398                     for (unsigned int j = 0; j < LC_ALL_INDEX_; j++) {
7399                         Safefree(individ_locales[j]);
7400                     }
7401                 }
7402 #  else
7403                 name = calculate_LC_ALL_string(curlocales,
7404                                                INTERNAL_FORMAT,
7405                                                WANT_TEMP_PV,
7406                                                __LINE__);
7407 #  endif
7408                 description = GET_DESCRIPTION(trial, name);
7409             }
7410             else {
7411
7412                 /* Nothing seems to be working, yet we want to continue
7413                  * executing.  It may well be that locales are mostly
7414                  * irrelevant to this particular program, and there must be
7415                  * some locale underlying the program.  Figure it out as best
7416                  * we can, by querying the system's current locale */
7417
7418 #  ifdef LC_ALL
7419
7420                 STDIZED_SETLOCALE_LOCK;
7421                 name = stdized_setlocale(LC_ALL, NULL);
7422                 STDIZED_SETLOCALE_UNLOCK;
7423
7424                 if (UNLIKELY(! name)) {
7425                     name = "locale name not determinable";
7426                 }
7427
7428 #  else /* Below is ! LC_ALL */
7429
7430                 const char * system_locales[LC_ALL_INDEX_] = { NULL };
7431
7432                 for (unsigned int j = 0; j < LC_ALL_INDEX_; j++) {
7433                     STDIZED_SETLOCALE_LOCK;
7434                     system_locales[j] = savepv(stdized_setlocale(categories[j],
7435                                                                  NULL));
7436                     STDIZED_SETLOCALE_UNLOCK;
7437
7438                     if (UNLIKELY(! system_locales[j])) {
7439                         system_locales[j] = "not determinable";
7440                     }
7441                 }
7442
7443                 /* We use the name=value form for the string, as that is more
7444                  * human readable than the positional notation */
7445                 name = calculate_LC_ALL_string(system_locales,
7446                                                INTERNAL_FORMAT,
7447                                                WANT_TEMP_PV,
7448                                                __LINE__);
7449                 description = "what the system says";
7450
7451                 for (unsigned int j = 0; j < LC_ALL_INDEX_; j++) {
7452                     Safefree(system_locales[j]);
7453                 }
7454 #  endif
7455             }
7456
7457             PerlIO_printf(Perl_error_log,
7458                           "perl: warning: Falling back to %s (\"%s\").\n",
7459                           description, name);
7460
7461             /* Here, ok being true indicates that the first attempt failed, but
7462              * a fallback succeeded; false => nothing working.  Translate to
7463              * API return values. */
7464             ok = (ok) ? 0 : -1;
7465         }
7466     }
7467
7468 #  ifdef LC_ALL
7469
7470     give_perl_locale_control(lc_all_string, __LINE__);
7471     Safefree(lc_all_string);
7472
7473 #  else
7474
7475     give_perl_locale_control((const char **) &curlocales, __LINE__);
7476
7477     for (unsigned int j = 0; j < LC_ALL_INDEX_; j++) {
7478         Safefree(curlocales[j]);
7479     }
7480
7481 #  endif
7482 #  if defined(USE_PERLIO) && defined(USE_LOCALE_CTYPE)
7483
7484     /* Set PL_utf8locale to TRUE if using PerlIO _and_ the current LC_CTYPE
7485      * locale is UTF-8.  give_perl_locale_control() just above has already
7486      * calculated the latter value and saved it in PL_in_utf8_CTYPE_locale. If
7487      * both PL_utf8locale and PL_unicode (set by -C or by $ENV{PERL_UNICODE})
7488      * are true, perl.c:S_parse_body() will turn on the PerlIO :utf8 layer on
7489      * STDIN, STDOUT, STDERR, _and_ the default open discipline.  */
7490     PL_utf8locale = PL_in_utf8_CTYPE_locale;
7491
7492     /* Set PL_unicode to $ENV{PERL_UNICODE} if using PerlIO.
7493        This is an alternative to using the -C command line switch
7494        (the -C if present will override this). */
7495     {
7496          const char *p = PerlEnv_getenv("PERL_UNICODE");
7497          PL_unicode = p ? parse_unicode_opts(&p) : 0;
7498          if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
7499              PL_utf8cache = -1;
7500     }
7501
7502 #  endif
7503 #  if defined(USE_POSIX_2008_LOCALE) && defined(MULTIPLICITY)
7504     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
7505                            "finished Perl_init_i18nl10n; actual obj=%p,"
7506                            " expected obj=%p, initial=%s\n",
7507                            uselocale(0), PL_cur_locale_obj,
7508                            get_LC_ALL_display()));
7509 #  endif
7510
7511     /* So won't continue to output stuff */
7512     DEBUG_INITIALIZATION_set(FALSE);
7513
7514 #endif /* USE_LOCALE */
7515
7516     return ok;
7517 }
7518
7519 #undef GET_DESCRIPTION
7520 #ifdef USE_LOCALE_COLLATE
7521
7522 STATIC void
7523 S_compute_collxfrm_coefficients(pTHX)
7524 {
7525
7526     /* A locale collation definition includes primary, secondary, tertiary,
7527      * etc. weights for each character.  To sort, the primary weights are used,
7528      * and only if they compare equal, then the secondary weights are used, and
7529      * only if they compare equal, then the tertiary, etc.
7530      *
7531      * strxfrm() works by taking the input string, say ABC, and creating an
7532      * output transformed string consisting of first the primary weights,
7533      * A¹B¹C¹ followed by the secondary ones, A²B²C²; and then the tertiary,
7534      * etc, yielding A¹B¹C¹ A²B²C² A³B³C³ ....  Some characters may not have
7535      * weights at every level.  In our example, let's say B doesn't have a
7536      * tertiary weight, and A doesn't have a secondary weight.  The constructed
7537      * string is then going to be
7538      *  A¹B¹C¹ B²C² A³C³ ....
7539      * This has the desired effect that strcmp() will look at the secondary or
7540      * tertiary weights only if the strings compare equal at all higher
7541      * priority weights.  The spaces shown here, like in
7542      *  "A¹B¹C¹ A²B²C² "
7543      * are not just for readability.  In the general case, these must actually
7544      * be bytes, which we will call here 'separator weights'; and they must be
7545      * smaller than any other weight value, but since these are C strings, only
7546      * the terminating one can be a NUL (some implementations may include a
7547      * non-NUL separator weight just before the NUL).  Implementations tend to
7548      * reserve 01 for the separator weights.  They are needed so that a shorter
7549      * string's secondary weights won't be misconstrued as primary weights of a
7550      * longer string, etc.  By making them smaller than any other weight, the
7551      * shorter string will sort first.  (Actually, if all secondary weights are
7552      * smaller than all primary ones, there is no need for a separator weight
7553      * between those two levels, etc.)
7554      *
7555      * The length of the transformed string is roughly a linear function of the
7556      * input string.  It's not exactly linear because some characters don't
7557      * have weights at all levels.  When we call strxfrm() we have to allocate
7558      * some memory to hold the transformed string.  The calculations below try
7559      * to find coefficients 'm' and 'b' for this locale so that m*x + b equals
7560      * how much space we need, given the size of the input string in 'x'.  If
7561      * we calculate too small, we increase the size as needed, and call
7562      * strxfrm() again, but it is better to get it right the first time to
7563      * avoid wasted expensive string transformations.
7564      *
7565      * We use the string below to find how long the transformation of it is.
7566      * Almost all locales are supersets of ASCII, or at least the ASCII
7567      * letters.  We use all of them, half upper half lower, because if we used
7568      * fewer, we might hit just the ones that are outliers in a particular
7569      * locale.  Most of the strings being collated will contain a preponderance
7570      * of letters, and even if they are above-ASCII, they are likely to have
7571      * the same number of weight levels as the ASCII ones.  It turns out that
7572      * digits tend to have fewer levels, and some punctuation has more, but
7573      * those are relatively sparse in text, and khw believes this gives a
7574      * reasonable result, but it could be changed if experience so dictates. */
7575     const char longer[] = "ABCDEFGHIJKLMnopqrstuvwxyz";
7576     char * x_longer;        /* Transformed 'longer' */
7577     Size_t x_len_longer;    /* Length of 'x_longer' */
7578
7579     char * x_shorter;   /* We also transform a substring of 'longer' */
7580     Size_t x_len_shorter;
7581
7582     PL_in_utf8_COLLATE_locale = (PL_collation_standard)
7583                                 ? 0
7584                                 : is_locale_utf8(PL_collation_name);
7585     PL_strxfrm_NUL_replacement = '\0';
7586     PL_strxfrm_max_cp = 0;
7587
7588     /* mem_collxfrm_() is used get the transformation (though here we are
7589      * interested only in its length).  It is used because it has the
7590      * intelligence to handle all cases, but to work, it needs some values of
7591      * 'm' and 'b' to get it started.  For the purposes of this calculation we
7592      * use a very conservative estimate of 'm' and 'b'.  This assumes a weight
7593      * can be multiple bytes, enough to hold any UV on the platform, and there
7594      * are 5 levels, 4 weight bytes, and a trailing NUL.  */
7595     PL_collxfrm_base = 5;
7596     PL_collxfrm_mult = 5 * sizeof(UV);
7597
7598     /* Find out how long the transformation really is */
7599     x_longer = mem_collxfrm_(longer,
7600                              sizeof(longer) - 1,
7601                              &x_len_longer,
7602
7603                              /* We avoid converting to UTF-8 in the called
7604                               * function by telling it the string is in UTF-8
7605                               * if the locale is a UTF-8 one.  Since the string
7606                               * passed here is invariant under UTF-8, we can
7607                               * claim it's UTF-8 even if it isn't.  */
7608                               PL_in_utf8_COLLATE_locale);
7609     Safefree(x_longer);
7610
7611     /* Find out how long the transformation of a substring of 'longer' is.
7612      * Together the lengths of these transformations are sufficient to
7613      * calculate 'm' and 'b'.  The substring is all of 'longer' except the
7614      * first character.  This minimizes the chances of being swayed by outliers
7615      * */
7616     x_shorter = mem_collxfrm_(longer + 1,
7617                               sizeof(longer) - 2,
7618                               &x_len_shorter,
7619                               PL_in_utf8_COLLATE_locale);
7620     Safefree(x_shorter);
7621
7622     /* If the results are nonsensical for this simple test, the whole locale
7623      * definition is suspect.  Mark it so that locale collation is not active
7624      * at all for it.  XXX Should we warn? */
7625     if (   x_len_shorter == 0
7626         || x_len_longer == 0
7627         || x_len_shorter >= x_len_longer)
7628     {
7629         PL_collxfrm_mult = 0;
7630         PL_collxfrm_base = 1;
7631         DEBUG_L(PerlIO_printf(Perl_debug_log,
7632                 "Disabling locale collation for LC_COLLATE='%s';"
7633                 " length for shorter sample=%zu; longer=%zu\n",
7634                 PL_collation_name, x_len_shorter, x_len_longer));
7635     }
7636     else {
7637         SSize_t base;       /* Temporary */
7638
7639         /* We have both: m * strlen(longer)  + b = x_len_longer
7640          *               m * strlen(shorter) + b = x_len_shorter;
7641          * subtracting yields:
7642          *          m * (strlen(longer) - strlen(shorter))
7643          *                             = x_len_longer - x_len_shorter
7644          * But we have set things up so that 'shorter' is 1 byte smaller than
7645          * 'longer'.  Hence:
7646          *          m = x_len_longer - x_len_shorter
7647          *
7648          * But if something went wrong, make sure the multiplier is at least 1.
7649          */
7650         if (x_len_longer > x_len_shorter) {
7651             PL_collxfrm_mult = (STRLEN) x_len_longer - x_len_shorter;
7652         }
7653         else {
7654             PL_collxfrm_mult = 1;
7655         }
7656
7657         /*     mx + b = len
7658          * so:      b = len - mx
7659          * but in case something has gone wrong, make sure it is non-negative
7660          * */
7661         base = x_len_longer - PL_collxfrm_mult * (sizeof(longer) - 1);
7662         if (base < 0) {
7663             base = 0;
7664         }
7665
7666         /* Add 1 for the trailing NUL */
7667         PL_collxfrm_base = base + 1;
7668     }
7669
7670     DEBUG_L(PerlIO_printf(Perl_debug_log,
7671                           "?UTF-8 locale=%d; x_len_shorter=%zu, "
7672                           "x_len_longer=%zu,"
7673                           " collate multipler=%zu, collate base=%zu\n",
7674                           PL_in_utf8_COLLATE_locale,
7675                           x_len_shorter, x_len_longer,
7676                           PL_collxfrm_mult, PL_collxfrm_base));
7677 }
7678
7679 char *
7680 Perl_mem_collxfrm_(pTHX_ const char *input_string,
7681                          STRLEN len,    /* Length of 'input_string' */
7682                          STRLEN *xlen,  /* Set to length of returned string
7683                                            (not including the collation index
7684                                            prefix) */
7685                          bool utf8      /* Is the input in UTF-8? */
7686                    )
7687 {
7688     /* mem_collxfrm_() is like strxfrm() but with two important differences.
7689      * First, it handles embedded NULs. Second, it allocates a bit more memory
7690      * than needed for the transformed data itself.  The real transformed data
7691      * begins at offset COLLXFRM_HDR_LEN.  *xlen is set to the length of that,
7692      * and doesn't include the collation index size.
7693      *
7694      * It is the caller's responsibility to eventually free the memory returned
7695      * by this function.
7696      *
7697      * Please see sv_collxfrm() to see how this is used. */
7698
7699 #  define COLLXFRM_HDR_LEN    sizeof(PL_collation_ix)
7700
7701     char * s = (char *) input_string;
7702     STRLEN s_strlen = strlen(input_string);
7703     char *xbuf = NULL;
7704     STRLEN xAlloc;          /* xalloc is a reserved word in VC */
7705     STRLEN length_in_chars;
7706     bool first_time = TRUE; /* Cleared after first loop iteration */
7707
7708 #  ifdef USE_LOCALE_CTYPE
7709         const char * orig_CTYPE_locale = NULL;
7710 #  endif
7711
7712 #  if defined(USE_POSIX_2008_LOCALE) && defined HAS_STRXFRM_L
7713     locale_t constructed_locale = (locale_t) 0;
7714 #  endif
7715
7716     PERL_ARGS_ASSERT_MEM_COLLXFRM_;
7717
7718     /* Must be NUL-terminated */
7719     assert(*(input_string + len) == '\0');
7720
7721     if (PL_collxfrm_mult == 0) {     /* unknown or bad */
7722         if (PL_collxfrm_base != 0) { /* bad collation => skip */
7723             DEBUG_L(PerlIO_printf(Perl_debug_log,
7724                           "mem_collxfrm_: locale's collation is defective\n"));
7725             goto bad;
7726         }
7727
7728         /* (mult, base) == (0,0) means we need to calculate mult and base
7729          * before proceeding */
7730         S_compute_collxfrm_coefficients(aTHX);
7731     }
7732
7733     /* Replace any embedded NULs with the control that sorts before any others.
7734      * This will give as good as possible results on strings that don't
7735      * otherwise contain that character, but otherwise there may be
7736      * less-than-perfect results with that character and NUL.  This is
7737      * unavoidable unless we replace strxfrm with our own implementation. */
7738     if (UNLIKELY(s_strlen < len)) {   /* Only execute if there is an embedded
7739                                          NUL */
7740         char * e = s + len;
7741         char * sans_nuls;
7742         STRLEN sans_nuls_len;
7743         int try_non_controls;
7744         char this_replacement_char[] = "?\0";   /* Room for a two-byte string,
7745                                                    making sure 2nd byte is NUL.
7746                                                  */
7747         STRLEN this_replacement_len;
7748
7749         /* If we don't know what non-NUL control character sorts lowest for
7750          * this locale, find it */
7751         if (PL_strxfrm_NUL_replacement == '\0') {
7752             int j;
7753             char * cur_min_x = NULL;    /* The min_char's xfrm, (except it also
7754                                            includes the collation index
7755                                            prefixed. */
7756
7757             DEBUG_Lv(PerlIO_printf(Perl_debug_log, "Looking to replace NUL\n"));
7758
7759             /* Unlikely, but it may be that no control will work to replace
7760              * NUL, in which case we instead look for any character.  Controls
7761              * are preferred because collation order is, in general, context
7762              * sensitive, with adjoining characters affecting the order, and
7763              * controls are less likely to have such interactions, allowing the
7764              * NUL-replacement to stand on its own.  (Another way to look at it
7765              * is to imagine what would happen if the NUL were replaced by a
7766              * combining character; it wouldn't work out all that well.) */
7767             for (try_non_controls = 0;
7768                  try_non_controls < 2;
7769                  try_non_controls++)
7770             {
7771
7772 #  ifdef USE_LOCALE_CTYPE
7773
7774                 /* In this case we use isCNTRL_LC() below, which relies on
7775                  * LC_CTYPE, so that must be switched to correspond with the
7776                  * LC_COLLATE locale */
7777                 if (! try_non_controls && ! PL_in_utf8_COLLATE_locale) {
7778                     orig_CTYPE_locale = toggle_locale_c(LC_CTYPE,
7779                                                         PL_collation_name);
7780                 }
7781 #  endif
7782                 /* Look through all legal code points (NUL isn't) */
7783                 for (j = 1; j < 256; j++) {
7784                     char * x;       /* j's xfrm plus collation index */
7785                     STRLEN x_len;   /* length of 'x' */
7786                     STRLEN trial_len = 1;
7787                     char cur_source[] = { '\0', '\0' };
7788
7789                     /* Skip non-controls the first time through the loop.  The
7790                      * controls in a UTF-8 locale are the L1 ones */
7791                     if (! try_non_controls && (PL_in_utf8_COLLATE_locale)
7792                                                ? ! isCNTRL_L1(j)
7793                                                : ! isCNTRL_LC(j))
7794                     {
7795                         continue;
7796                     }
7797
7798                     /* Create a 1-char string of the current code point */
7799                     cur_source[0] = (char) j;
7800
7801                     /* Then transform it */
7802                     x = mem_collxfrm_(cur_source, trial_len, &x_len,
7803                                       0 /* The string is not in UTF-8 */);
7804
7805                     /* Ignore any character that didn't successfully transform.
7806                      * */
7807                     if (! x) {
7808                         continue;
7809                     }
7810
7811                     /* If this character's transformation is lower than
7812                      * the current lowest, this one becomes the lowest */
7813                     if (   cur_min_x == NULL
7814                         || strLT(x         + COLLXFRM_HDR_LEN,
7815                                  cur_min_x + COLLXFRM_HDR_LEN))
7816                     {
7817                         PL_strxfrm_NUL_replacement = j;
7818                         Safefree(cur_min_x);
7819                         cur_min_x = x;
7820                     }
7821                     else {
7822                         Safefree(x);
7823                     }
7824                 } /* end of loop through all 255 characters */
7825
7826 #  ifdef USE_LOCALE_CTYPE
7827                 restore_toggled_locale_c(LC_CTYPE, orig_CTYPE_locale);
7828 #  endif
7829
7830                 /* Stop looking if found */
7831                 if (cur_min_x) {
7832                     break;
7833                 }
7834
7835                 /* Unlikely, but possible, if there aren't any controls that
7836                  * work in the locale, repeat the loop, looking for any
7837                  * character that works */
7838                 DEBUG_L(PerlIO_printf(Perl_debug_log,
7839                 "mem_collxfrm_: No control worked.  Trying non-controls\n"));
7840             } /* End of loop to try first the controls, then any char */
7841
7842             if (! cur_min_x) {
7843                 DEBUG_L(PerlIO_printf(Perl_debug_log,
7844                     "mem_collxfrm_: Couldn't find any character to replace"
7845                     " embedded NULs in locale %s with", PL_collation_name));
7846                 goto bad;
7847             }
7848
7849             DEBUG_L(PerlIO_printf(Perl_debug_log,
7850                     "mem_collxfrm_: Replacing embedded NULs in locale %s with "
7851                     "0x%02X\n", PL_collation_name, PL_strxfrm_NUL_replacement));
7852
7853             Safefree(cur_min_x);
7854         } /* End of determining the character that is to replace NULs */
7855
7856         /* If the replacement is variant under UTF-8, it must match the
7857          * UTF8-ness of the original */
7858         if ( ! UVCHR_IS_INVARIANT(PL_strxfrm_NUL_replacement) && utf8) {
7859             this_replacement_char[0] =
7860                                 UTF8_EIGHT_BIT_HI(PL_strxfrm_NUL_replacement);
7861             this_replacement_char[1] =
7862                                 UTF8_EIGHT_BIT_LO(PL_strxfrm_NUL_replacement);
7863             this_replacement_len = 2;
7864         }
7865         else {
7866             this_replacement_char[0] = PL_strxfrm_NUL_replacement;
7867             /* this_replacement_char[1] = '\0' was done at initialization */
7868             this_replacement_len = 1;
7869         }
7870
7871         /* The worst case length for the replaced string would be if every
7872          * character in it is NUL.  Multiply that by the length of each
7873          * replacement, and allow for a trailing NUL */
7874         sans_nuls_len = (len * this_replacement_len) + 1;
7875         Newx(sans_nuls, sans_nuls_len, char);
7876         *sans_nuls = '\0';
7877
7878         /* Replace each NUL with the lowest collating control.  Loop until have
7879          * exhausted all the NULs */
7880         while (s + s_strlen < e) {
7881             my_strlcat(sans_nuls, s, sans_nuls_len);
7882
7883             /* Do the actual replacement */
7884             my_strlcat(sans_nuls, this_replacement_char, sans_nuls_len);
7885
7886             /* Move past the input NUL */
7887             s += s_strlen + 1;
7888             s_strlen = strlen(s);
7889         }
7890
7891         /* And add anything that trails the final NUL */
7892         my_strlcat(sans_nuls, s, sans_nuls_len);
7893
7894         /* Switch so below we transform this modified string */
7895         s = sans_nuls;
7896         len = strlen(s);
7897     } /* End of replacing NULs */
7898
7899     /* Make sure the UTF8ness of the string and locale match */
7900     if (utf8 != PL_in_utf8_COLLATE_locale) {
7901         /* XXX convert above Unicode to 10FFFF? */
7902         const char * const t = s;   /* Temporary so we can later find where the
7903                                        input was */
7904
7905         /* Here they don't match.  Change the string's to be what the locale is
7906          * expecting */
7907
7908         if (! utf8) { /* locale is UTF-8, but input isn't; upgrade the input */
7909             s = (char *) bytes_to_utf8((const U8 *) s, &len);
7910             utf8 = TRUE;
7911         }
7912         else {   /* locale is not UTF-8; but input is; downgrade the input */
7913
7914             s = (char *) bytes_from_utf8((const U8 *) s, &len, &utf8);
7915
7916             /* If the downgrade was successful we are done, but if the input
7917              * contains things that require UTF-8 to represent, have to do
7918              * damage control ... */
7919             if (UNLIKELY(utf8)) {
7920
7921                 /* What we do is construct a non-UTF-8 string with
7922                  *  1) the characters representable by a single byte converted
7923                  *     to be so (if necessary);
7924                  *  2) and the rest converted to collate the same as the
7925                  *     highest collating representable character.  That makes
7926                  *     them collate at the end.  This is similar to how we
7927                  *     handle embedded NULs, but we use the highest collating
7928                  *     code point instead of the smallest.  Like the NUL case,
7929                  *     this isn't perfect, but is the best we can reasonably
7930                  *     do.  Every above-255 code point will sort the same as
7931                  *     the highest-sorting 0-255 code point.  If that code
7932                  *     point can combine in a sequence with some other code
7933                  *     points for weight calculations, us changing something to
7934                  *     be it can adversely affect the results.  But in most
7935                  *     cases, it should work reasonably.  And note that this is
7936                  *     really an illegal situation: using code points above 255
7937                  *     on a locale where only 0-255 are valid.  If two strings
7938                  *     sort entirely equal, then the sort order for the
7939                  *     above-255 code points will be in code point order. */
7940
7941                 utf8 = FALSE;
7942
7943                 /* If we haven't calculated the code point with the maximum
7944                  * collating order for this locale, do so now */
7945                 if (! PL_strxfrm_max_cp) {
7946                     int j;
7947
7948                     /* The current transformed string that collates the
7949                      * highest (except it also includes the prefixed collation
7950                      * index. */
7951                     char * cur_max_x = NULL;
7952
7953                     /* Look through all legal code points (NUL isn't) */
7954                     for (j = 1; j < 256; j++) {
7955                         char * x;
7956                         STRLEN x_len;
7957                         char cur_source[] = { '\0', '\0' };
7958
7959                         /* Create a 1-char string of the current code point */
7960                         cur_source[0] = (char) j;
7961
7962                         /* Then transform it */
7963                         x = mem_collxfrm_(cur_source, 1, &x_len, FALSE);
7964
7965                         /* If something went wrong (which it shouldn't), just
7966                          * ignore this code point */
7967                         if (! x) {
7968                             continue;
7969                         }
7970
7971                         /* If this character's transformation is higher than
7972                          * the current highest, this one becomes the highest */
7973                         if (   cur_max_x == NULL
7974                             || strGT(x         + COLLXFRM_HDR_LEN,
7975                                      cur_max_x + COLLXFRM_HDR_LEN))
7976                         {
7977                             PL_strxfrm_max_cp = j;
7978                             Safefree(cur_max_x);
7979                             cur_max_x = x;
7980                         }
7981                         else {
7982                             Safefree(x);
7983                         }
7984                     }
7985
7986                     if (! cur_max_x) {
7987                         DEBUG_L(PerlIO_printf(Perl_debug_log,
7988                             "mem_collxfrm_: Couldn't find any character to"
7989                             " replace above-Latin1 chars in locale %s with",
7990                             PL_collation_name));
7991                         goto bad;
7992                     }
7993
7994                     DEBUG_L(PerlIO_printf(Perl_debug_log,
7995                             "mem_collxfrm_: highest 1-byte collating character"
7996                             " in locale %s is 0x%02X\n",
7997                             PL_collation_name,
7998                             PL_strxfrm_max_cp));
7999
8000                     Safefree(cur_max_x);
8001                 }
8002
8003                 /* Here we know which legal code point collates the highest.
8004                  * We are ready to construct the non-UTF-8 string.  The length
8005                  * will be at least 1 byte smaller than the input string
8006                  * (because we changed at least one 2-byte character into a
8007                  * single byte), but that is eaten up by the trailing NUL */
8008                 Newx(s, len, char);
8009
8010                 {
8011                     STRLEN i;
8012                     STRLEN d= 0;
8013                     char * e = (char *) t + len;
8014
8015                     for (i = 0; i < len; i+= UTF8SKIP(t + i)) {
8016                         U8 cur_char = t[i];
8017                         if (UTF8_IS_INVARIANT(cur_char)) {
8018                             s[d++] = cur_char;
8019                         }
8020                         else if (UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(t + i, e)) {
8021                             s[d++] = EIGHT_BIT_UTF8_TO_NATIVE(cur_char, t[i+1]);
8022                         }
8023                         else {  /* Replace illegal cp with highest collating
8024                                    one */
8025                             s[d++] = PL_strxfrm_max_cp;
8026                         }
8027                     }
8028                     s[d++] = '\0';
8029                     Renew(s, d, char);   /* Free up unused space */
8030                 }
8031             }
8032         }
8033
8034         /* Here, we have constructed a modified version of the input.  It could
8035          * be that we already had a modified copy before we did this version.
8036          * If so, that copy is no longer needed */
8037         if (t != input_string) {
8038             Safefree(t);
8039         }
8040     }
8041
8042     length_in_chars = (utf8)
8043                       ? utf8_length((U8 *) s, (U8 *) s + len)
8044                       : len;
8045
8046     /* The first element in the output is the collation id, used by
8047      * sv_collxfrm(); then comes the space for the transformed string.  The
8048      * equation should give us a good estimate as to how much is needed */
8049     xAlloc = COLLXFRM_HDR_LEN
8050            + PL_collxfrm_base
8051            + (PL_collxfrm_mult * length_in_chars);
8052     Newx(xbuf, xAlloc, char);
8053     if (UNLIKELY(! xbuf)) {
8054         DEBUG_L(PerlIO_printf(Perl_debug_log,
8055                       "mem_collxfrm_: Couldn't malloc %zu bytes\n", xAlloc));
8056         goto bad;
8057     }
8058
8059     /* Store the collation id */
8060     *(PERL_UINTMAX_T *)xbuf = PL_collation_ix;
8061
8062 #  if defined(USE_POSIX_2008_LOCALE) && defined HAS_STRXFRM_L
8063 #    ifdef USE_LOCALE_CTYPE
8064
8065     constructed_locale = newlocale(LC_CTYPE_MASK, PL_collation_name,
8066                                    duplocale(use_curlocale_scratch()));
8067 #    else
8068
8069     constructed_locale = duplocale(use_curlocale_scratch());
8070
8071 #    endif
8072 #    define my_strxfrm(dest, src, n)  strxfrm_l(dest, src, n,           \
8073                                                 constructed_locale)
8074 #    define CLEANUP_STRXFRM                                             \
8075         STMT_START {                                                    \
8076             if (constructed_locale != (locale_t) 0)                     \
8077                 freelocale(constructed_locale);                         \
8078         } STMT_END
8079 #  else
8080 #    define my_strxfrm(dest, src, n)  strxfrm(dest, src, n)
8081 #    ifdef USE_LOCALE_CTYPE
8082
8083     orig_CTYPE_locale = toggle_locale_c(LC_CTYPE, PL_collation_name);
8084
8085 #      define CLEANUP_STRXFRM                                           \
8086                 restore_toggled_locale_c(LC_CTYPE, orig_CTYPE_locale)
8087 #    else
8088 #      define CLEANUP_STRXFRM  NOOP
8089 #    endif
8090 #  endif
8091
8092     /* Then the transformation of the input.  We loop until successful, or we
8093      * give up */
8094     for (;;) {
8095
8096         errno = 0;
8097         *xlen = my_strxfrm(xbuf + COLLXFRM_HDR_LEN,
8098                            s,
8099                            xAlloc - COLLXFRM_HDR_LEN);
8100
8101
8102         /* If the transformed string occupies less space than we told strxfrm()
8103          * was available, it means it transformed the whole string. */
8104         if (*xlen < xAlloc - COLLXFRM_HDR_LEN) {
8105
8106             /* But there still could have been a problem */
8107             if (errno != 0) {
8108                 DEBUG_L(PerlIO_printf(Perl_debug_log,
8109                        "strxfrm failed for LC_COLLATE=%s; errno=%d, input=%s\n",
8110                        PL_collation_name, errno,
8111                        _byte_dump_string((U8 *) s, len, 0)));
8112                 goto bad;
8113             }
8114
8115             /* Here, the transformation was successful.  Some systems include a
8116              * trailing NUL in the returned length.  Ignore it, using a loop in
8117              * case multiple trailing NULs are returned. */
8118             while (   (*xlen) > 0
8119                    && *(xbuf + COLLXFRM_HDR_LEN + (*xlen) - 1) == '\0')
8120             {
8121                 (*xlen)--;
8122             }
8123
8124             /* If the first try didn't get it, it means our prediction was low.
8125              * Modify the coefficients so that we predict a larger value in any
8126              * future transformations */
8127             if (! first_time) {
8128                 STRLEN needed = *xlen + 1;   /* +1 For trailing NUL */
8129                 STRLEN computed_guess = PL_collxfrm_base
8130                                       + (PL_collxfrm_mult * length_in_chars);
8131
8132                 /* On zero-length input, just keep current slope instead of
8133                  * dividing by 0 */
8134                 const STRLEN new_m = (length_in_chars != 0)
8135                                      ? needed / length_in_chars
8136                                      : PL_collxfrm_mult;
8137
8138                 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
8139                     "initial size of %zu bytes for a length "
8140                     "%zu string was insufficient, %zu needed\n",
8141                     computed_guess, length_in_chars, needed));
8142
8143                 /* If slope increased, use it, but discard this result for
8144                  * length 1 strings, as we can't be sure that it's a real slope
8145                  * change */
8146                 if (length_in_chars > 1 && new_m  > PL_collxfrm_mult) {
8147
8148 #  ifdef DEBUGGING
8149
8150                     STRLEN old_m = PL_collxfrm_mult;
8151                     STRLEN old_b = PL_collxfrm_base;
8152
8153 #  endif
8154
8155                     PL_collxfrm_mult = new_m;
8156                     PL_collxfrm_base = 1;   /* +1 For trailing NUL */
8157                     computed_guess = PL_collxfrm_base
8158                                     + (PL_collxfrm_mult * length_in_chars);
8159                     if (computed_guess < needed) {
8160                         PL_collxfrm_base += needed - computed_guess;
8161                     }
8162
8163                     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
8164                                     "slope is now %zu; was %zu, base "
8165                         "is now %zu; was %zu\n",
8166                         PL_collxfrm_mult, old_m,
8167                         PL_collxfrm_base, old_b));
8168                 }
8169                 else {  /* Slope didn't change, but 'b' did */
8170                     const STRLEN new_b = needed
8171                                         - computed_guess
8172                                         + PL_collxfrm_base;
8173                     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
8174                         "base is now %zu; was %zu\n", new_b, PL_collxfrm_base));
8175                     PL_collxfrm_base = new_b;
8176                 }
8177             }
8178
8179             break;
8180         }
8181
8182         if (UNLIKELY(*xlen >= PERL_INT_MAX)) {
8183             DEBUG_L(PerlIO_printf(Perl_debug_log,
8184                   "mem_collxfrm_: Needed %zu bytes, max permissible is %u\n",
8185                   *xlen, PERL_INT_MAX));
8186             goto bad;
8187         }
8188
8189         /* A well-behaved strxfrm() returns exactly how much space it needs
8190          * (usually not including the trailing NUL) when it fails due to not
8191          * enough space being provided.  Assume that this is the case unless
8192          * it's been proven otherwise */
8193         if (LIKELY(PL_strxfrm_is_behaved) && first_time) {
8194             xAlloc = *xlen + COLLXFRM_HDR_LEN + 1;
8195         }
8196         else { /* Here, either:
8197                 *  1)  The strxfrm() has previously shown bad behavior; or
8198                 *  2)  It isn't the first time through the loop, which means
8199                 *      that the strxfrm() is now showing bad behavior, because
8200                 *      we gave it what it said was needed in the previous
8201                 *      iteration, and it came back saying it needed still more.
8202                 *      (Many versions of cygwin fit this.  When the buffer size
8203                 *      isn't sufficient, they return the input size instead of
8204                 *      how much is needed.)
8205                 * Increase the buffer size by a fixed percentage and try again.
8206                 * */
8207             xAlloc += (xAlloc / 4) + 1;
8208             PL_strxfrm_is_behaved = FALSE;
8209
8210             DEBUG_Lv(PerlIO_printf(Perl_debug_log,
8211                      "mem_collxfrm_ required more space than previously"
8212                      " calculated for locale %s, trying again with new"
8213                      " guess=%zu+%zu\n",
8214                 PL_collation_name,  COLLXFRM_HDR_LEN,
8215                      xAlloc - COLLXFRM_HDR_LEN));
8216         }
8217
8218         Renew(xbuf, xAlloc, char);
8219         if (UNLIKELY(! xbuf)) {
8220             DEBUG_L(PerlIO_printf(Perl_debug_log,
8221                       "mem_collxfrm_: Couldn't realloc %zu bytes\n", xAlloc));
8222             goto bad;
8223         }
8224
8225         first_time = FALSE;
8226     }
8227
8228     CLEANUP_STRXFRM;
8229
8230     DEBUG_L(print_collxfrm_input_and_return(s, s + len, xbuf, *xlen, utf8));
8231
8232     /* Free up unneeded space; retain enough for trailing NUL */
8233     Renew(xbuf, COLLXFRM_HDR_LEN + *xlen + 1, char);
8234
8235     if (s != input_string) {
8236         Safefree(s);
8237     }
8238
8239     return xbuf;
8240
8241   bad:
8242
8243     CLEANUP_STRXFRM;
8244     DEBUG_L(print_collxfrm_input_and_return(s, s + len, NULL, 0, utf8));
8245
8246     Safefree(xbuf);
8247     if (s != input_string) {
8248         Safefree(s);
8249     }
8250     *xlen = 0;
8251
8252     return NULL;
8253 }
8254
8255 #  ifdef DEBUGGING
8256
8257 STATIC void
8258 S_print_collxfrm_input_and_return(pTHX_
8259                                   const char * s,
8260                                   const char * e,
8261                                   const char * xbuf,
8262                                   const STRLEN xlen,
8263                                   const bool is_utf8)
8264 {
8265
8266     PERL_ARGS_ASSERT_PRINT_COLLXFRM_INPUT_AND_RETURN;
8267
8268     PerlIO_printf(Perl_debug_log,
8269                   "mem_collxfrm_[ix %" UVuf "] for locale '%s':\n"
8270                   "     input=%s\n    return=%s\n    return len=%zu\n",
8271                   (UV) PL_collation_ix, PL_collation_name,
8272                   get_displayable_string(s, e, is_utf8),
8273                   ((xbuf == NULL)
8274                    ? "(null)"
8275                    : ((xlen == 0)
8276                       ? "(empty)"
8277                       : _byte_dump_string((U8 *) xbuf + COLLXFRM_HDR_LEN,
8278                                           xlen, 0))),
8279                   xlen);
8280 }
8281
8282 #  endif    /* DEBUGGING */
8283
8284 SV *
8285 Perl_strxfrm(pTHX_ SV * src)
8286 {
8287     PERL_ARGS_ASSERT_STRXFRM;
8288
8289     /* For use by POSIX::strxfrm().  If they differ, toggle LC_CTYPE to
8290      * LC_COLLATE to avoid potential mojibake.
8291      *
8292      * If we can't calculate a collation, 'src' is instead returned, so that
8293      * future comparisons will be by code point order */
8294
8295 #  ifdef USE_LOCALE_CTYPE
8296
8297     const char * orig_ctype = toggle_locale_c(LC_CTYPE,
8298                                               querylocale_c(LC_COLLATE));
8299 #  endif
8300
8301     SV * dst = src;
8302     STRLEN dstlen;
8303     STRLEN srclen;
8304     const char *p = SvPV_const(src, srclen);
8305     const U32 utf8_flag = SvUTF8(src);
8306     char *d = mem_collxfrm_(p, srclen, &dstlen, cBOOL(utf8_flag));
8307
8308     assert(utf8_flag == 0 || utf8_flag == SVf_UTF8);
8309
8310     if (d != NULL) {
8311         assert(dstlen > 0);
8312         dst =newSVpvn_flags(d + COLLXFRM_HDR_LEN,
8313                             dstlen, SVs_TEMP|utf8_flag);
8314         Safefree(d);
8315     }
8316
8317 #  ifdef USE_LOCALE_CTYPE
8318
8319     restore_toggled_locale_c(LC_CTYPE, orig_ctype);
8320
8321 #  endif
8322
8323     return dst;
8324 }
8325
8326 #endif /* USE_LOCALE_COLLATE */
8327 #ifdef USE_LOCALE
8328
8329 STATIC const char *
8330 S_toggle_locale_i(pTHX_ const unsigned cat_index,
8331                         const char * new_locale,
8332                         const line_t caller_line)
8333 {
8334     PERL_ARGS_ASSERT_TOGGLE_LOCALE_I;
8335     assert(cat_index <= LC_ALL_INDEX_);
8336
8337     /* Changes the locale for the category specified by 'index' to 'new_locale,
8338      * if they aren't already the same.
8339      *
8340      * Returns a copy of the name of the original locale for 'cat_index'
8341      * so can be switched back to with the companion function
8342      * restore_toggled_locale_i(),  (NULL if no restoral is necessary.) */
8343
8344     /* Find the original locale of the category we may need to change, so that
8345      * it can be restored to later */
8346     const char * locale_to_restore_to = querylocale_i(cat_index);
8347
8348     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
8349              "(%" LINE_Tf "): toggle_locale_i: index=%d(%s), wanted=%s,"
8350              " actual=%s\n",
8351              caller_line, cat_index, category_names[cat_index],
8352              new_locale, locale_to_restore_to));
8353
8354     if (! locale_to_restore_to) {
8355         locale_panic_via_(Perl_form(aTHX_
8356                                     "Could not find current %s locale",
8357                                     category_names[cat_index]),
8358                          __FILE__, caller_line);
8359     }
8360
8361     /* If the locales are the same, there's nothing to do */
8362     if (strEQ(locale_to_restore_to, new_locale)) {
8363         DEBUG_Lv(PerlIO_printf(Perl_debug_log,
8364                                "(%" LINE_Tf "): %s locale unchanged as %s\n",
8365                                caller_line, category_names[cat_index],
8366                                new_locale));
8367
8368         return NULL;
8369     }
8370
8371     /* Finally, change the locale to the new one */
8372     void_setlocale_i_with_caller(cat_index, new_locale, __FILE__, caller_line);
8373
8374     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
8375                            "(%" LINE_Tf "): %s locale switched to %s\n",
8376                            caller_line, category_names[cat_index], new_locale));
8377
8378     return locale_to_restore_to;
8379
8380 #  ifndef DEBUGGING
8381     PERL_UNUSED_ARG(caller_line);
8382 #  endif
8383
8384 }
8385
8386 STATIC void
8387 S_restore_toggled_locale_i(pTHX_ const unsigned int cat_index,
8388                                  const char * restore_locale,
8389                                  const line_t caller_line)
8390 {
8391     /* Restores the locale for LC_category corresponding to cat_index to
8392      * 'restore_locale' (which is a copy that will be freed by this function),
8393      * or do nothing if the latter parameter is NULL */
8394
8395     PERL_ARGS_ASSERT_RESTORE_TOGGLED_LOCALE_I;
8396     assert(cat_index <= LC_ALL_INDEX_);
8397
8398     if (restore_locale == NULL) {
8399         DEBUG_Lv(PerlIO_printf(Perl_debug_log,
8400                                "(%" LINE_Tf "): No need to restore %s\n",
8401                                caller_line, category_names[cat_index]));
8402         return;
8403     }
8404
8405     DEBUG_Lv(PerlIO_printf(Perl_debug_log,
8406                            "(%" LINE_Tf "): %s restoring locale to %s\n",
8407                            caller_line, category_names[cat_index],
8408                            restore_locale));
8409
8410     void_setlocale_i_with_caller(cat_index, restore_locale,
8411                                   __FILE__, caller_line);
8412
8413 #  ifndef DEBUGGING
8414     PERL_UNUSED_ARG(caller_line);
8415 #  endif
8416
8417 }
8418
8419 #  ifdef USE_LOCALE_CTYPE
8420
8421 STATIC bool
8422 S_is_codeset_name_UTF8(const char * name)
8423 {
8424     /* Return a boolean as to if the passed-in name indicates it is a UTF-8
8425      * code set.  Several variants are possible */
8426     const Size_t len = strlen(name);
8427
8428     PERL_ARGS_ASSERT_IS_CODESET_NAME_UTF8;
8429
8430 #    ifdef WIN32
8431
8432     /* http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756.aspx */
8433     if (memENDs(name, len, "65001")) {
8434         return TRUE;
8435     }
8436
8437 #    endif
8438                /* 'UTF8' or 'UTF-8' */
8439     return (    inRANGE(len, 4, 5)
8440             &&  name[len-1] == '8'
8441             && (   memBEGINs(name, len, "UTF")
8442                 || memBEGINs(name, len, "utf"))
8443             && (len == 4 || name[3] == '-'));
8444 }
8445
8446 #  endif
8447 #endif  /* USE_LOCALE */
8448
8449 bool
8450 Perl__is_in_locale_category(pTHX_ const bool compiling, const int category)
8451 {
8452     /* Internal function which returns if we are in the scope of a pragma that
8453      * enables the locale category 'category'.  'compiling' should indicate if
8454      * this is during the compilation phase (TRUE) or not (FALSE). */
8455
8456     const COP * const cop = (compiling) ? &PL_compiling : PL_curcop;
8457
8458     SV *these_categories = cop_hints_fetch_pvs(cop, "locale", 0);
8459     if (! these_categories || these_categories == &PL_sv_placeholder) {
8460         return FALSE;
8461     }
8462
8463     /* The pseudo-category 'not_characters' is -1, so just add 1 to each to get
8464      * a valid unsigned */
8465     assert(category >= -1);
8466     return cBOOL(SvUV(these_categories) & (1U << (category + 1)));
8467 }
8468
8469 /* my_strerror() returns a mortalized copy of the text of the error message
8470  * associated with 'errnum'.
8471  *
8472  * If not called from within the scope of 'use locale', it uses the text from
8473  * the C locale.  If Perl is compiled to not pay attention to LC_CTYPE nor
8474  * LC_MESSAGES, it uses whatever strerror() returns.  Otherwise the text is
8475  * derived from the locale, LC_MESSAGES if we have that; LC_CTYPE if not.
8476  *
8477  * It returns in *utf8ness the result's UTF-8ness
8478  *
8479  * The function just calls strerror(), but temporarily switches locales, if
8480  * needed.  Many platforms require LC_CTYPE and LC_MESSAGES to be in the same
8481  * CODESET in order for the return from strerror() to not contain '?' symbols,
8482  * or worse, mojibaked.  It's cheaper to just use the stricter criteria of
8483  * being in the same locale.  So the code below uses a common locale for both
8484  * categories.  Again, that is C if not within 'use locale' scope; or the
8485  * LC_MESSAGES locale if in scope and we have that category; and LC_CTYPE if we
8486  * don't have LC_MESSAGES; and whatever strerror returns if we don't have
8487  * either category.
8488  *
8489  * There are two sets of implementations.  The first below is if we have
8490  * strerror_l().  This is the simpler.  We just use the already-built C locale
8491  * object if not in locale scope, or build up a custom one otherwise.
8492  *
8493  * When strerror_l() is not available, we may have to swap locales temporarily
8494  * to bring the two categories into sync with each other, and possibly to the C
8495  * locale.
8496  *
8497  * Because the prepropessing directives to conditionally compile this function
8498  * would greatly obscure the logic of the various implementations, the whole
8499  * function is repeated for each configuration, with some common macros. */
8500
8501 /* Used to shorten the definitions of the following implementations of
8502  * my_strerror() */
8503 #define DEBUG_STRERROR_ENTER(errnum, in_locale)                             \
8504     DEBUG_Lv(PerlIO_printf(Perl_debug_log,                                  \
8505                            "my_strerror called with errnum %d;"             \
8506                            " Within locale scope=%d\n",                     \
8507                            errnum, in_locale))
8508
8509 #define DEBUG_STRERROR_RETURN(errstr, utf8ness)                             \
8510     DEBUG_Lv(PerlIO_printf(Perl_debug_log,                                  \
8511                            "Strerror returned; saving a copy: '%s';"        \
8512                            " utf8ness=%d\n",                                \
8513                            get_displayable_string(errstr,                   \
8514                                                   errstr + strlen(errstr),  \
8515                                                   *utf8ness),               \
8516                            (int) *utf8ness))
8517
8518 /* On platforms that have precisely one of these categories (Windows
8519  * qualifies), these yield the correct one */
8520 #if defined(USE_LOCALE_CTYPE)
8521 #  define WHICH_LC_INDEX LC_CTYPE_INDEX_
8522 #elif defined(USE_LOCALE_MESSAGES)
8523 #  define WHICH_LC_INDEX LC_MESSAGES_INDEX_
8524 #endif
8525
8526 /*===========================================================================*/
8527 /* First set of implementations, when have strerror_l() */
8528
8529 #if defined(USE_POSIX_2008_LOCALE) && defined(HAS_STRERROR_L)
8530
8531 #  if ! defined(USE_LOCALE_CTYPE) && ! defined(USE_LOCALE_MESSAGES)
8532
8533 /* Here, neither category is defined: use the C locale */
8534 const char *
8535 Perl_my_strerror(pTHX_ const int errnum, utf8ness_t * utf8ness)
8536 {
8537     PERL_ARGS_ASSERT_MY_STRERROR;
8538
8539     DEBUG_STRERROR_ENTER(errnum, 0);
8540
8541     const char *errstr = savepv(strerror_l(errnum, PL_C_locale_obj));
8542     *utf8ness = UTF8NESS_IMMATERIAL;
8543
8544     DEBUG_STRERROR_RETURN(errstr, utf8ness);
8545
8546     SAVEFREEPV(errstr);
8547     return errstr;
8548 }
8549
8550 #  elif ! defined(USE_LOCALE_CTYPE) || ! defined(USE_LOCALE_MESSAGES)
8551
8552 /*--------------------------------------------------------------------------*/
8553
8554 /* Here one or the other of CTYPE or MESSAGES is defined, but not both.  If we
8555  * are not within 'use locale' scope of the only one defined, we use the C
8556  * locale; otherwise use the current locale object */
8557
8558 const char *
8559 Perl_my_strerror(pTHX_ const int errnum, utf8ness_t * utf8ness)
8560 {
8561     PERL_ARGS_ASSERT_MY_STRERROR;
8562
8563     DEBUG_STRERROR_ENTER(errnum, IN_LC(categories[WHICH_LC_INDEX]));
8564
8565     /* Use C if not within locale scope;  Otherwise, use current locale */
8566     const locale_t which_obj = (IN_LC(categories[WHICH_LC_INDEX]))
8567                                ? PL_C_locale_obj
8568                                : use_curlocale_scratch();
8569
8570     const char *errstr = savepv(strerror_l(errnum, which_obj));
8571     *utf8ness = get_locale_string_utf8ness_i(errstr, LOCALE_UTF8NESS_UNKNOWN,
8572                                              NULL, WHICH_LC_INDEX);
8573     DEBUG_STRERROR_RETURN(errstr, utf8ness);
8574
8575     SAVEFREEPV(errstr);
8576     return errstr;
8577 }
8578
8579 /*--------------------------------------------------------------------------*/
8580 #  else     /* Are using both categories.  Place them in the same CODESET,
8581              * either C or the LC_MESSAGES locale */
8582
8583 const char *
8584 Perl_my_strerror(pTHX_ const int errnum, utf8ness_t * utf8ness)
8585 {
8586     PERL_ARGS_ASSERT_MY_STRERROR;
8587
8588     DEBUG_STRERROR_ENTER(errnum, IN_LC(LC_MESSAGES));
8589
8590     const char *errstr;
8591     if (! IN_LC(LC_MESSAGES)) {    /* Use C if not within locale scope */
8592         errstr = savepv(strerror_l(errnum, PL_C_locale_obj));
8593         *utf8ness = UTF8NESS_IMMATERIAL;
8594     }
8595     else {  /* Otherwise, use the LC_MESSAGES locale, making sure LC_CTYPE
8596                matches */
8597         locale_t cur = duplocale(use_curlocale_scratch());
8598
8599         cur = newlocale(LC_CTYPE_MASK, querylocale_c(LC_MESSAGES), cur);
8600         errstr = savepv(strerror_l(errnum, cur));
8601         *utf8ness = get_locale_string_utf8ness_i(errstr,
8602                                                  LOCALE_UTF8NESS_UNKNOWN,
8603                                                  NULL, LC_MESSAGES_INDEX_);
8604         freelocale(cur);
8605     }
8606
8607     DEBUG_STRERROR_RETURN(errstr, utf8ness);
8608
8609     SAVEFREEPV(errstr);
8610     return errstr;
8611 }
8612 #  endif    /* Above is using strerror_l */
8613 /*===========================================================================*/
8614 #else       /* Below is not using strerror_l */
8615 #  if ! defined(USE_LOCALE_CTYPE) && ! defined(USE_LOCALE_MESSAGES)
8616
8617 /* If not using using either of the categories, return plain, unadorned
8618  * strerror */
8619
8620 const char *
8621 Perl_my_strerror(pTHX_ const int errnum, utf8ness_t * utf8ness)
8622 {
8623     PERL_ARGS_ASSERT_MY_STRERROR;
8624
8625     DEBUG_STRERROR_ENTER(errnum, 0);
8626
8627     const char *errstr = savepv(Strerror(errnum));
8628     *utf8ness = UTF8NESS_IMMATERIAL;
8629
8630     DEBUG_STRERROR_RETURN(errstr, utf8ness);
8631
8632     SAVEFREEPV(errstr);
8633     return errstr;
8634 }
8635
8636 /*--------------------------------------------------------------------------*/
8637 #  elif ! defined(USE_LOCALE_CTYPE) || ! defined(USE_LOCALE_MESSAGES)
8638
8639 /* Here one or the other of CTYPE or MESSAGES is defined, but not both.  If we
8640  * are not within 'use locale' scope of the only one defined, we use the C
8641  * locale; otherwise use the current locale */
8642
8643 const char *
8644 Perl_my_strerror(pTHX_ const int errnum, utf8ness_t * utf8ness)
8645 {
8646     PERL_ARGS_ASSERT_MY_STRERROR;
8647
8648     DEBUG_STRERROR_ENTER(errnum, IN_LC(categories[WHICH_LC_INDEX]));
8649
8650     const char *errstr;
8651     if (IN_LC(categories[WHICH_LC_INDEX])) {
8652         errstr = savepv(Strerror(errnum));
8653         *utf8ness = get_locale_string_utf8ness_i(errstr,
8654                                                  LOCALE_UTF8NESS_UNKNOWN,
8655                                                  NULL, WHICH_LC_INDEX);
8656     }
8657     else {
8658
8659         LOCALE_LOCK;
8660
8661         const char * orig_locale = toggle_locale_i(WHICH_LC_INDEX, "C");
8662
8663         errstr = savepv(Strerror(errnum));
8664
8665         restore_toggled_locale_i(WHICH_LC_INDEX, orig_locale);
8666
8667         LOCALE_UNLOCK;
8668
8669         *utf8ness = UTF8NESS_IMMATERIAL;
8670     }
8671
8672     DEBUG_STRERROR_RETURN(errstr, utf8ness);
8673
8674     SAVEFREEPV(errstr);
8675     return errstr;
8676 }
8677
8678 /*--------------------------------------------------------------------------*/
8679 #  else
8680
8681 /* Below, have both LC_CTYPE and LC_MESSAGES.  Place them in the same CODESET,
8682  * either C or the LC_MESSAGES locale */
8683
8684 const char *
8685 Perl_my_strerror(pTHX_ const int errnum, utf8ness_t * utf8ness)
8686 {
8687     PERL_ARGS_ASSERT_MY_STRERROR;
8688
8689     DEBUG_STRERROR_ENTER(errnum, IN_LC(LC_MESSAGES));
8690
8691     const char * desired_locale = (IN_LC(LC_MESSAGES))
8692                                   ? querylocale_c(LC_MESSAGES)
8693                                   : "C";
8694     /* XXX Can fail on z/OS */
8695
8696     LOCALE_LOCK;
8697
8698     const char* orig_CTYPE_locale    = toggle_locale_c(LC_CTYPE,
8699                                                        desired_locale);
8700     const char* orig_MESSAGES_locale = toggle_locale_c(LC_MESSAGES,
8701                                                        desired_locale);
8702     const char *errstr = savepv(Strerror(errnum));
8703
8704     restore_toggled_locale_c(LC_MESSAGES, orig_MESSAGES_locale);
8705     restore_toggled_locale_c(LC_CTYPE, orig_CTYPE_locale);
8706
8707     LOCALE_UNLOCK;
8708
8709     *utf8ness = get_locale_string_utf8ness_i(errstr, LOCALE_UTF8NESS_UNKNOWN,
8710                                              NULL, LC_MESSAGES_INDEX_);
8711     DEBUG_STRERROR_RETURN(errstr, utf8ness);
8712
8713     SAVEFREEPV(errstr);
8714     return errstr;
8715 }
8716
8717 /*--------------------------------------------------------------------------*/
8718 #  endif /* end of not using strerror_l() */
8719 #endif   /* end of all the my_strerror() implementations */
8720
8721 /*
8722
8723 =for apidoc switch_to_global_locale
8724
8725 This function copies the locale state of the calling thread into the program's
8726 global locale, and converts the thread to use that global locale.
8727
8728 It is intended so that Perl can safely be used with C libraries that access the
8729 global locale and which can't be converted to not access it.  Effectively, this
8730 means libraries that call C<L<setlocale(3)>> on non-Windows systems.  (For
8731 portability, it is a good idea to use it on Windows as well.)
8732
8733 A downside of using it is that it disables the services that Perl provides to
8734 hide locale gotchas from your code.  The service you most likely will miss
8735 regards the radix character (decimal point) in floating point numbers.  Code
8736 executed after this function is called can no longer just assume that this
8737 character is correct for the current circumstances.
8738
8739 To return to Perl control, and restart the gotcha prevention services, call
8740 C<L</sync_locale>>.  Behavior is undefined for any pure Perl code that executes
8741 while the switch is in effect.
8742
8743 The global locale and the per-thread locales are independent.  As long as just
8744 one thread converts to the global locale, everything works smoothly.  But if
8745 more than one does, they can easily interfere with each other, and races are
8746 likely.  On Windows systems prior to Visual Studio 15 (at which point Microsoft
8747 fixed a bug), races can occur (even if only one thread has been converted to
8748 the global locale), but only if you use the following operations:
8749
8750 =over
8751
8752 =item L<POSIX::localeconv|POSIX/localeconv>
8753
8754 =item L<I18N::Langinfo>, items C<CRNCYSTR> and C<THOUSEP>
8755
8756 =item L<perlapi/Perl_langinfo>, items C<CRNCYSTR> and C<THOUSEP>
8757
8758 =back
8759
8760 The first item is not fixable (except by upgrading to a later Visual Studio
8761 release), but it would be possible to work around the latter two items by
8762 having Perl change its algorithm for calculating these to use Windows API
8763 functions (likely C<GetNumberFormat> and C<GetCurrencyFormat>); patches
8764 welcome.
8765
8766 XS code should never call plain C<setlocale>, but should instead be converted
8767 to either call L<C<Perl_setlocale>|perlapi/Perl_setlocale> (which is a drop-in
8768 for the system C<setlocale>) or use the methods given in L<perlcall> to call
8769 L<C<POSIX::setlocale>|POSIX/setlocale>.  Either one will transparently properly
8770 handle all cases of single- vs multi-thread, POSIX 2008-supported or not.
8771
8772 =cut
8773 */
8774
8775 #if defined(WIN32) && defined(USE_THREAD_SAFE_LOCALE)
8776 #  define CHANGE_SYSTEM_LOCALE_TO_GLOBAL                                \
8777     STMT_START {                                                        \
8778         if (_configthreadlocale(_DISABLE_PER_THREAD_LOCALE) == -1) {    \
8779             locale_panic_("_configthreadlocale returned an error");     \
8780         }                                                               \
8781     } STMT_END
8782 #elif defined(USE_POSIX_2008_LOCALE)
8783 #  define CHANGE_SYSTEM_LOCALE_TO_GLOBAL                                \
8784     STMT_START {                                                        \
8785         locale_t old_locale = uselocale(LC_GLOBAL_LOCALE);              \
8786         if (! old_locale) {                                             \
8787             locale_panic_("Could not change to global locale");         \
8788         }                                                               \
8789                                                                         \
8790         /* Free the per-thread memory */                                \
8791         if (   old_locale != LC_GLOBAL_LOCALE                           \
8792             && old_locale != PL_C_locale_obj)                           \
8793         {                                                               \
8794             freelocale(old_locale);                                     \
8795         }                                                               \
8796     } STMT_END
8797 #else
8798 #  define CHANGE_SYSTEM_LOCALE_TO_GLOBAL
8799 #endif
8800
8801 void
8802 Perl_switch_to_global_locale(pTHX)
8803 {
8804
8805 #ifdef USE_LOCALE
8806
8807     DEBUG_L(PerlIO_printf(Perl_debug_log, "Entering switch_to_global; %s\n",
8808                                           get_LC_ALL_display()));
8809
8810    /* In these cases, we use the system state to determine if we are in the
8811     * global locale or not. */
8812 #  ifdef USE_POSIX_2008_LOCALE
8813
8814     const bool perl_controls = (LC_GLOBAL_LOCALE != uselocale((locale_t) 0));
8815
8816 #  elif defined(USE_THREAD_SAFE_LOCALE) && defined(WIN32)
8817
8818     int config_return = _configthreadlocale(0);
8819     if (config_return == -1) {
8820         locale_panic_("_configthreadlocale returned an error");
8821     }
8822     const bool perl_controls = (config_return == _ENABLE_PER_THREAD_LOCALE);
8823
8824 #  else
8825
8826     const bool perl_controls = false;
8827
8828 #  endif
8829
8830     /* No-op if already in global */
8831     if (! perl_controls) {
8832         return;
8833     }
8834
8835 #  ifdef LC_ALL
8836
8837     const char * thread_locale = calculate_LC_ALL_string(NULL,
8838                                                          EXTERNAL_FORMAT_FOR_SET,
8839                                                          WANT_TEMP_PV,
8840                                                          __LINE__);
8841     CHANGE_SYSTEM_LOCALE_TO_GLOBAL;
8842     posix_setlocale(LC_ALL, thread_locale);
8843
8844 #  else   /* Must be USE_POSIX_2008_LOCALE) */
8845
8846     const char * cur_thread_locales[LC_ALL_INDEX_];
8847
8848     /* Save each category's current per-thread state */
8849     for (unsigned i = 0; i < LC_ALL_INDEX_; i++) {
8850         cur_thread_locales[i] = querylocale_i(i);
8851     }
8852
8853     CHANGE_SYSTEM_LOCALE_TO_GLOBAL;
8854
8855     /* Set the global to what was our per-thread state */
8856     POSIX_SETLOCALE_LOCK;
8857     for (unsigned int i = 0; i < LC_ALL_INDEX_; i++) {
8858         posix_setlocale(categories[i], cur_thread_locales[i]);
8859     }
8860     POSIX_SETLOCALE_UNLOCK;
8861
8862 #  endif
8863 #  ifdef USE_LOCALE_NUMERIC
8864
8865     /* Switch to the underlying C numeric locale; the application is on its
8866      * own. */
8867     POSIX_SETLOCALE_LOCK;
8868     posix_setlocale(LC_NUMERIC, PL_numeric_name);
8869     POSIX_SETLOCALE_UNLOCK;
8870
8871 #  endif
8872 #endif
8873
8874 }
8875
8876 /*
8877
8878 =for apidoc sync_locale
8879
8880 This function copies the state of the program global locale into the calling
8881 thread, and converts that thread to using per-thread locales, if it wasn't
8882 already, and the platform supports them.  The LC_NUMERIC locale is toggled into
8883 the standard state (using the C locale's conventions), if not within the
8884 lexical scope of S<C<use locale>>.
8885
8886 Perl will now consider itself to have control of the locale.
8887
8888 Since unthreaded perls have only a global locale, this function is a no-op
8889 without threads.
8890
8891 This function is intended for use with C libraries that do locale manipulation.
8892 It allows Perl to accommodate the use of them.  Call this function before
8893 transferring back to Perl space so that it knows what state the C code has left
8894 things in.
8895
8896 XS code should not manipulate the locale on its own.  Instead,
8897 L<C<Perl_setlocale>|perlapi/Perl_setlocale> can be used at any time to query or
8898 change the locale (though changing the locale is antisocial and dangerous on
8899 multi-threaded systems that don't have multi-thread safe locale operations.
8900 (See L<perllocale/Multi-threaded operation>).
8901
8902 Using the libc L<C<setlocale(3)>> function should be avoided.  Nevertheless,
8903 certain non-Perl libraries called from XS, do call it, and their behavior may
8904 not be able to be changed.  This function, along with
8905 C<L</switch_to_global_locale>>, can be used to get seamless behavior in these
8906 circumstances, as long as only one thread is involved.
8907
8908 If the library has an option to turn off its locale manipulation, doing that is
8909 preferable to using this mechanism.  C<Gtk> is such a library.
8910
8911 The return value is a boolean: TRUE if the global locale at the time of call
8912 was in effect for the caller; and FALSE if a per-thread locale was in effect.
8913
8914 =cut
8915 */
8916
8917 bool
8918 Perl_sync_locale(pTHX)
8919 {
8920
8921 #ifndef USE_LOCALE
8922
8923     return TRUE;
8924
8925 #else
8926
8927     bool was_in_global = TRUE;
8928
8929 #  ifdef USE_THREAD_SAFE_LOCALE
8930 #    if defined(WIN32)
8931
8932     int config_return = _configthreadlocale(_DISABLE_PER_THREAD_LOCALE);
8933     if (config_return == -1) {
8934         locale_panic_("_configthreadlocale returned an error");
8935     }
8936     was_in_global = (config_return == _DISABLE_PER_THREAD_LOCALE);
8937
8938 #    elif defined(USE_POSIX_2008_LOCALE)
8939
8940     was_in_global = (LC_GLOBAL_LOCALE == uselocale(LC_GLOBAL_LOCALE));
8941
8942 #    else
8943 #      error Unexpected Configuration
8944 #    endif
8945 #  endif    /* USE_THREAD_SAFE_LOCALE */
8946
8947     /* Here, we are in the global locale.  Get and save the values for each
8948      * category, and convert the current thread to use them */
8949
8950 #  ifdef LC_ALL
8951
8952     STDIZED_SETLOCALE_LOCK;
8953     const char * lc_all_string = savepv(stdized_setlocale(LC_ALL, NULL));
8954     STDIZED_SETLOCALE_UNLOCK;
8955
8956     give_perl_locale_control(lc_all_string, __LINE__);
8957     Safefree(lc_all_string);
8958
8959 #  else
8960
8961     const char * current_globals[LC_ALL_INDEX_];
8962     for (unsigned i = 0; i < LC_ALL_INDEX_; i++) {
8963         STDIZED_SETLOCALE_LOCK;
8964         current_globals[i] = savepv(stdized_setlocale(categories[i], NULL));
8965         STDIZED_SETLOCALE_UNLOCK;
8966     }
8967
8968     give_perl_locale_control((const char **) &current_globals, __LINE__);
8969
8970     for (unsigned i = 0; i < LC_ALL_INDEX_; i++) {
8971         Safefree(current_globals[i]);
8972     }
8973
8974 #  endif
8975
8976     return was_in_global;
8977
8978 #endif
8979
8980 }
8981
8982 #if defined(DEBUGGING) && defined(USE_LOCALE)
8983
8984 STATIC char *
8985 S_my_setlocale_debug_string_i(pTHX_
8986                               const unsigned cat_index,
8987                               const char* locale, /* Optional locale name */
8988
8989                               /* return value from setlocale() when attempting
8990                                * to set 'category' to 'locale' */
8991                               const char* retval,
8992
8993                               const line_t line)
8994 {
8995     /* Returns a pointer to a NUL-terminated string in static storage with
8996      * added text about the info passed in.  This is not thread safe and will
8997      * be overwritten by the next call, so this should be used just to
8998      * formulate a string to immediately print or savepv() on. */
8999
9000     const char * locale_quote;
9001     const char * retval_quote;
9002
9003     assert(cat_index <= LC_ALL_INDEX_);
9004
9005     if (locale == NULL) {
9006         locale_quote = "";
9007         locale = "NULL";
9008     }
9009     else {
9010         locale_quote = "\"";
9011     }
9012
9013     if (retval == NULL) {
9014         retval_quote = "";
9015         retval = "NULL";
9016     }
9017     else {
9018         retval_quote = "\"";
9019     }
9020
9021 #  ifdef USE_LOCALE_THREADS
9022 #    define THREAD_FORMAT "%p:"
9023 #    define THREAD_ARGUMENT aTHX_
9024 #  else
9025 #    define THREAD_FORMAT
9026 #    define THREAD_ARGUMENT
9027 #  endif
9028
9029     return Perl_form(aTHX_
9030                      "%s:%" LINE_Tf ": " THREAD_FORMAT
9031                      " setlocale(%s[%d], %s%s%s) returned %s%s%s\n",
9032
9033                      __FILE__, line, THREAD_ARGUMENT
9034                      category_names[cat_index], categories[cat_index],
9035                      locale_quote, locale, locale_quote,
9036                      retval_quote, retval, retval_quote);
9037 }
9038
9039 #endif
9040 #ifdef USE_PERL_SWITCH_LOCALE_CONTEXT
9041
9042 void
9043 Perl_switch_locale_context(pTHX)
9044 {
9045     /* libc keeps per-thread locale status information in some configurations.
9046      * So, we can't just switch out aTHX to switch to a new thread.  libc has
9047      * to follow along.  This routine does that based on per-interpreter
9048      * variables we keep just for this purpose.
9049      *
9050      * There are two implementations where this is an issue.  For the other
9051      * implementations, it doesn't matter because libc is using global values
9052      * that all threads know about.
9053      *
9054      * The two implementations are where libc keeps thread-specific information
9055      * on its own.  These are
9056      *
9057      * POSIX 2008:  The current locale is kept by libc as an object.  We save
9058      *              a copy of that in the per-thread PL_cur_locale_obj, and so
9059      *              this routine uses that copy to tell the thread it should be
9060      *              operating with that object
9061      * Windows thread-safe locales:  A given thread in Windows can be being run
9062      *              with per-thread locales, or not.  When the thread context
9063      *              changes, libc doesn't automatically know if the thread is
9064      *              using per-thread locales, nor does it know what the new
9065      *              thread's locale is.  We keep that information in the
9066      *              per-thread variables:
9067      *                  PL_controls_locale  indicates if this thread is using
9068      *                                      per-thread locales or not
9069      *                  PL_cur_LC_ALL       indicates what the the locale
9070      *                                      should be if it is a per-thread
9071      *                                      locale.
9072      */
9073
9074     if (UNLIKELY(   PL_veto_switch_non_tTHX_context
9075                  || PL_phase == PERL_PHASE_CONSTRUCT))
9076     {
9077         return;
9078     }
9079
9080 #  ifdef USE_POSIX_2008_LOCALE
9081
9082     if (! uselocale(PL_cur_locale_obj)) {
9083         locale_panic_(Perl_form(aTHX_
9084                                 "Can't uselocale(%p), LC_ALL supposed to"
9085                                 " be '%s'",
9086                                 PL_cur_locale_obj, get_LC_ALL_display()));
9087     }
9088
9089 #  elif defined(WIN32)
9090
9091     if (! bool_setlocale_c(LC_ALL, PL_cur_LC_ALL)) {
9092         locale_panic_(Perl_form(aTHX_ "Can't setlocale(%s)", PL_cur_LC_ALL));
9093     }
9094
9095 #  endif
9096
9097 }
9098
9099 #endif
9100
9101 void
9102 Perl_thread_locale_init(pTHX)
9103 {
9104
9105 #ifdef USE_THREAD_SAFE_LOCALE
9106 #  ifdef USE_POSIX_2008_LOCALE
9107
9108     /* Called from a thread on startup.
9109      *
9110      * The operations here have to be done from within the calling thread, as
9111      * they affect libc's knowledge of the thread; libc has no knowledge of
9112      * aTHX */
9113
9114      DEBUG_L(PerlIO_printf(Perl_debug_log,
9115                            "new thread, initial locale is %s;"
9116                            " calling setlocale(LC_ALL, \"C\")\n",
9117                            get_LC_ALL_display()));
9118
9119     if (! uselocale(PL_C_locale_obj)) {
9120
9121         /* Not being able to change to the C locale is severe; don't keep
9122          * going.  */
9123         locale_panic_(Perl_form(aTHX_
9124                                 "Can't uselocale(%p), 'C'", PL_C_locale_obj));
9125         NOT_REACHED; /* NOTREACHED */
9126     }
9127
9128 #    ifdef MULTIPLICITY
9129
9130     PL_cur_locale_obj = PL_C_locale_obj;
9131
9132 #    endif
9133 #  elif defined(WIN32)
9134
9135     /* On Windows, make sure new thread has per-thread locales enabled */
9136     if (_configthreadlocale(_ENABLE_PER_THREAD_LOCALE) == -1) {
9137         locale_panic_("_configthreadlocale returned an error");
9138     }
9139     void_setlocale_c(LC_ALL, "C");
9140
9141 #  endif
9142 #endif
9143
9144 }
9145
9146 void
9147 Perl_thread_locale_term(pTHX)
9148 {
9149     /* Called from a thread as it gets ready to terminate.
9150      *
9151      * The operations here have to be done from within the calling thread, as
9152      * they affect libc's knowledge of the thread; libc has no knowledge of
9153      * aTHX */
9154
9155 #if defined(USE_POSIX_2008_LOCALE) && defined(USE_THREADS)
9156
9157     /* Switch to the global locale, so can free up the per-thread object */
9158     locale_t actual_obj = uselocale(LC_GLOBAL_LOCALE);
9159     if (actual_obj != LC_GLOBAL_LOCALE && actual_obj != PL_C_locale_obj) {
9160         freelocale(actual_obj);
9161     }
9162
9163     /* Prevent leaks even if something has gone wrong */
9164     locale_t expected_obj = PL_cur_locale_obj;
9165     if (UNLIKELY(   expected_obj != actual_obj
9166                  && expected_obj != LC_GLOBAL_LOCALE
9167                  && expected_obj != PL_C_locale_obj))
9168     {
9169         freelocale(expected_obj);
9170     }
9171
9172     PL_cur_locale_obj = LC_GLOBAL_LOCALE;
9173
9174 #endif
9175 #ifdef WIN32_USE_FAKE_OLD_MINGW_LOCALES
9176
9177     /* When faking the mingw implementation, we coerce this function into doing
9178      * something completely different from its intent -- namely to free up our
9179      * static buffer to avoid a leak.  This function gets called for each
9180      * thread that is terminating, so will give us a chance to free the buffer
9181      * from the appropriate pool.  On unthreaded systems, it gets called by the
9182      * mutex termination code. */
9183
9184 #  ifdef MULTIPLICITY
9185
9186     if (aTHX != wsetlocale_buf_aTHX) {
9187         return;
9188     }
9189
9190 #  endif
9191
9192     if (wsetlocale_buf_size > 0) {
9193         Safefree(wsetlocale_buf);
9194         wsetlocale_buf_size = 0;
9195     }
9196
9197 #endif
9198
9199 }
9200
9201 /*
9202  * ex: set ts=8 sts=4 sw=4 et:
9203  */