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