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