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