3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
4 * 2002, 2003, 2005, 2006, 2007, 2008 by Larry Wall and others
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.
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!
20 * [p.238 of _The Lord of the Rings_, II/i: "Many Meetings"]
23 /* utility functions for handling locale-specific stuff like what
24 * character represents the decimal point.
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
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.
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.
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.
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.
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.
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.
80 * There are 3.5 major implementations here; which one chosen depends on what
81 * the platform has available, and Configuration options.
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).
88 * This implementation is composed of two layers:
89 * a) posix_setlocale() implements the libc setlocale(). In most cases,
90 * it is just an alias for the libc version. But Windows doesn't
91 * fully conform to the POSIX standard, and this is a layer on top of
92 * libc to bring it more into conformance. And in Configurations
93 * where perl is to ignore some locale categories that the libc
94 * setlocale() knows about, there is a layer to cope with that.
95 * b) stdized_setlocale() is a layer above a) that fixes some vagaries in
96 * the return value of the libc setlocale(). On most platforms this
97 * layer is empty; it requires perl to be Configured with a parameter
98 * indicating the platform's defect, in order to be activated. The
99 * current ones are listed at the definition of the macro.
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.
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.
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.
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
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.
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
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.
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
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).
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
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.
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
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.
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
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.
217 * There are also a few other macros herein that use this naming convention to
218 * describe their category parameter.
220 * Relevant Configure options
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.
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.
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.
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.
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.
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
264 * -Accflags=-DNO_LOCALE_CTYE
265 * -Accflags=-DNO_LOCALE_NUMERIC
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 XXX
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
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.
285 * -Accflags=USE_FAKE_LC_ALL_POSITIONAL_NOTATION
286 * This is used when developing Perl on a platform that uses
287 * 'name=value;' notation to represent LC_ALL when not all categories
288 * are the same. When so compiled, much of the code gets compiled
289 * and exercised that applies to platforms that instead use positional
290 * notation. This allows for finding many bugs in that portion of the
291 * implementation, without having to access such a platform.
293 * -Accflags=-DWIN32_USE_FAKE_OLD_MINGW_LOCALES
294 * This is used when developing Perl on a non-Windows platform to
295 * compile and exercise much of the locale-related code that instead
296 * applies to MingW platforms that don't use the more modern UCRT
297 * library. This allows for finding many bugs in that portion of the
298 * implementation, without having to access such a platform.
301 /* If the environment says to, we can output debugging information during
302 * initialization. This is done before option parsing, and before any thread
303 * creation, so can be a file-level static. (Must come before #including
307 /* Returns the Unix errno portion; ignoring any others. This is a macro here
308 * instead of putting it into perl.h, because unclear to khw what should be
310 #define GET_ERRNO saved_errno
313 static int debug_initialization = 0;
314 # define DEBUG_INITIALIZATION_set(v) (debug_initialization = v)
315 # define DEBUG_LOCALE_INITIALIZATION_ debug_initialization
317 # ifdef HAS_EXTENDED_OS_ERRNO
318 /* Output the non-zero errno and/or the non-zero extended errno */
319 # define DEBUG_ERRNO \
321 int extended = get_extended_os_errno(); \
322 const char * errno_string; \
323 if (GET_ERRNO == 0) { /* Skip output if both errno types are 0 */ \
324 if (LIKELY(extended == 0)) errno_string = ""; \
325 else errno_string = Perl_form(aTHX_ "; $^E=%d", extended); \
327 else if (LIKELY(extended == GET_ERRNO)) \
328 errno_string = Perl_form(aTHX_ "; $!=%d", GET_ERRNO); \
329 else errno_string = Perl_form(aTHX_ "; $!=%d, $^E=%d", \
330 GET_ERRNO, extended);
332 /* Output the errno, if non-zero */
333 # define DEBUG_ERRNO \
335 const char * errno_string = ""; \
336 if (GET_ERRNO != 0) { \
338 errno_string = Perl_form(aTHX_ "; $!=%d", GET_ERRNO); \
342 /* Automatically include the caller's file, and line number in debugging output;
343 * and the errno (and/or extended errno) if non-zero. On threaded perls add
345 # if defined(USE_ITHREADS) && ! defined(NO_LOCALE_THREADS)
346 # define DEBUG_PRE_STMTS \
348 PerlIO_printf(Perl_debug_log, "\n%s: %" LINE_Tf ": 0x%p%s: ", \
349 __FILE__, (line_t)__LINE__, aTHX_ \
352 # define DEBUG_PRE_STMTS \
354 PerlIO_printf(Perl_debug_log, "\n%s: %" LINE_Tf "%s: ", \
355 __FILE__, (line_t)__LINE__, \
358 # define DEBUG_POST_STMTS RESTORE_ERRNO;
360 # define debug_initialization 0
361 # define DEBUG_INITIALIZATION_set(v)
362 # define DEBUG_PRE_STMTS
363 # define DEBUG_POST_STMTS
367 #define PERL_IN_LOCALE_C
370 #ifdef WIN32_USE_FAKE_OLD_MINGW_LOCALES
372 /* Use -Accflags=-DWIN32_USE_FAKE_OLD_MINGW_LOCALES on a POSIX or *nix box
373 * to get a semblance of pretending the locale handling is that of a MingW
374 * that doesn't use UCRT (hence 'OLD' in the name). This exercizes code
375 * paths that are not compiled on non-Windows boxes, and allows for ASAN.
376 * This is thus a way to see if locale.c on Windows is likely going to
377 * compile, without having to use a real Win32 box. And running the test
378 * suite will verify to a large extent our logic and memory allocation
379 * handling for such boxes. And access to ASAN and PERL_MEMLOG Of course the underlying calls are to the POSIX
380 * libc, so any differences in implementation between those and the Windows
381 * versions will not be caught by this. */
384 # undef P_CS_PRECEDES
385 # undef CURRENCY_SYMBOL
387 # undef _configthreadlocale
388 # define _configthreadlocale(arg) NOOP
390 # define MultiByteToWideChar(cp, flags, byte_string, m1, wstring, req_size) \
391 (mbsrtowcs(wstring, &(byte_string), req_size, NULL) + 1)
392 # define WideCharToMultiByte(cp, flags, wstring, m1, byte_string, \
393 req_size, default_char, found_default_char) \
394 (wcsrtombs(byte_string, &(wstring), req_size, NULL) + 1)
398 static const wchar_t * wsetlocale_buf = NULL;
399 static Size_t wsetlocale_buf_size = 0;
400 static PerlInterpreter * wsetlocale_buf_aTHX = NULL;
404 S_wsetlocale(const int category, const wchar_t * wlocale)
406 /* Windows uses a setlocale that takes a wchar_t* locale. Other boxes
407 * don't have this, so this Windows replacement converts the wchar_t input
408 * to plain 'char*', calls plain setlocale(), and converts the result back
411 const char * byte_locale = NULL;
413 byte_locale = Win_wstring_to_byte_string(CP_UTF8, wlocale);
416 const char * byte_result = setlocale(category, byte_locale);
417 Safefree(byte_locale);
418 if (byte_result == NULL) {
422 const wchar_t * wresult = Win_byte_string_to_wstring(CP_UTF8, byte_result);
428 /* Emulate a global static memory return from wsetlocale(). This currently
429 * leaks at process end; would require changing LOCALE_TERM to fix that */
430 Size_t string_size = wcslen(wresult) + 1;
432 if (wsetlocale_buf_size == 0) {
433 Newx(wsetlocale_buf, string_size, wchar_t);
434 wsetlocale_buf_size = string_size;
439 wsetlocale_buf_aTHX = aTHX;
444 else if (string_size > wsetlocale_buf_size) {
445 Renew(wsetlocale_buf, string_size, wchar_t);
446 wsetlocale_buf_size = string_size;
449 Copy(wresult, wsetlocale_buf, string_size, wchar_t);
452 return wsetlocale_buf;
455 # define _wsetlocale(category, wlocale) S_wsetlocale(category, wlocale)
457 #endif /* WIN32_USE_FAKE_OLD_MINGW_LOCALES */
459 /* 'for' loop headers to hide the necessary casts */
460 #define for_all_individual_category_indexes(i) \
461 for (locale_category_index i = (locale_category_index) 0; \
463 i = (locale_category_index) ((int) i + 1))
465 #define for_all_but_0th_individual_category_indexes(i) \
466 for (locale_category_index i = (locale_category_index) 1; \
468 i = (locale_category_index) ((int) i + 1))
470 #define for_all_category_indexes(i) \
471 for (locale_category_index i = (locale_category_index) 0; \
472 i <= LC_ALL_INDEX_; \
473 i = (locale_category_index) ((int) i + 1))
476 # if defined(USE_FAKE_LC_ALL_POSITIONAL_NOTATION) && defined(LC_ALL)
478 /* This simulates an underlying positional notation for LC_ALL when compiled on
479 * a system that uses name=value notation. Use this to develop on Linux and
480 * make a quick check that things have some chance of working on a positional
481 * box. Enable by adding to the Congfigure parameters:
482 * -Accflags=USE_FAKE_LC_ALL_POSITIONAL_NOTATION
484 * NOTE it redefines setlocale() and usequerylocale()
488 S_positional_name_value_xlation(const char * locale, bool direction)
489 { /* direction == 1 is from name=value to positional
490 direction == 0 is from positional to name=value */
494 const char * individ_locales[LC_ALL_INDEX_] = { NULL };
496 /* This parses either notation */
497 switch (parse_LC_ALL_string(locale,
498 (const char **) &individ_locales,
499 no_override, /* Handled by other code */
500 false, /* Return only [0] if suffices */
501 false, /* Don't panic on error */
504 default: /* Some compilers don't realize that below is the complete
505 list of the available enum values */
512 SAVEFREEPV(individ_locales[0]);
513 return individ_locales[0];
516 calc_LC_ALL_format format = (direction)
517 ? EXTERNAL_FORMAT_FOR_SET
519 const char * retval = calculate_LC_ALL_string(individ_locales,
524 for_all_individual_category_indexes(i) {
525 Safefree(individ_locales[i]);
534 S_positional_setlocale(int cat, const char * locale)
536 if (cat != LC_ALL) return setlocale(cat, locale);
538 if (locale && strNE(locale, "")) {
539 locale = S_positional_name_value_xlation(locale, 0);
540 if (! locale) return NULL;
543 locale = setlocale(cat, locale);
544 if (locale == NULL) return NULL;
545 return S_positional_name_value_xlation(locale, 1);
549 # define setlocale(a,b) S_positional_setlocale(a,b)
550 # ifdef USE_POSIX_2008_LOCALE
553 S_positional_newlocale(int mask, const char * locale, locale_t base)
557 if (mask != LC_ALL_MASK) return newlocale(mask, locale, base);
559 if (strNE(locale, "")) locale = S_positional_name_value_xlation(locale, 0);
560 if (locale == NULL) return NULL;
561 return newlocale(LC_ALL_MASK, locale, base);
565 # define newlocale(a,b,c) S_positional_newlocale(a,b,c)
568 #endif /* End of fake positional notation */
579 /* The main errno that gets used is this one, on platforms that support it */
581 # define SET_EINVAL SETERRNO(EINVAL, LIB_INVARG)
586 /* If we have any of these library functions, we can reliably determine is a
587 * locale is a UTF-8 one or not. And if we aren't using locales at all, we act
588 * as if everything is the C locale, so the answer there is always "No, it
589 * isn't UTF-8"; this too is reliably accurate */
590 #if defined(HAS_SOME_LANGINFO) || defined(HAS_MBTOWC) \
591 || defined(HAS_MBRTOWC) || ! defined(USE_LOCALE)
592 # define HAS_RELIABLE_UTF8NESS_DETERMINATION
595 /* This is a starting guess as to when this is true. It definititely isn't
596 * true on *BSD where positional LC_ALL notation is used. Likely this will end
597 * up being defined in hints files. */
598 #ifdef PERL_LC_ALL_USES_NAME_VALUE_PAIRS
599 # define NEWLOCALE_HANDLES_DISPARATE_LC_ALL
602 /* But regardless, we have to look at individual categories if some are
604 #ifdef HAS_IGNORED_LOCALE_CATEGORIES_
605 # undef NEWLOCALE_HANDLES_DISPARATE_LC_ALL
609 /* Not all categories need be set to the same locale. This macro determines if
610 * 'name' which represents LC_ALL is uniform or disparate. There are two
611 * situations: 1) the platform uses unordered name=value pairs; 2) the platform
612 * uses ordered positional values, with a separator string between them */
613 # ifdef PERL_LC_ALL_SEPARATOR /* positional */
614 # define is_disparate_LC_ALL(name) cBOOL(instr(name, PERL_LC_ALL_SEPARATOR))
615 # else /* name=value */
617 /* In the, hopefully never occurring, event that the platform doesn't use
618 * either mechanism for disparate LC_ALL's, assume the name=value pairs
619 * form, rather than taking the extreme step of refusing to compile. Many
620 * programs won't have disparate locales, so will generally work */
621 # define PERL_LC_ALL_SEPARATOR ";"
622 # define is_disparate_LC_ALL(name) cBOOL( strchr(name, ';') \
623 && strchr(name, '='))
626 /* It is possible to compile perl to always keep any individual category in the
627 * C locale. This would be done where the implementation on a platform is
628 * flawed or incomplete. At the time of this writing, for example, OpenBSD has
629 * not implemented LC_COLLATE beyond the C locale. The 'category_available[]'
630 * table is a bool that says whether a category is changeable, or must be kept
631 * in C. This macro substitutes C for the locale appropriately, expanding to
632 * nothing on the more typical case where all possible categories present on
633 * the platform are handled. */
634 # ifdef HAS_IGNORED_LOCALE_CATEGORIES_
635 # define need_to_override_category(i) (! category_available[i])
636 # define override_ignored_category(i, new_locale) \
637 ((need_to_override_category(i)) ? "C" : (new_locale))
639 # define need_to_override_category(i) 0
640 # define override_ignored_category(i, new_locale) (new_locale)
643 PERL_STATIC_INLINE const char *
644 S_mortalized_pv_copy(pTHX_ const char * const pv)
646 PERL_ARGS_ASSERT_MORTALIZED_PV_COPY;
648 /* Copies the input pv, and arranges for it to be freed at an unspecified
655 const char * copy = savepv(pv);
662 /* Default values come from the C locale */
663 #define C_codeset "ANSI_X3.4-1968" /* Only in some Configurations, and usually
664 a single instance, so is a #define */
665 static const char C_decimal_point[] = ".";
667 #if (defined(USE_LOCALE_NUMERIC) && ! defined(TS_W32_BROKEN_LOCALECONV)) \
668 || ! ( defined(USE_LOCALE_NUMERIC) \
669 && (defined(HAS_SOME_LANGINFO) || defined(HAS_LOCALECONV)))
670 static const char C_thousands_sep[] = "";
673 /* Is the C string input 'name' "C" or "POSIX"? If so, and 'name' is the
674 * return of setlocale(), then this is extremely likely to be the C or POSIX
675 * locale. However, the output of setlocale() is documented to be opaque, but
676 * the odds are extremely small that it would return these two strings for some
677 * other locale. Note that VMS includes many non-ASCII characters in these two
678 * locales as controls and punctuation (below are hex bytes):
680 * punct: A1-A3 A5 A7-AB B0-B3 B5-B7 B9-BD BF-CF D1-DD DF-EF F1-FD
681 * Oddly, none there are listed as alphas, though some represent alphabetics
682 * http://www.nntp.perl.org/group/perl.perl5.porters/2013/02/msg198753.html */
683 #define isNAME_C_OR_POSIX(name) \
685 && (( *(name) == 'C' && (*(name + 1)) == '\0') \
686 || strEQ((name), "POSIX")))
688 #if defined(HAS_NL_LANGINFO_L) || defined(HAS_NL_LANGINFO)
689 # define HAS_SOME_LANGINFO
692 #define my_langinfo_c(item, category, locale, retbufp, retbuf_sizep, utf8ness) \
693 my_langinfo_i(item, category##_INDEX_, locale, retbufp, \
694 retbuf_sizep, utf8ness)
697 # define setlocale_debug_string_i(index, locale, result) \
698 my_setlocale_debug_string_i(index, locale, result, __LINE__)
699 # define setlocale_debug_string_c(category, locale, result) \
700 setlocale_debug_string_i(category##_INDEX_, locale, result)
701 # define setlocale_debug_string_r(category, locale, result) \
702 setlocale_debug_string_i(get_category_index(category), \
706 # define toggle_locale_i(index, locale) \
707 S_toggle_locale_i(aTHX_ index, locale, __LINE__)
708 # define toggle_locale_c(cat, locale) toggle_locale_i(cat##_INDEX_, locale)
709 # define restore_toggled_locale_i(index, locale) \
710 S_restore_toggled_locale_i(aTHX_ index, locale, __LINE__)
711 # define restore_toggled_locale_c(cat, locale) \
712 restore_toggled_locale_i(cat##_INDEX_, locale)
714 /* On systems without LC_ALL, pretending it exists anyway simplifies things.
715 * Choose a value for it that is very unlikely to clash with any actual
717 # define FAKE_LC_ALL PERL_INT_MIN
719 /* Below are parallel arrays for locale information indexed by our mapping of
720 * category numbers into small non-negative indexes. locale_table.h contains
721 * an entry like this for each individual category used on this system:
722 * PERL_LOCALE_TABLE_ENTRY(CTYPE, S_new_ctype)
724 * Each array redefines PERL_LOCALE_TABLE_ENTRY to generate the information
725 * needed for that array, and #includes locale_table.h to get the valid
728 * An entry for the conglomerate category LC_ALL is added here, immediately
729 * following the individual categories. (The treatment for it varies, so can't
730 * be in locale_table.h.)
732 * Following this, each array ends with an entry for illegal categories. All
733 * category numbers unknown to perl get mapped to this entry. This is likely
734 * to be a parameter error from the calling program; but it could be that this
735 * platform has a category we don't know about, in which case it needs to be
736 * added, using the paradigm of one of the existing categories. */
738 /* The first array is the locale categories perl uses on this system, used to
739 * map our index back to the system's category number. */
740 STATIC const int categories[] = {
742 # undef PERL_LOCALE_TABLE_ENTRY
743 # define PERL_LOCALE_TABLE_ENTRY(name, call_back) LC_ ## name,
744 # include "locale_table.h"
752 (FAKE_LC_ALL + 1) /* Entry for unknown category; this number is unlikely
753 to clash with a real category */
756 # define GET_NAME_AS_STRING(token) # token
757 # define GET_LC_NAME_AS_STRING(token) GET_NAME_AS_STRING(LC_ ## token)
759 /* The second array is the category names. */
760 STATIC const char * const category_names[] = {
762 # undef PERL_LOCALE_TABLE_ENTRY
763 # define PERL_LOCALE_TABLE_ENTRY(name, call_back) GET_LC_NAME_AS_STRING(name),
764 # include "locale_table.h"
767 # define LC_ALL_STRING "LC_ALL"
769 # define LC_ALL_STRING "If you see this, it is a bug in perl;" \
770 " please report it via perlbug"
775 # define LC_UNKNOWN_STRING "Locale category unknown to Perl; if you see" \
776 " this, it is a bug in perl; please report it" \
781 STATIC const Size_t category_name_lengths[] = {
783 # undef PERL_LOCALE_TABLE_ENTRY
784 # define PERL_LOCALE_TABLE_ENTRY(name, call_back) \
785 STRLENs(GET_LC_NAME_AS_STRING(name)),
786 # include "locale_table.h"
788 STRLENs(LC_ALL_STRING),
789 STRLENs(LC_UNKNOWN_STRING)
792 /* Each entry includes space for the '=' and ';' */
793 # undef PERL_LOCALE_TABLE_ENTRY
794 # define PERL_LOCALE_TABLE_ENTRY(name, call_back) \
795 + STRLENs(GET_LC_NAME_AS_STRING(name)) + 2
797 STATIC const Size_t lc_all_boiler_plate_length = 1 /* space for trailing NUL */
798 # include "locale_table.h"
801 /* A few categories require additional setup when they are changed. This table
802 * points to the functions that do that setup */
803 STATIC void (*update_functions[]) (pTHX_ const char *, bool force) = {
805 # undef PERL_LOCALE_TABLE_ENTRY
806 # define PERL_LOCALE_TABLE_ENTRY(name, call_back) call_back,
807 # include "locale_table.h"
810 NULL, /* No update for unknown category */
813 # if defined(HAS_IGNORED_LOCALE_CATEGORIES_)
815 /* Indicates if each category on this platform is available to use not in
817 STATIC const bool category_available[] = {
819 # undef PERL_LOCALE_TABLE_ENTRY
820 # define PERL_LOCALE_TABLE_ENTRY(name, call_back) LC_ ## name ## _AVAIL_,
821 # include "locale_table.h"
829 false /* LC_UNKNOWN_AVAIL_ */
833 # if defined(USE_POSIX_2008_LOCALE)
835 STATIC const int category_masks[] = {
837 # undef PERL_LOCALE_TABLE_ENTRY
838 # define PERL_LOCALE_TABLE_ENTRY(name, call_back) LC_ ## name ## _MASK,
839 # include "locale_table.h"
841 LC_ALL_MASK, /* Will rightly refuse to compile unless this is defined */
842 0 /* Empty mask for unknown category */
846 # if ! defined(PERL_LC_ALL_USES_NAME_VALUE_PAIRS)
848 /* On platforms that use positional notation for expressing LC_ALL, this maps
849 * the position of each category to our corresponding internal index for it.
850 * This is initialized at run time if needed. LC_ALL_INDEX_ is not legal for
851 * an individual locale, hence marks the elements here as not actually
855 map_LC_ALL_position_to_index[LC_ALL_INDEX_] = { LC_ALL_INDEX_ };
859 #if defined(USE_LOCALE) || defined(DEBUGGING)
862 S_get_displayable_string(pTHX_
863 const char * const s,
864 const char * const e,
867 PERL_ARGS_ASSERT_GET_DISPLAYABLE_STRING;
874 bool prev_was_printable = TRUE;
875 bool first_time = TRUE;
878 /* Worst case scenario: All are non-printable so have a blank between each.
879 * If UTF-8, all are the largest possible code point; otherwise all are a
880 * single byte. '(2 + 1)' is from each byte takes 2 characters to
881 * display, and a blank (or NUL for the final one) after it */
882 const Size_t size = (e - s) * (2 + 1) * ((is_utf8) ? UVSIZE : 1);
883 Newxz(ret, size, char);
888 ? utf8_to_uvchr_buf((U8 *) t, e, NULL)
891 if (! prev_was_printable) {
892 my_strlcat(ret, " ", size);
895 /* Escape these to avoid any ambiguity */
896 if (cp == ' ' || cp == '\\') {
897 my_strlcat(ret, "\\", size);
899 my_strlcat(ret, Perl_form(aTHX_ "%c", (U8) cp), size);
900 prev_was_printable = TRUE;
904 my_strlcat(ret, " ", size);
906 my_strlcat(ret, Perl_form(aTHX_ "%02" UVXf, cp), size);
907 prev_was_printable = FALSE;
909 t += (is_utf8) ? UTF8SKIP(t) : 1;
919 # define get_category_index(cat) get_category_index_helper(cat, NULL, __LINE__)
921 STATIC locale_category_index
922 S_get_category_index_helper(pTHX_ const int category, bool * succeeded,
923 const line_t caller_line)
925 PERL_ARGS_ASSERT_GET_CATEGORY_INDEX_HELPER;
927 /* Given a category, return the equivalent internal index we generally use
928 * instead, warn or panic if not found. */
930 locale_category_index i;
932 # undef PERL_LOCALE_TABLE_ENTRY
933 # define PERL_LOCALE_TABLE_ENTRY(name, call_back) \
934 case LC_ ## name: i = LC_ ## name ## _INDEX_; break;
938 # include "locale_table.h"
940 case LC_ALL: i = LC_ALL_INDEX_; break;
943 default: goto unknown_locale;
946 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
947 "index of category %d (%s) is %d;"
948 " called from %" LINE_Tf "\n",
949 category, category_names[i], i, caller_line));
961 return LC_ALL_INDEX_; /* Arbitrary */
964 locale_panic_via_(Perl_form(aTHX_ "Unknown locale category %d", category),
965 __FILE__, caller_line);
966 NOT_REACHED; /* NOTREACHED */
969 #endif /* ifdef USE_LOCALE */
972 Perl_force_locale_unlock(pTHX)
974 /* Remove any locale mutex, in preperation for an inglorious termination,
975 * typically a panic */
977 #if defined(USE_LOCALE_THREADS)
979 /* If recursively locked, clear all at once */
980 if (PL_locale_mutex_depth > 1) {
981 PL_locale_mutex_depth = 1;
984 if (PL_locale_mutex_depth > 0) {
992 #ifdef USE_POSIX_2008_LOCALE
995 S_use_curlocale_scratch(pTHX)
997 /* This function is used to hide from the caller the case where the current
998 * locale_t object in POSIX 2008 is the global one, which is illegal in
999 * many of the P2008 API calls. This checks for that and, if necessary
1000 * creates a proper P2008 object. Any prior object is deleted, as is any
1001 * remaining object during global destruction. */
1003 locale_t cur = uselocale((locale_t) 0);
1005 if (cur != LC_GLOBAL_LOCALE) {
1009 if (PL_scratch_locale_obj) {
1010 freelocale(PL_scratch_locale_obj);
1013 PL_scratch_locale_obj = duplocale(LC_GLOBAL_LOCALE);
1014 return PL_scratch_locale_obj;
1020 Perl_locale_panic(const char * msg,
1021 const line_t immediate_caller_line,
1022 const char * const higher_caller_file,
1023 const line_t higher_caller_line)
1025 PERL_ARGS_ASSERT_LOCALE_PANIC;
1029 force_locale_unlock();
1031 #ifdef USE_C_BACKTRACE
1032 dump_c_backtrace(Perl_debug_log, 20, 1);
1035 const char * called_by = "";
1036 if ( strNE(__FILE__, higher_caller_file)
1037 || immediate_caller_line != higher_caller_line)
1039 called_by = Perl_form(aTHX_ "\nCalled by %s: %" LINE_Tf "\n",
1040 higher_caller_file, higher_caller_line);
1045 const char * errno_text;
1047 #ifdef HAS_EXTENDED_OS_ERRNO
1049 const int extended_errnum = get_extended_os_errno();
1050 if (errno != extended_errnum) {
1051 errno_text = Perl_form(aTHX_ "; errno=%d, $^E=%d",
1052 errno, extended_errnum);
1059 errno_text = Perl_form(aTHX_ "; errno=%d", errno);
1062 /* diag_listed_as: panic: %s */
1063 Perl_croak(aTHX_ "%s: %" LINE_Tf ": panic: %s%s%s\n",
1064 __FILE__, immediate_caller_line,
1065 msg, errno_text, called_by);
1068 /* Macros to report and croak on an unexpected failure to set the locale. The
1069 * via version has more stack trace information */
1070 #define setlocale_failure_panic_i(i, cur, fail, line, higher_line) \
1071 setlocale_failure_panic_via_i(i, cur, fail, __LINE__, line, \
1072 __FILE__, higher_line)
1074 #define setlocale_failure_panic_c(cat, cur, fail, line, higher_line) \
1075 setlocale_failure_panic_i(cat##_INDEX_, cur, fail, line, higher_line)
1077 #if defined(LC_ALL) && defined(USE_LOCALE)
1079 /* Expands to the code to
1080 * result = savepvn(s, len)
1081 * if the category whose internal index is 'i' doesn't need to be kept in the C
1082 * locale on this system, or if 'action is 'no_override'. Otherwise it expands
1084 * result = savepv("C")
1085 * unless 'action' isn't 'check_that_overridden', in which case if the string
1086 * 's' isn't already "C" it panics */
1087 # ifndef HAS_IGNORED_LOCALE_CATEGORIES_
1088 # define OVERRIDE_AND_SAVEPV(s, len, result, i, action) \
1089 result = savepvn(s, len)
1091 # define OVERRIDE_AND_SAVEPV(s, len, result, i, action) \
1093 if (LIKELY( ! need_to_override_category(i) \
1094 || action == no_override)) { \
1095 result = savepvn(s, len); \
1098 const char * temp = savepvn(s, len); \
1099 result = savepv(override_ignored_category(i, temp)); \
1100 if (action == check_that_overridden && strNE(result, temp)) { \
1101 locale_panic_(Perl_form(aTHX_ \
1102 "%s expected to be '%s', instead is '%s'", \
1103 category_names[i], result, temp)); \
1110 STATIC parse_LC_ALL_string_return
1111 S_parse_LC_ALL_string(pTHX_ const char * string,
1112 const char ** output,
1113 const parse_LC_ALL_STRING_action override,
1114 bool always_use_full_array,
1115 const bool panic_on_error,
1116 const line_t caller_line)
1118 /* This function parses the value of the input 'string' which is expected
1119 * to be the representation of an LC_ALL locale, and splits the result into
1120 * the values for the individual component categories, returning those in
1121 * the 'output' array. Each array value will be a savepv() copy that is
1122 * the responsibility of the caller to make sure gets freed
1124 * The locale for each category is independent of the other categories.
1125 * Often, they are all the same, but certainly not always. Perl, in fact,
1126 * usually keeps LC_NUMERIC in the C locale, regardless of the underlying
1127 * locale. LC_ALL has to be able to represent the case of when not all
1128 * categories have the same locale. Platforms have differing ways of
1129 * representing this. Internally, this file uses the 'name=value;'
1130 * representation found on some platforms, so this function always looks
1131 * for and parses that. Other platforms use a positional notation. On
1132 * those platforms, this function also parses that form. It examines the
1133 * input to see which form is being parsed.
1135 * Often, all categories will have the same locale. This is special cased
1136 * if 'always_use_full_array' is false on input:
1137 * 1) If the input 'string' is a single value, this function doesn't
1138 * store anything into 'output', and returns 'no_array'
1139 * 2) Some platforms will return multiple occurrences of the same
1140 * value rather than coalescing them down to a single one. HP-UX
1141 * is such a one. This function will do that collapsing for you,
1142 * returning 'only_element_0' and saving the single value in
1143 * output[0], which the caller will need to arrange to be freed.
1144 * The rest of output[] is undefined, and does not need to be
1147 * Otherwise, the input 'string' may not be valid. This function looks
1148 * mainly for syntactic errors, and if found, returns 'invalid'. 'output'
1149 * will not be filled in in that case, but the input state of it isn't
1150 * necessarily preserved. Turning on -DL debugging will give details as to
1151 * the error. If 'panic_on_error' is 'true', the function panics instead
1152 * of returning on error, with a message giving the details.
1154 * Otherwise, output[] will be filled with the individual locale names for
1155 * all categories on the system, 'full_array' will be returned, and the
1156 * caller needs to arrange for each to be freed. This means that either at
1157 * least one category differed from the others, or 'always_use_full_array' was
1160 * perl may be configured to ignore changes to a category's locale to
1161 * non-C. The parameter 'override' tells this function what to do when
1162 * encountering such an illegal combination:
1164 * no_override indicates to take no special action
1165 * override_if_ignored, indicates to return 'C' instead of what the
1166 * input string actually says.
1167 * check_that_overridden indicates to panic if the string says the
1168 * category is not 'C'. This is used when
1169 * non-C is very unexpected behavior.
1172 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
1173 "Entering parse_LC_ALL_string; called from %" \
1174 LINE_Tf "\nnew='%s'\n", caller_line, string));
1176 # ifdef PERL_LC_ALL_USES_NAME_VALUE_PAIRS
1178 const char separator[] = ";";
1179 const Size_t separator_len = 1;
1180 const bool single_component = (strchr(string, ';') == NULL);
1184 /* It's possible (but quite unlikely) that the separator string is an '='
1185 * or a ';'. Requiring both to be present for using the 'name=value;' form
1186 * properly handles those possibilities */
1187 const bool name_value = strchr(string, '=') && strchr(string, ';');
1188 const char * separator;
1189 Size_t separator_len;
1190 bool single_component;
1194 single_component = false; /* Since has both [;=], must be multi */
1197 separator = PERL_LC_ALL_SEPARATOR;
1198 separator_len = STRLENs(PERL_LC_ALL_SEPARATOR);
1199 single_component = instr(string, separator) == NULL;
1202 Size_t component_number = 0; /* Position in the parsing loop below */
1205 # ifndef HAS_IGNORED_LOCALE_CATEGORIES_
1206 PERL_UNUSED_ARG(override);
1209 /* Any ignored categories are to be set to "C", so if this single-component
1210 * LC_ALL isn't to C, it has both "C" and non-C, so isn't really a single
1211 * component. All the non-ignored categories are set to the input
1212 * component, but the ignored ones are overridden to be C.
1214 * This incidentally handles the case where the string is "". The return
1215 * will be C for each ignored category and "" for the others. Then the
1216 * caller can individually set each category, and get the right answer. */
1217 if (single_component && ! isNAME_C_OR_POSIX(string)) {
1218 for_all_individual_category_indexes(i) {
1219 OVERRIDE_AND_SAVEPV(string, strlen(string), output[i], i, override);
1227 if (single_component) {
1228 if (! always_use_full_array) {
1232 for_all_individual_category_indexes(i) {
1233 output[i] = savepv(string);
1239 /* Here the input is multiple components. Parse through them. (It is
1240 * possible that these components are all the same, so we check, and if so,
1241 * return just the 0th component (unless 'always_use_full_array' is true)
1243 * This enum notes the possible errors findable in parsing */
1248 contains_LC_ALL_element
1251 /* Keep track of the categories we have encountered so far */
1252 bool seen[LC_ALL_INDEX_] = { false };
1254 Size_t index; /* Our internal index for the current category */
1255 const char * s = string;
1256 const char * e = s + strlen(string);
1257 const char * category_end = NULL;
1258 const char * saved_first = NULL;
1260 /* Parse the input locale string */
1263 /* 'separator' has been set up to delimit the components */
1264 const char * next_sep = instr(s, separator);
1265 if (! next_sep) { /* At the end of the input */
1269 # ifndef PERL_LC_ALL_USES_NAME_VALUE_PAIRS
1272 /* Get the index of the category in this position */
1273 index = map_LC_ALL_position_to_index[component_number++];
1279 { /* Get the category part when each component is the
1280 * 'category=locale' form */
1282 category_end = strchr(s, '=');
1284 /* The '=' terminates the category name. If no '=', is improper
1286 if (! category_end) {
1291 /* Find our internal index of the category name; uses a linear
1292 * search. (XXX This could be avoided by various means, but the
1293 * maximum likely search is 6 items, and khw doesn't think the
1294 * added complexity would save very much at all.) */
1295 const unsigned int name_len = (unsigned int) (category_end - s);
1296 for (index = 0; index < C_ARRAY_LENGTH(category_names); index++) {
1297 if ( name_len == category_name_lengths[index]
1298 && memEQ(s, category_names[index], name_len))
1300 goto found_category;
1304 /* Here, the category is not in our list. */
1305 error = unknown_category;
1308 found_category: /* The system knows about this category. */
1310 if (index == LC_ALL_INDEX_) {
1311 error = contains_LC_ALL_element;
1315 /* The locale name starts just beyond the '=' */
1316 s = category_end + 1;
1318 /* Linux (and maybe others) doesn't treat a duplicate category in
1319 * the string as an error. Instead it uses the final occurrence as
1320 * the intended value. So if this is a duplicate, free the former
1321 * value before setting the new one */
1323 Safefree(output[index]);
1330 /* Here, 'index' contains our internal index number for the current
1331 * category, and 's' points to the beginning of the locale name for
1333 OVERRIDE_AND_SAVEPV(s, next_sep - s, output[index], index, override);
1335 if (! always_use_full_array) {
1336 if (! saved_first) {
1337 saved_first = output[index];
1340 if (strNE(saved_first, output[index])) {
1341 always_use_full_array = true;
1346 /* Next time start from the new position */
1347 s = next_sep + separator_len;
1350 /* Finished looping through all the categories
1352 * Check if the input was incomplete. */
1354 # ifndef PERL_LC_ALL_USES_NAME_VALUE_PAIRS
1356 if (! name_value) { /* Positional notation */
1357 if (component_number != LC_ALL_INDEX_) {
1366 { /* Here is the name=value notation */
1367 for_all_individual_category_indexes(i) {
1375 /* In the loop above, we changed 'always_use_full_array' to true iff not all
1376 * categories have the same locale. Hence, if it is still 'false', all of
1377 * them are the same. */
1378 if (always_use_full_array) {
1382 /* Free the dangling ones */
1383 for_all_but_0th_individual_category_indexes(i) {
1384 Safefree(output[i]);
1388 return only_element_0;
1392 /* Don't leave memory dangling that we allocated before the failure */
1393 for_all_individual_category_indexes(i) {
1395 Safefree(output[i]);
1401 const char * display_start = s;
1402 const char * display_end = e;
1406 msg = "doesn't list every locale category";
1407 display_start = string;
1410 msg = "needs an '=' to split name=value";
1412 case unknown_category:
1413 msg = "is an unknown category";
1414 display_end = (category_end && category_end > display_start)
1418 case contains_LC_ALL_element:
1419 msg = "has LC_ALL, which is illegal here";
1423 msg = Perl_form(aTHX_ "'%.*s' %s\n",
1424 (int) (display_end - display_start),
1425 display_start, msg);
1427 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s", msg));
1429 if (panic_on_error) {
1430 locale_panic_via_(msg, __FILE__, caller_line);
1436 # undef OVERRIDE_AND_SAVEPV
1439 /*==========================================================================
1440 * Here starts the code that gives a uniform interface to its callers, hiding
1441 * the differences between platforms.
1443 * base_posix_setlocale_() presents a consistent POSIX-compliant interface to
1444 * setlocale(). Windows requres a customized base-level setlocale(). This
1445 * layer should only be used by the next level up: the plain posix_setlocale
1446 * layer. Any necessary mutex locking needs to be done at a higher level. The
1447 * return may be overwritten by the next call to this function */
1449 # define base_posix_setlocale_(cat, locale) win32_setlocale(cat, locale)
1451 # define base_posix_setlocale_(cat, locale) \
1452 ((const char *) setlocale(cat, locale))
1455 /*==========================================================================
1456 * Here is the main posix layer. It is the same as the base one unless the
1457 * system is lacking LC_ALL, or there are categories that we ignore, but that
1458 * the system libc knows about */
1460 #if ! defined(USE_LOCALE) \
1461 || (defined(LC_ALL) && ! defined(HAS_IGNORED_LOCALE_CATEGORIES_))
1462 # define posix_setlocale(cat, locale) base_posix_setlocale_(cat, locale)
1464 # define posix_setlocale(cat, locale) \
1465 S_posix_setlocale_with_complications(aTHX_ cat, locale, __LINE__)
1468 S_posix_setlocale_with_complications(pTHX_ const int cat,
1469 const char * new_locale,
1470 const line_t caller_line)
1472 /* This implements the posix layer above the base posix layer.
1473 * It is needed to reconcile our internal records that reflect only a
1474 * proper subset of the categories known by the system. */
1476 /* Querying the current locale returns the real value */
1477 if (new_locale == NULL) {
1478 new_locale = base_posix_setlocale_(cat, NULL);
1483 const char * locale_on_entry = NULL;
1485 /* If setting from the environment, actually do the set to get the system's
1486 * idea of what that means; we may have to override later. */
1487 if (strEQ(new_locale, "")) {
1488 locale_on_entry = base_posix_setlocale_(cat, NULL);
1489 assert(locale_on_entry);
1490 new_locale = base_posix_setlocale_(cat, "");
1499 const char * new_locales[LC_ALL_INDEX_] = { NULL };
1501 if (cat == LC_ALL) {
1502 switch (parse_LC_ALL_string(new_locale,
1503 (const char **) &new_locales,
1504 override_if_ignored, /* Override any
1507 false, /* Return only [0] if suffices */
1508 false, /* Don't panic on error */
1518 case only_element_0:
1519 new_locale = new_locales[0];
1520 SAVEFREEPV(new_locale);
1525 /* Turn the array into a string that the libc setlocale() should
1526 * understand. (Another option would be to loop, setting the
1527 * individual locales, and then return base(cat, NULL) */
1528 new_locale = calculate_LC_ALL_string(new_locales,
1529 EXTERNAL_FORMAT_FOR_SET,
1533 for_all_individual_category_indexes(i) {
1534 Safefree(new_locales[i]);
1537 /* And call the libc setlocale. We could avoid this call if
1538 * locale_on_entry is set and eq the new_locale. But that would be
1539 * only for the relatively rare case of the desired locale being
1540 * "", and the time spent in doing the string compare might be more
1541 * than that of just setting it unconditionally */
1542 new_locale = base_posix_setlocale_(cat, new_locale);
1553 /* Here, 'new_locale' is a single value, not an aggregation. Just set it.
1556 base_posix_setlocale_(cat,
1557 override_ignored_category(
1558 get_category_index(cat), new_locale));
1567 /* 'locale_on_entry' being set indicates there has likely been a change in
1568 * locale which needs to be restored */
1569 if (locale_on_entry) {
1570 if (! base_posix_setlocale_(cat, locale_on_entry)) {
1571 setlocale_failure_panic_i(get_category_index(cat),
1572 NULL, locale_on_entry,
1573 __LINE__, caller_line);
1583 /* End of posix layer
1584 *==========================================================================
1586 * The next layer up is to catch vagaries and bugs in the libc setlocale return
1587 * value. The return is not guaranteed to be stable.
1589 * Any necessary mutex locking needs to be done at a higher level.
1591 * On most platforms this layer is empty, expanding to just the layer
1592 * below. To enable it, call Configure with either or both:
1593 * -Accflags=-DHAS_LF_IN_SETLOCALE_RETURN
1594 * to indicate that extraneous \n characters can be returned
1596 * -Accflags=-DHAS_BROKEN_SETLOCALE_QUERY_LC_ALL
1597 * to indicate that setlocale(LC_ALL, NULL) cannot be relied
1601 #define STDIZED_SETLOCALE_LOCK POSIX_SETLOCALE_LOCK
1602 #define STDIZED_SETLOCALE_UNLOCK POSIX_SETLOCALE_UNLOCK
1603 #if ! defined(USE_LOCALE) \
1604 || ! ( defined(HAS_LF_IN_SETLOCALE_RETURN) \
1605 || defined(HAS_BROKEN_SETLOCALE_QUERY_LC_ALL))
1606 # define stdized_setlocale(cat, locale) posix_setlocale(cat, locale)
1607 # define stdize_locale(cat, locale) (locale)
1609 # define stdized_setlocale(cat, locale) \
1610 S_stdize_locale(aTHX_ cat, posix_setlocale(cat, locale), __LINE__)
1613 S_stdize_locale(pTHX_ const int category,
1614 const char *input_locale,
1615 const line_t caller_line)
1617 /* The return value of setlocale() is opaque, but is required to be usable
1618 * as input to a future setlocale() to create the same state.
1619 * Unfortunately not all systems are compliant. This function brings those
1620 * outliers into conformance. It is based on what problems have arisen in
1623 * This has similar constraints as the posix layer. You need to lock
1624 * around it until its return is safely copied or no longer needed. (The
1625 * return may point to a global static buffer or may be mortalized.)
1627 * The current things this corrects are:
1628 * 1) A new-line. This function chops any \n characters
1629 * 2) A broken 'setlocale(LC_ALL, foo)' This constructs a proper returned
1630 * string from the constituent categories
1632 * If no changes were made, the input is returned as-is */
1634 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
1635 "Entering stdize_locale(%d, '%s');"
1636 " called from %" LINE_Tf "\n",
1637 category, input_locale, caller_line));
1639 if (input_locale == NULL) {
1644 char * retval = (char *) input_locale;
1646 # if defined(LC_ALL) && defined(HAS_BROKEN_SETLOCALE_QUERY_LC_ALL)
1648 /* If setlocale(LC_ALL, NULL) is broken, compute what the system
1649 * actually thinks it should be from its individual components */
1650 if (category == LC_ALL) {
1651 retval = (char *) calculate_LC_ALL_string(
1652 NULL, /* query each individ locale */
1653 EXTERNAL_FORMAT_FOR_SET,
1659 # ifdef HAS_NL_IN_SETLOCALE_RETURN
1661 char * first_bad = NULL;
1665 PERL_UNUSED_ARG(category);
1666 PERL_UNUSED_ARG(caller_line);
1668 # define INPUT_LOCALE retval
1669 # define MARK_CHANGED
1672 char * individ_locales[LC_ALL_INDEX_] = { NULL };
1673 bool made_changes = false;
1675 if (category != LC_ALL) {
1676 individ_locales[0] = retval;
1681 /* And parse the locale string, splitting into its individual
1683 switch (parse_LC_ALL_string(retval,
1684 (const char **) &individ_locales,
1685 check_that_overridden, /* ignored
1689 false, /* Return only [0] if suffices */
1690 false, /* Don't panic on error */
1697 case full_array: /* Loop below through all the component categories.
1699 upper = LC_ALL_INDEX_ - 1;
1703 /* All categories here are set to the same locale, and the parse
1704 * didn't fill in any of 'individ_locales'. Set the 0th element to
1706 individ_locales[0] = retval;
1709 case only_element_0: /* Element 0 is the only element we need to look
1716 for (unsigned int i = 0; i <= upper; i++)
1718 # define INPUT_LOCALE individ_locales[i]
1719 # define MARK_CHANGED made_changes = true;
1720 # endif /* Has LC_ALL */
1723 first_bad = (char *) strchr(INPUT_LOCALE, '\n');
1725 /* Most likely, there isn't a problem with the input */
1726 if (UNLIKELY(first_bad)) {
1728 /* This element will need to be adjusted. Create a modifiable
1731 retval = savepv(INPUT_LOCALE);
1734 /* Translate the found position into terms of the copy */
1735 first_bad = retval + (first_bad - INPUT_LOCALE);
1737 /* Get rid of the \n and what follows. (Originally, only a
1738 * trailing \n was stripped. Unsure what to do if not trailing) */
1739 *((char *) first_bad) = '\0';
1740 } /* End of needs adjusting */
1741 } /* End of looking for problems */
1745 /* If we had multiple elements, extra work is required */
1748 /* If no changes were made to the input, 'retval' already contains it
1752 /* But if did make changes, need to calculate the new value */
1753 retval = (char *) calculate_LC_ALL_string(
1754 (const char **) &individ_locales,
1755 EXTERNAL_FORMAT_FOR_SET,
1760 /* And free the no-longer needed memory */
1761 for (unsigned int i = 0; i <= upper; i++) {
1762 Safefree(individ_locales[i]);
1767 # undef INPUT_LOCALE
1768 # undef MARK_CHANGED
1769 # endif /* HAS_NL_IN_SETLOCALE_RETURN */
1771 return (const char *) retval;
1774 #endif /* USE_LOCALE */
1776 /* End of stdize_locale layer
1778 * ==========================================================================
1780 * The next many lines form several implementations of a layer above the
1781 * close-to-the-metal 'posix' and 'stdized' macros. They are used to present a
1782 * uniform API to the rest of the code in this file in spite of the disparate
1783 * underlying implementations. Which implementation gets compiled depends on
1784 * the platform capabilities (and some user choice) as determined by Configure.
1786 * As more fully described in the introductory comments in this file, the
1787 * API of each implementation consists of three sets of macros. Each set has
1788 * three variants with suffixes '_c', '_r', and '_i'. In the list below '_X'
1789 * is to be replaced by any of these suffixes.
1791 * 1) bool_setlocale_X attempts to set the given category's locale to the
1792 * given value, returning if it worked or not.
1793 * 2) void_setlocale_X is like the corresponding bool_setlocale, but used when
1794 * success is the only sane outcome, so failure causes it
1796 * 3) querylocale_X to see what the given category's locale is
1798 * 4) setlocale_i() is defined only in those implementations where the bool
1799 * and query forms are essentially the same, and can be
1800 * combined to save CPU time.
1802 * Each implementation below is separated by ==== lines, and includes bool,
1803 * void, and query macros. The query macros are first, followed by any
1804 * functions needed to implement them. Then come the bool, again followed by
1805 * any implementing functions Then are the void macros; next is setlocale_i if
1806 * present on this implementation. Finally are any helper functions. The sets
1807 * in each implementation are separated by ---- lines.
1809 * The returned strings from all the querylocale...() forms in all
1810 * implementations are thread-safe, and the caller should not free them,
1811 * but each may be a mortalized copy. If you need something stable across
1812 * calls, you need to savepv() the result yourself.
1814 *===========================================================================*/
1816 #if (! defined(USE_LOCALE_THREADS) && ! defined(USE_POSIX_2008_LOCALE)) \
1817 || ( defined(WIN32) && defined(USE_THREAD_SAFE_LOCALE))
1819 /* For non-threaded perls, the implementation just expands to the base-level
1820 * functions (except if we are Configured to nonetheless use the POSIX 2008
1821 * interface) This implementation is also used on threaded perls where
1822 * threading is invisible to us. Currently this is only on later Windows
1825 # define querylocale_r(cat) mortalized_pv_copy(stdized_setlocale(cat, NULL))
1826 # define querylocale_c(cat) querylocale_r(cat)
1827 # define querylocale_i(i) querylocale_c(categories[i])
1829 /*---------------------------------------------------------------------------*/
1831 # define bool_setlocale_r(cat, locale) cBOOL(posix_setlocale(cat, locale))
1832 # define bool_setlocale_i(i, locale) \
1833 bool_setlocale_c(categories[i], locale)
1834 # define bool_setlocale_c(cat, locale) bool_setlocale_r(cat, locale)
1836 /*---------------------------------------------------------------------------*/
1838 # define void_setlocale_r_with_caller(cat, locale, file, line) \
1840 if (! bool_setlocale_r(cat, locale)) \
1841 setlocale_failure_panic_via_i(get_category_index(cat), \
1842 NULL, locale, __LINE__, 0, \
1846 # define void_setlocale_c_with_caller(cat, locale, file, line) \
1847 void_setlocale_r_with_caller(cat, locale, file, line)
1849 # define void_setlocale_i_with_caller(i, locale, file, line) \
1850 void_setlocale_r_with_caller(categories[i], locale, file, line)
1852 # define void_setlocale_r(cat, locale) \
1853 void_setlocale_r_with_caller(cat, locale, __FILE__, __LINE__)
1854 # define void_setlocale_c(cat, locale) void_setlocale_r(cat, locale)
1855 # define void_setlocale_i(i, locale) void_setlocale_r(categories[i], locale)
1857 /*---------------------------------------------------------------------------*/
1859 /* setlocale_i is only defined for Configurations where the libc setlocale()
1860 * doesn't need any tweaking. It allows for some shortcuts */
1861 # ifndef USE_LOCALE_THREADS
1862 # define setlocale_i(i, locale) stdized_setlocale(categories[i], locale)
1864 # elif defined(WIN32) && defined(USE_THREAD_SAFE_LOCALE)
1866 /* On Windows, we don't know at compile time if we are in thread-safe mode or
1867 * not. If we are, we can just return the result of the layer below us. If we
1868 * are in unsafe mode, we need to first copy that result to a safe place while
1869 * in a critical section */
1871 # define setlocale_i(i, locale) S_setlocale_i(aTHX_ categories[i], locale)
1874 S_setlocale_i(pTHX_ const int category, const char * locale)
1876 if (LIKELY(_configthreadlocale(0) == _ENABLE_PER_THREAD_LOCALE)) {
1877 return stdized_setlocale(category, locale);
1881 const char * retval = save_to_buffer(stdized_setlocale(category, locale),
1883 &PL_setlocale_bufsize);
1891 /*===========================================================================*/
1892 #elif defined(USE_LOCALE_THREADS) \
1893 && ! defined(USE_THREAD_SAFE_LOCALE)
1895 /* Here, there are threads, and there is no support for thread-safe
1896 * operation. This is a dangerous situation, which perl is documented as
1897 * not supporting, but it arises in practice. We can do a modicum of
1898 * automatic mitigation by making sure there is a per-thread return from
1899 * setlocale(), and that a mutex protects it from races */
1901 # define querylocale_r(cat) \
1902 mortalized_pv_copy(less_dicey_setlocale_r(cat, NULL))
1903 # define querylocale_c(cat) querylocale_r(cat)
1904 # define querylocale_i(i) querylocale_r(categories[i])
1907 S_less_dicey_setlocale_r(pTHX_ const int category, const char * locale)
1909 const char * retval;
1911 PERL_ARGS_ASSERT_LESS_DICEY_SETLOCALE_R;
1913 STDIZED_SETLOCALE_LOCK;
1915 retval = save_to_buffer(stdized_setlocale(category, locale),
1916 &PL_less_dicey_locale_buf,
1917 &PL_less_dicey_locale_bufsize);
1919 STDIZED_SETLOCALE_UNLOCK;
1924 /*---------------------------------------------------------------------------*/
1926 # define bool_setlocale_r(cat, locale) \
1927 less_dicey_bool_setlocale_r(cat, locale)
1928 # define bool_setlocale_i(i, locale) \
1929 bool_setlocale_r(categories[i], locale)
1930 # define bool_setlocale_c(cat, locale) bool_setlocale_r(cat, locale)
1933 S_less_dicey_bool_setlocale_r(pTHX_ const int cat, const char * locale)
1937 PERL_ARGS_ASSERT_LESS_DICEY_BOOL_SETLOCALE_R;
1939 /* Unlikely, but potentially possible that another thread could zap the
1940 * buffer from true to false or vice-versa, so need to lock here */
1941 POSIX_SETLOCALE_LOCK;
1942 retval = cBOOL(posix_setlocale(cat, locale));
1943 POSIX_SETLOCALE_UNLOCK;
1948 /*---------------------------------------------------------------------------*/
1950 # define void_setlocale_r_with_caller(cat, locale, file, line) \
1952 if (! bool_setlocale_r(cat, locale)) \
1953 setlocale_failure_panic_via_i(get_category_index(cat), \
1954 NULL, locale, __LINE__, 0, \
1958 # define void_setlocale_c_with_caller(cat, locale, file, line) \
1959 void_setlocale_r_with_caller(cat, locale, file, line)
1961 # define void_setlocale_i_with_caller(i, locale, file, line) \
1962 void_setlocale_r_with_caller(categories[i], locale, file, line)
1964 # define void_setlocale_r(cat, locale) \
1965 void_setlocale_r_with_caller(cat, locale, __FILE__, __LINE__)
1966 # define void_setlocale_c(cat, locale) void_setlocale_r(cat, locale)
1967 # define void_setlocale_i(i, locale) void_setlocale_r(categories[i], locale)
1969 /*===========================================================================*/
1971 #elif defined(USE_POSIX_2008_LOCALE)
1973 # error This code assumes that LC_ALL is available on a system modern enough to have POSIX 2008
1976 /* Here, there is a completely different API to get thread-safe locales. We
1977 * emulate the setlocale() API with our own function(s). setlocale categories,
1978 * like LC_NUMERIC, are not valid here for the POSIX 2008 API. Instead, there
1979 * are equivalents, like LC_NUMERIC_MASK, which we use instead, which we find
1980 * by table lookup. */
1982 # if defined(__GLIBC__) && defined(USE_LOCALE_MESSAGES)
1983 /* https://sourceware.org/bugzilla/show_bug.cgi?id=24936 */
1984 # define HAS_GLIBC_LC_MESSAGES_BUG
1985 # include <libintl.h>
1988 # define querylocale_i(i) querylocale_2008_i(i, __LINE__)
1989 # define querylocale_c(cat) querylocale_i(cat##_INDEX_)
1990 # define querylocale_r(cat) querylocale_i(get_category_index(cat))
1993 S_querylocale_2008_i(pTHX_ const locale_category_index index,
1994 const line_t caller_line)
1996 PERL_ARGS_ASSERT_QUERYLOCALE_2008_I;
1997 assert(index <= LC_ALL_INDEX_);
1999 /* This function returns the name of the locale category given by the input
2000 * 'index' into our parallel tables of them.
2002 * POSIX 2008, for some sick reason, chose not to provide a method to find
2003 * the category name of a locale, disregarding a basic linguistic tenet
2004 * that for any object, people will create a name for it. (The next
2005 * version of the POSIX standard is proposed to fix this.) Some vendors
2006 * have created a querylocale() function to do this in the meantime. On
2007 * systems without querylocale(), we have to keep track of what the locale
2008 * has been set to, so that we can return its name so as to emulate
2009 * setlocale(). There are potential problems with this:
2011 * 1) We don't know what calling newlocale() with the locale argument ""
2012 * actually does. It gets its values from the program's environment.
2013 * find_locale_from_environment() is used to work around this. But it
2014 * isn't fool-proof. See the comments for that function for details.
2015 * 2) It's possible for C code in some library to change the locale
2016 * without us knowing it, and thus our records become wrong;
2017 * querylocale() would catch this. But as of September 2017, there
2018 * are no occurrences in CPAN of uselocale(). Some libraries do use
2019 * setlocale(), but that changes the global locale, and threads using
2020 * per-thread locales will just ignore those changes.
2021 * 3) Many systems have multiple names for the same locale. Generally,
2022 * there is an underlying base name, with aliases that evaluate to it.
2023 * On some systems, if you set the locale to an alias, and then
2024 * retrieve the name, you get the alias as expected; but on others you
2025 * get the base name, not the alias you used. And sometimes the
2026 * charade is incomplete. See
2027 * https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=269375.
2029 * The code is structured so that the returned locale name when the
2030 * locale is changed is whatever the result of querylocale() on the
2031 * new locale is. This effectively gives the result the system
2032 * expects. Without querylocale, the name returned is always the
2033 * input name. Theoretically this could cause problems, but khw knows
2034 * of none so far, but mentions it here in case you are trying to
2035 * debug something. (This could be worked around by messing with the
2036 * global locale temporarily, using setlocale() to get the base name;
2037 * but that could cause a race. The comments for
2038 * find_locale_from_environment() give details on the potential race.)
2041 const locale_t cur_obj = uselocale((locale_t) 0);
2042 const char * retval;
2044 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "querylocale_2008_i(%s) on %p;"
2045 " called from %" LINE_Tf "\n",
2046 category_names[index], cur_obj,
2049 if (UNLIKELY(cur_obj == LC_GLOBAL_LOCALE)) {
2051 /* Even on platforms that have querylocale(), it is unclear if they
2052 * work in the global locale, and we have the means to get the correct
2053 * answer anyway. khw is unsure this situation even comes up these
2054 * days, hence the branch prediction */
2055 POSIX_SETLOCALE_LOCK;
2056 retval = mortalized_pv_copy(posix_setlocale(categories[index], NULL));
2057 POSIX_SETLOCALE_UNLOCK;
2060 /* Here we have handled the case of the the current locale being the global
2061 * one. Below is the 'else' case of that. There are two different
2062 * implementations, depending on USE_PL_CURLOCALES */
2064 # ifdef USE_PL_CURLOCALES
2068 /* PL_curlocales[] is kept up-to-date for all categories except LC_ALL,
2069 * which may have been invalidated by setting it to NULL, and if so,
2070 * should now be calculated. (The called function updates that
2072 if (index == LC_ALL_INDEX_ && PL_curlocales[LC_ALL_INDEX_] == NULL) {
2073 calculate_LC_ALL_string((const char **) &PL_curlocales,
2079 if (cur_obj == PL_C_locale_obj) {
2081 /* If the current locale object is the C object, then the answer is
2082 * "C" or POSIX, regardless of the category. Handling this
2083 * reasonably likely case specially shortcuts extra effort, and
2084 * hides some bugs from us in OS's that alias other locales to C,
2085 * but do so incompletely. If our records say it is POSIX, use
2086 * that; otherwise use C. See
2087 * https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=269375 */
2088 retval = mortalized_pv_copy((strEQ(PL_curlocales[index], "POSIX"))
2093 retval = mortalized_pv_copy(PL_curlocales[index]);
2099 /* Below is the implementation of the 'else' clause which handles the case
2100 * of the current locale not being the global one on platforms where
2101 * USE_PL_CURLOCALES is NOT in effect. That means the system must have
2102 * some form of querylocale. But these have varying characteristics, so
2103 * first create some #defines to make the actual 'else' clause uniform.
2105 * First, glibc has a function that implements querylocale(), but is called
2106 * something else, and takes the category number; the others take the mask.
2108 # if defined(USE_QUERYLOCALE) && ( defined(_NL_LOCALE_NAME) \
2109 && defined(HAS_NL_LANGINFO_L))
2110 # define my_querylocale(index, cur_obj) \
2111 nl_langinfo_l(_NL_LOCALE_NAME(categories[index]), cur_obj)
2113 /* Experience so far shows it is thread-safe, as well as glibc's
2114 * nl_langinfo_l(), so unless overridden, mark it so */
2115 # ifdef NO_THREAD_SAFE_QUERYLOCALE
2116 # undef HAS_THREAD_SAFE_QUERYLOCALE
2118 # define HAS_THREAD_SAFE_QUERYLOCALE
2120 # else /* below, ! glibc */
2122 /* Otherwise, use the system's querylocale(). */
2123 # define my_querylocale(index, cur_obj) \
2124 querylocale(category_masks[index], cur_obj)
2126 /* There is no standard for this function, and khw has never seen
2127 * anything beyond minimal vendor documentation, lacking important
2128 * details. Experience has shown that some implementations have race
2129 * condiions, and their returns may not be thread safe. It would be
2130 * unreliable to test for complete thread safety in Configure. What we
2131 * do instead is to assume that it is thread-safe, unless overriden by,
2132 * say, a hints file specifying
2133 * -Accflags='-DNO_THREAD_SAFE_QUERYLOCALE */
2134 # ifdef NO_THREAD_SAFE_QUERYLOCALE
2135 # undef HAS_THREAD_SAFE_QUERYLOCALE
2137 # define HAS_THREAD_SAFE_QUERYLOCALE
2141 /* Here, we have set up enough information to know if this querylocale()
2142 * is thread-safe, or needs to use a mutex */
2143 # ifdef HAS_THREAD_SAFE_QUERYLOCALE
2144 # define QUERYLOCALE_LOCK
2145 # define QUERYLOCALE_UNLOCK
2147 # define QUERYLOCALE_LOCK gwLOCALE_LOCK
2148 # define QUERYLOCALE_UNLOCK gwLOCALE_UNLOCK
2151 /* Finally, everything is ready, so here is the 'else' clause to implement
2152 * the case of the current locale not being the global one on systems that
2153 * have some form of querylocale(). (POSIX will presumably eventually
2154 * publish their next version in their pipeline, which will define a
2155 * precisely specified querylocale equivalent, and there can be a new
2156 * #ifdef to use it without having to guess at its characteristics) */
2159 /* We don't keep records when there is querylocale(), so as to avoid the
2160 * pitfalls mentioned at the beginning of this function.
2162 * That means LC_ALL has to be calculated from all its constituent
2163 * categories each time, since the querylocale() forms on many (if not
2164 * all) platforms only work on individual categories */
2165 if (index == LC_ALL_INDEX_) {
2166 retval = calculate_LC_ALL_string(NULL, INTERNAL_FORMAT,
2173 retval = savepv(my_querylocale(index, cur_obj));
2176 /* querylocale() may conflate the C locale with something that
2177 * isn't exactly the same. See for example
2178 * https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=269375
2179 * We know that if the locale object is the C one, we
2180 * are in the C locale, which may go by the name POSIX, as both, by
2181 * definition, are equivalent. But we consider any other name
2182 * spurious, so override with "C". As in the PL_CURLOCALES case
2183 * above, this hides those glitches, for the most part, from the
2184 * rest of our code. (The code is ordered this way so that if the
2185 * system distinugishes "C" from "POSIX", we do too.) */
2186 if (cur_obj == PL_C_locale_obj && ! isNAME_C_OR_POSIX(retval)) {
2188 retval = savepv("C");
2195 # undef QUERYLOCALE_LOCK
2196 # undef QUERYLOCALE_UNLOCK
2199 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2200 "querylocale_2008_i(%s) returning '%s'\n",
2201 category_names[index], retval));
2202 assert(strNE(retval, ""));
2206 /*---------------------------------------------------------------------------*/
2208 # define bool_setlocale_i(i, locale) \
2209 bool_setlocale_2008_i(i, locale, __LINE__)
2210 # define bool_setlocale_c(cat, locale) \
2211 bool_setlocale_i(cat##_INDEX_, locale)
2212 # define bool_setlocale_r(cat, locale) \
2213 bool_setlocale_i(get_category_index(cat), locale)
2215 /* If this doesn't exist on this platform, make it a no-op (to save #ifdefs) */
2216 # ifndef update_PL_curlocales_i
2217 # define update_PL_curlocales_i(index, new_locale, caller_line)
2221 S_bool_setlocale_2008_i(pTHX_
2223 /* Our internal index of the 'category' setlocale is called with */
2224 const locale_category_index index,
2225 const char * new_locale, /* The locale to set the category to */
2226 const line_t caller_line /* Called from this line number */
2229 PERL_ARGS_ASSERT_BOOL_SETLOCALE_2008_I;
2230 assert(index <= LC_ALL_INDEX_);
2232 /* This function effectively performs a setlocale() on just the current
2233 * thread; thus it is thread-safe. It does this by using the POSIX 2008
2234 * locale functions to emulate the behavior of setlocale(). Similar to
2235 * regular setlocale(), the return from this function points to memory that
2236 * can be overwritten by other system calls, so needs to be copied
2237 * immediately if you need to retain it. The difference here is that
2238 * system calls besides another setlocale() can overwrite it.
2240 * By doing this, most locale-sensitive functions become thread-safe. The
2241 * exceptions are mostly those that return a pointer to static memory.
2244 int mask = category_masks[index];
2245 const locale_t entry_obj = uselocale((locale_t) 0);
2246 const char * locale_on_entry = querylocale_i(index);
2248 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2249 "bool_setlocale_2008_i: input=%d (%s), mask=0x%x,"
2250 " new locale=\"%s\", current locale=\"%s\","
2251 " index=%d, entry object=%p;"
2252 " called from %" LINE_Tf "\n",
2253 categories[index], category_names[index], mask,
2254 ((new_locale == NULL) ? "(nil)" : new_locale),
2255 locale_on_entry, index, entry_obj, caller_line));
2257 /* Here, trying to change the locale, but it is a no-op if the new boss is
2258 * the same as the old boss. Except this routine is called when converting
2259 * from the global locale, so in that case we will create a per-thread
2260 * locale below (with the current values). It also seemed that newlocale()
2261 * could free up the basis locale memory if we called it with the new and
2262 * old being the same, but khw now thinks that this was due to some other
2263 * bug, since fixed, as there are other places where newlocale() gets
2264 * similarly called without problems. */
2265 if ( entry_obj != LC_GLOBAL_LOCALE
2267 && strEQ(new_locale, locale_on_entry))
2269 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2270 "bool_setlocale_2008_i: no-op to change to"
2271 " what it already was\n"));
2275 # ifndef USE_QUERYLOCALE
2277 /* Without a querylocale() mechanism, we have to figure out ourselves what
2278 * happens with setting a locale to "" */
2280 if (strEQ(new_locale, "")) {
2281 new_locale = find_locale_from_environment(index);
2289 # ifdef NEWLOCALE_HANDLES_DISPARATE_LC_ALL
2291 const bool need_loop = false;
2295 bool need_loop = false;
2296 const char * new_locales[LC_ALL_INDEX_] = { NULL };
2298 /* If we're going to have to parse the LC_ALL string, might as well do it
2299 * now before we have made changes that we would have to back out of if the
2301 if (index == LC_ALL_INDEX_) {
2302 switch (parse_LC_ALL_string(new_locale,
2303 (const char **) &new_locales,
2304 override_if_ignored,
2305 false, /* Return only [0] if suffices */
2306 false, /* Don't panic on error */
2317 case only_element_0:
2318 SAVEFREEPV(new_locales[0]);
2319 new_locale = new_locales[0];
2330 # ifdef HAS_GLIBC_LC_MESSAGES_BUG
2332 /* For this bug, if the LC_MESSAGES locale changes, we have to do an
2333 * expensive workaround. Save the current value so we can later determine
2335 const char * old_messages_locale = NULL;
2336 if ( (index == LC_MESSAGES_INDEX_ || index == LC_ALL_INDEX_)
2337 && LIKELY(PL_phase != PERL_PHASE_CONSTRUCT))
2339 old_messages_locale = querylocale_c(LC_MESSAGES);
2344 assert(PL_C_locale_obj);
2346 /* Now ready to switch to the input 'new_locale' */
2348 /* Switching locales generally entails freeing the current one's space (at
2349 * the C library's discretion), hence we can't be using that locale at the
2350 * time of the switch (this wasn't obvious to khw from the man pages). So
2351 * switch to a known locale object that we don't otherwise mess with. */
2352 if (! uselocale(PL_C_locale_obj)) {
2354 /* Not being able to change to the C locale is severe; don't keep
2356 setlocale_failure_panic_i(index, locale_on_entry, "C",
2357 __LINE__, caller_line);
2358 NOT_REACHED; /* NOTREACHED */
2361 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2362 "bool_setlocale_2008_i: now using C"
2363 " object=%p\n", PL_C_locale_obj));
2365 /* These two objects are special:
2366 * LC_GLOBAL_LOCALE because it is undefined behavior to call
2367 * newlocale() with it as a parameter.
2368 * PL_C_locale_obj because newlocale() generally destroys its locale
2369 * object parameter when it succeeds; and we don't
2370 * want that happening to this immutable object.
2371 * Copies will be made for them to use instead if we get so far as to call
2373 bool entry_obj_is_special = ( entry_obj == LC_GLOBAL_LOCALE
2374 || entry_obj == PL_C_locale_obj);
2377 /* PL_C_locale_obj is LC_ALL set to the C locale. If this call is to
2378 * switch to LC_ALL => C, simply use that object. But in fact, we already
2379 * have switched to it just above, in preparation for the general case.
2380 * Since we're already there, no need to do further switching. */
2381 if (mask == LC_ALL_MASK && isNAME_C_OR_POSIX(new_locale)) {
2382 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2383 "bool_setlocale_2008_i: will stay in C"
2385 new_obj = PL_C_locale_obj;
2387 /* 'entry_obj' is now dangling, of no further use to anyone (unless it
2388 * is one of the special ones). Free it to avoid a leak */
2389 if (! entry_obj_is_special) {
2390 freelocale(entry_obj);
2393 update_PL_curlocales_i(index, new_locale, caller_line);
2395 else { /* Here is the general case, not to LC_ALL => C */
2397 /* The newlocale() call(s) below take a basis object to build upon to
2398 * create the changed locale, trashing it iff successful.
2400 * For the objects that are not to be modified by this function, we
2401 * create a duplicate that gets trashed instead.
2403 * Also if we will have to loop doing multiple newlocale()s, there is a
2404 * chance we will succeed for the first few, and then fail, having to
2405 * back out. We need to duplicate 'entry_obj' in this case as well, so
2406 * it remains valid as something to back out to. */
2407 locale_t basis_obj = entry_obj;
2409 if (entry_obj_is_special || need_loop) {
2410 basis_obj = duplocale(basis_obj);
2412 locale_panic_via_("duplocale failed", __FILE__, caller_line);
2413 NOT_REACHED; /* NOTREACHED */
2416 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2417 "bool_setlocale_2008_i created %p by"
2418 " duping the input\n", basis_obj));
2421 # define DEBUG_NEW_OBJECT_CREATED(category, locale, new, old, caller_line) \
2422 DEBUG_Lv(PerlIO_printf(Perl_debug_log, \
2423 "bool_setlocale_2008_i(%s, %s): created %p" \
2424 " while freeing %p; called from %" LINE_Tf \
2425 " via %" LINE_Tf "\n", \
2426 category, locale, new, old, \
2427 caller_line, __LINE__))
2428 # define DEBUG_NEW_OBJECT_FAILED(category, locale, basis_obj) \
2429 DEBUG_L(PerlIO_printf(Perl_debug_log, \
2430 "bool_setlocale_2008_i: creating new object" \
2431 " for (%s '%s') from %p failed; called from %" \
2432 LINE_Tf " via %" LINE_Tf "\n", \
2433 category, locale, basis_obj, \
2434 caller_line, __LINE__));
2436 /* Ready to create a new locale by modification of the existing one.
2438 * NOTE: This code may incorrectly show up as a leak under the address
2439 * sanitizer. We do not free this object under normal teardown, however
2440 * you can set PERL_DESTRUCT_LEVEL=2 to cause it to be freed.
2443 # ifdef NEWLOCALE_HANDLES_DISPARATE_LC_ALL
2445 /* Some platforms have a newlocale() that can handle disparate LC_ALL
2446 * input, so on these a single call to newlocale() always works */
2449 /* If a single call to newlocale() will do */
2455 new_obj = newlocale(mask,
2456 override_ignored_category(index, new_locale),
2459 DEBUG_NEW_OBJECT_FAILED(category_names[index], new_locale,
2462 /* Since the call failed, it didn't trash 'basis_obj', which is
2463 * a dup for these objects, and hence would leak if we don't
2464 * free it. XXX However, something is seriously wrong if we
2465 * can't switch to C or the global locale, so maybe should
2467 if (entry_obj_is_special) {
2468 freelocale(basis_obj);
2471 goto must_restore_state;
2474 DEBUG_NEW_OBJECT_CREATED(category_names[index], new_locale,
2475 new_obj, basis_obj, caller_line);
2477 update_PL_curlocales_i(index, new_locale, caller_line);
2480 # ifndef NEWLOCALE_HANDLES_DISPARATE_LC_ALL
2482 else { /* Need multiple newlocale() calls */
2484 /* Loop through the individual categories, setting the locale of
2485 * each to the corresponding name previously populated into
2486 * newlocales[]. Each iteration builds on the previous one, adding
2487 * its category to what's already been calculated, and taking as a
2488 * basis for what's been calculated 'basis_obj', which is updated
2489 * each iteration to be the result of the previous one. Upon
2490 * success, newlocale() trashes the 'basis_obj' parameter to it.
2491 * If any iteration fails, we immediately give up, restore the
2492 * locale to what it was at the time this function was called
2493 * (saved in 'entry_obj'), and return failure. */
2495 /* Loop, using the previous iteration's result as the basis for the
2496 * next one. (The first time we effectively use the locale in
2497 * force upon entry to this function.) */
2498 for_all_individual_category_indexes(i) {
2499 new_obj = newlocale(category_masks[i],
2503 DEBUG_NEW_OBJECT_CREATED(category_names[i],
2507 basis_obj = new_obj;
2511 /* Failed. Likely this is because the proposed new locale
2512 * isn't valid on this system. */
2514 DEBUG_NEW_OBJECT_FAILED(category_names[i],
2518 /* newlocale() didn't trash this, since the function call
2520 freelocale(basis_obj);
2522 for_all_individual_category_indexes(j) {
2523 Safefree(new_locales[j]);
2526 goto must_restore_state;
2529 /* Success for all categories. */
2530 for_all_individual_category_indexes(i) {
2531 update_PL_curlocales_i(i, new_locales[i], caller_line);
2532 Safefree(new_locales[i]);
2535 /* We dup'd entry_obj in case we had to fall back to it. The
2536 * newlocale() above destroyed the dup when it first succeeded, but
2537 * entry_obj itself is left dangling, so free it */
2538 if (! entry_obj_is_special) {
2539 freelocale(entry_obj);
2543 # endif /* End of newlocale can't handle disparate LC_ALL input */
2547 # undef DEBUG_NEW_OBJECT_CREATED
2548 # undef DEBUG_NEW_OBJECT_FAILED
2550 /* Here, successfully created an object representing the desired locale;
2551 * now switch into it */
2552 if (! uselocale(new_obj)) {
2553 freelocale(new_obj);
2554 locale_panic_(Perl_form(aTHX_ "(called from %" LINE_Tf "):"
2555 " bool_setlocale_2008_i: switching"
2556 " into new locale failed",
2560 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2561 "bool_setlocale_2008_i: now using %p\n", new_obj));
2563 # ifdef MULTIPLICITY /* Unlikely, but POSIX 2008 functions could be
2564 Configured to be used on unthreaded perls, in which
2565 case this object doesn't exist */
2567 if (DEBUG_Lv_TEST) {
2568 if (PL_cur_locale_obj != new_obj) {
2569 PerlIO_printf(Perl_debug_log,
2570 "bool_setlocale_2008_i: PL_cur_locale_obj"
2571 " was %p, now is %p\n",
2572 PL_cur_locale_obj, new_obj);
2576 /* Update the current object */
2577 PL_cur_locale_obj = new_obj;
2580 # ifdef HAS_GLIBC_LC_MESSAGES_BUG
2582 /* Invalidate the glibc cache of loaded translations if the locale has
2583 * changed, see [perl #134264] and
2584 * https://sourceware.org/bugzilla/show_bug.cgi?id=24936 */
2585 if (old_messages_locale) {
2586 if (strNE(old_messages_locale, querylocale_c(LC_MESSAGES))) {
2587 textdomain(textdomain(NULL));
2597 /* We earlier switched to the LC_ALL => C locale in anticipation of it
2598 * succeeding, Now have to switch back to the state upon entry. */
2599 if (! uselocale(entry_obj)) {
2600 setlocale_failure_panic_i(index, "switching back to",
2601 locale_on_entry, __LINE__, caller_line);
2607 /*---------------------------------------------------------------------------*/
2609 # define void_setlocale_i_with_caller(i, locale, file, line) \
2611 if (! bool_setlocale_i(i, locale)) \
2612 setlocale_failure_panic_via_i(i, NULL, locale, __LINE__, 0, \
2616 # define void_setlocale_r_with_caller(cat, locale, file, line) \
2617 void_setlocale_i_with_caller(get_category_index(cat), locale, \
2620 # define void_setlocale_c_with_caller(cat, locale, file, line) \
2621 void_setlocale_i_with_caller(cat##_INDEX_, locale, file, line)
2623 # define void_setlocale_i(i, locale) \
2624 void_setlocale_i_with_caller(i, locale, __FILE__, __LINE__)
2625 # define void_setlocale_c(cat, locale) \
2626 void_setlocale_i(cat##_INDEX_, locale)
2627 # define void_setlocale_r(cat, locale) \
2628 void_setlocale_i(get_category_index(cat), locale)
2630 /*===========================================================================*/
2633 # error Unexpected Configuration
2634 #endif /* End of the various implementations of the setlocale and
2635 querylocale macros used in the remainder of this program */
2637 /* query_nominal_locale_i() is used when the caller needs the locale that an
2638 * external caller would be expecting, and not what we're secretly using
2639 * behind the scenes. It deliberately doesn't handle LC_ALL; use
2640 * calculate_LC_ALL_string() for that. */
2641 #ifdef USE_LOCALE_NUMERIC
2642 # define query_nominal_locale_i(i) \
2643 (__ASSERT_(i != LC_ALL_INDEX_) \
2644 ((i == LC_NUMERIC_INDEX_) ? PL_numeric_name : querylocale_i(i)))
2646 # define query_nominal_locale_i(i) \
2647 (__ASSERT_(i != LC_ALL_INDEX_) querylocale_i(i))
2650 #ifdef USE_PL_CURLOCALES
2653 S_update_PL_curlocales_i(pTHX_
2654 const locale_category_index index,
2655 const char * new_locale,
2656 const line_t caller_line)
2658 /* Update PL_curlocales[], which is parallel to the other ones indexed by
2659 * our mapping of libc category number to our internal equivalents. */
2661 PERL_ARGS_ASSERT_UPDATE_PL_CURLOCALES_I;
2662 assert(index <= LC_ALL_INDEX_);
2664 if (index == LC_ALL_INDEX_) {
2666 /* For LC_ALL, we change all individual categories to correspond,
2667 * including the LC_ALL element */
2668 for (unsigned int i = 0; i <= LC_ALL_INDEX_; i++) {
2669 Safefree(PL_curlocales[i]);
2670 PL_curlocales[i] = NULL;
2673 switch (parse_LC_ALL_string(new_locale,
2674 (const char **) &PL_curlocales,
2675 check_that_overridden, /* things should
2679 true, /* Always fill array */
2680 true, /* Panic if fails, as to get here
2681 it earlier had to have succeeded
2687 case only_element_0:
2688 locale_panic_via_("Unexpected return from parse_LC_ALL_string",
2689 __FILE__, caller_line);
2692 /* parse_LC_ALL_string() has already filled PL_curlocales properly,
2693 * except for the LC_ALL element, which should be set to
2695 PL_curlocales[LC_ALL_INDEX_] = savepv(new_locale);
2698 else { /* Not LC_ALL */
2700 /* Update the single category's record */
2701 Safefree(PL_curlocales[index]);
2702 PL_curlocales[index] = savepv(new_locale);
2704 /* Invalidate LC_ALL */
2705 Safefree(PL_curlocales[LC_ALL_INDEX_]);
2706 PL_curlocales[LC_ALL_INDEX_] = NULL;
2710 # endif /* Need PL_curlocales[] */
2712 /*===========================================================================*/
2714 #if defined(USE_LOCALE)
2716 /* This paradigm is needed in several places in the function below. We have to
2717 * substitute the nominal locale for LC_NUMERIC when returning a value for
2718 * external consumption */
2719 # ifndef USE_LOCALE_NUMERIC
2720 # define ENTRY(i, array, format) array[i]
2722 # define ENTRY(i, array, format) \
2723 (UNLIKELY( format == EXTERNAL_FORMAT_FOR_QUERY \
2724 && i == LC_NUMERIC_INDEX_) \
2731 S_calculate_LC_ALL_string(pTHX_ const char ** category_locales_list,
2732 const calc_LC_ALL_format format,
2733 const calc_LC_ALL_return returning,
2734 const line_t caller_line)
2736 PERL_ARGS_ASSERT_CALCULATE_LC_ALL_STRING;
2738 /* NOTE: On Configurations that have PL_curlocales[], this function has the
2739 * side effect of updating the LC_ALL_INDEX_ element with its result.
2741 * This function calculates a string that defines the locale(s) LC_ALL is
2742 * set to, in either:
2743 * 1) Our internal format if 'format' is set to INTERNAL_FORMAT.
2744 * 2) The external format returned by Perl_setlocale() if 'format' is set
2745 * to EXTERNAL_FORMAT_FOR_QUERY or EXTERNAL_FORMAT_FOR_SET.
2747 * These two are distinguished by:
2748 * a) EXTERNAL_FORMAT_FOR_SET returns the actual locale currently in
2750 * b) EXTERNAL_FORMAT_FOR_QUERY returns the nominal locale.
2751 * Currently this can differ only from the actual locale in the
2752 * LC_NUMERIC category when it is set to a locale whose radix is
2753 * not a dot. (The actual locale is kept as a dot to accommodate
2754 * the large corpus of XS code that expects it to be that;
2755 * switched to a non-dot temporarily during certain operations
2756 * that require the actual radix.)
2758 * In both 1) and 2), LC_ALL's values are passed to this function by
2759 * 'category_locales_list' which is either:
2760 * 1) a pointer to an array of strings with up-to-date values of all the
2761 * individual categories; or
2762 * 2) NULL, to indicate to use querylocale_i() to get each individual
2765 * The caller sets 'returning' to
2766 * WANT_TEMP_PV the function returns the calculated string
2767 * as a mortalized temporary, so the caller
2768 * doesn't have to worry about it being
2769 * per-thread, nor needs to arrange for its
2771 * WANT_PL_setlocale_buf the function stores the calculated string
2772 * into the per-thread buffer PL_setlocale_buf
2773 * and returns a pointer to that. The buffer
2774 * is cleaned up automatically in process
2775 * destruction. This return method avoids
2776 * extra copies in some circumstances.
2777 * WANT_VOID NULL is returned. This is used when the
2778 * function is being called only for its side
2779 * effect of updating
2780 * PL_curlocales[LC_ALL_INDEX_]
2782 * querylocale(), on systems that have it, doesn't tend to work for LC_ALL.
2783 * So we have to construct the answer ourselves based on the passed in
2786 * If all individual categories are the same locale, we can just set LC_ALL
2787 * to that locale. But if not, we have to create an aggregation of all the
2788 * categories on the system. Platforms differ as to the syntax they use
2789 * for these non-uniform locales for LC_ALL. Some, like glibc and Windows,
2790 * use an unordered series of name=value pairs, like
2791 * LC_NUMERIC=C;LC_TIME=en_US.UTF-8;...
2792 * to specify LC_ALL; others, like *BSD, use a positional notation with a
2793 * delimitter, typically a single '/' character:
2796 * When the external format is desired, this function returns whatever the
2797 * system expects. The internal format is always name=value pairs.
2799 * For systems that have categories we don't know about, the algorithm
2800 * below won't know about those missing categories, leading to potential
2801 * bugs for code that looks at them. If there is an environment variable
2802 * that sets that category, we won't know to look for it, and so our use of
2803 * LANG or "C" improperly overrides it. On the other hand, if we don't do
2804 * what is done here, and there is no environment variable, the category's
2805 * locale should be set to LANG or "C". So there is no good solution. khw
2806 * thinks the best is to make sure we have a complete list of possible
2807 * categories, adding new ones as they show up on obscure platforms.
2810 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
2811 "Entering calculate_LC_ALL_string(%s);"
2812 " called from %" LINE_Tf "\n",
2813 ((format == EXTERNAL_FORMAT_FOR_QUERY)
2814 ? "EXTERNAL_FORMAT_FOR_QUERY"
2815 : ((format == EXTERNAL_FORMAT_FOR_SET)
2816 ? "EXTERNAL_FORMAT_FOR_SET"
2817 : "INTERNAL_FORMAT")),
2820 bool input_list_was_NULL = (category_locales_list == NULL);
2822 /* If there was no input category list, construct a temporary one
2824 const char * my_category_locales_list[LC_ALL_INDEX_];
2825 const char ** locales_list = category_locales_list;
2826 if (locales_list == NULL) {
2827 locales_list = my_category_locales_list;
2829 if (format == EXTERNAL_FORMAT_FOR_QUERY) {
2830 for_all_individual_category_indexes(i) {
2831 locales_list[i] = query_nominal_locale_i(i);
2835 for_all_individual_category_indexes(i) {
2836 locales_list[i] = querylocale_i(i);
2841 /* While we are calculating LC_ALL, we see if every category's locale is
2842 * the same as every other's or not. */
2843 # ifndef HAS_IGNORED_LOCALE_CATEGORIES_
2845 /* When we pay attention to all categories, we assume they are all the same
2846 * until proven different */
2847 bool disparate = false;
2851 /* But if there are ignored categories, those will be set to "C", so try an
2852 * arbitrary category, and if it isn't C, we know immediately that the
2853 * locales are disparate. (The #if conditionals are to handle the case
2854 * where LC_NUMERIC_INDEX_ is 0. We don't want to use LC_NUMERIC to
2855 * compare, as that may be different between external and internal forms.)
2857 # if ! defined(USE_LOCALE_NUMERIC)
2859 bool disparate = ! isNAME_C_OR_POSIX(locales_list[0]);
2861 # elif LC_NUMERIC_INDEX_ != 0
2863 bool disparate = ! isNAME_C_OR_POSIX(locales_list[0]);
2867 /* Would need revision to handle the very unlikely case where only a single
2868 * category, LC_NUMERIC, is defined */
2869 assert(LOCALE_CATEGORIES_COUNT_ > 0);
2871 bool disparate = ! isNAME_C_OR_POSIX(locales_list[1]);
2876 /* Calculate the needed size for the string listing the individual locales.
2877 * Initialize with values known at compile time. */
2879 const char *separator;
2881 # ifdef PERL_LC_ALL_USES_NAME_VALUE_PAIRS /* Positional formatted LC_ALL */
2882 PERL_UNUSED_ARG(format);
2885 if (format != INTERNAL_FORMAT) {
2887 /* Here, we will be using positional notation. it includes n-1
2889 total_len = ( LOCALE_CATEGORIES_COUNT_ - 1)
2890 * STRLENs(PERL_LC_ALL_SEPARATOR)
2891 + 1; /* And a trailing NUL */
2892 separator = PERL_LC_ALL_SEPARATOR;
2899 /* name=value output is always used in internal format, and when
2900 * positional isn't available on the platform. */
2901 total_len = lc_all_boiler_plate_length;
2905 /* The total length then is just the sum of the above boiler-plate plus the
2906 * total strlen()s of the locale name of each individual category. */
2907 for_all_individual_category_indexes(i) {
2908 const char * entry = ENTRY(i, locales_list, format);
2910 total_len += strlen(entry);
2911 if (! disparate && strNE(entry, locales_list[0])) {
2916 bool free_if_void_return = false;
2917 const char * retval;
2919 /* If all categories have the same locale, we already know the answer */
2921 if (returning == WANT_PL_setlocale_buf) {
2922 save_to_buffer(locales_list[0],
2924 &PL_setlocale_bufsize);
2925 retval = PL_setlocale_buf;
2929 retval = locales_list[0];
2931 /* If a temporary is wanted for the return, and we had to create
2932 * the input list ourselves, we created it into such a temporary,
2933 * so no further work is needed; but otherwise, make a mortal copy
2934 * of this passed-in list element */
2935 if (returning == WANT_TEMP_PV && ! input_list_was_NULL) {
2936 retval = savepv(retval);
2940 /* In all cases here, there's nothing we create that needs to be
2941 * freed, so leave 'free_if_void_return' set to the default
2945 else { /* Here, not all categories have the same locale */
2949 /* If returning to PL_setlocale_buf, set up to write directly to it,
2950 * being sure it is resized to be large enough */
2951 if (returning == WANT_PL_setlocale_buf) {
2952 set_save_buffer_min_size(total_len,
2954 &PL_setlocale_bufsize);
2955 constructed = PL_setlocale_buf;
2957 else { /* Otherwise we need new memory to hold the calculated value. */
2959 Newx(constructed, total_len, char);
2961 /* If returning the new memory, it must be set up to be freed
2962 * later; otherwise at the end of this function */
2963 if (returning == WANT_TEMP_PV) {
2964 SAVEFREEPV(constructed);
2967 free_if_void_return = true;
2971 constructed[0] = '\0';
2973 /* Loop through all the categories */
2974 for_all_individual_category_indexes(j) {
2976 /* Add a separator, except before the first one */
2978 my_strlcat(constructed, separator, total_len);
2985 # ifndef PERL_LC_ALL_USES_NAME_VALUE_PAIRS
2987 if (UNLIKELY(format != INTERNAL_FORMAT)) {
2989 /* In positional notation 'j' means the position, and we have
2990 * to convert to the index 'i' */
2991 i = map_LC_ALL_position_to_index[j];
2993 entry = ENTRY(i, locales_list, format);
2994 needed_len = my_strlcat(constructed, entry, total_len);
3000 /* Below, we are to use name=value notation, either because
3001 * that's what the platform uses, or because this is the
3002 * internal format, which uses that notation regardless of the
3005 entry = ENTRY(i, locales_list, format);
3007 /* "name=locale;" */
3008 my_strlcat(constructed, category_names[i], total_len);
3009 my_strlcat(constructed, "=", total_len);
3010 needed_len = my_strlcat(constructed, entry, total_len);
3013 if (LIKELY(needed_len <= total_len)) {
3017 /* If would have overflowed, panic */
3018 locale_panic_via_(Perl_form(aTHX_
3019 "Internal length calculation wrong.\n"
3020 "\"%s\" was not entirely added to"
3021 " \"%.*s\"; needed=%zu, had=%zu",
3022 entry, (int) total_len,
3024 needed_len, total_len),
3027 } /* End of loop through the categories */
3029 retval = constructed;
3030 } /* End of the categories' locales are displarate */
3032 # if defined(USE_PL_CURLOCALES) && defined(LC_ALL)
3034 if (format == INTERNAL_FORMAT) {
3036 /* PL_curlocales[LC_ALL_INDEX_] is updated as a side-effect of this
3037 * function for internal format. */
3038 Safefree(PL_curlocales[LC_ALL_INDEX_]);
3039 PL_curlocales[LC_ALL_INDEX_] = savepv(retval);
3044 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3045 "calculate_LC_ALL_string calculated '%s'\n",
3048 if (returning == WANT_VOID) {
3049 if (free_if_void_return) {
3059 # if defined(WIN32) || ( defined(USE_POSIX_2008_LOCALE) \
3060 && ! defined(USE_QUERYLOCALE))
3063 S_find_locale_from_environment(pTHX_ const locale_category_index index)
3065 /* NB: This function may actually change the locale on Windows. It
3066 * currently is designed to be called only from setting the locale on
3067 * Windows, and POSIX 2008
3069 * This function returns the locale specified by the program's environment
3070 * for the category specified by our internal index number 'index'. It
3071 * therefore simulates:
3072 * setlocale(cat, "")
3073 * but, except for some cases in Windows, doesn't actually change the
3074 * locale; merely returns it.
3076 * The return need not be freed by the caller. This
3077 * promise relies on PerlEnv_getenv() returning a mortalized copy to us.
3079 * The simulation is needed only on certain platforms; otherwise, libc is
3080 * called with "" to get the actual value(s). The simulation is needed
3083 * 1) On Windows systems, the concept of the POSIX ordering of
3084 * environment variables is missing. To increase portability of
3085 * programs across platforms, the POSIX ordering is emulated on
3088 * 2) On POSIX 2008 systems without querylocale(), it is problematic
3089 * getting the results of the POSIX 2008 equivalent of
3091 * setlocale(category, "")
3093 * To ensure that we know exactly what those values are, we do the
3094 * setting ourselves, using the documented algorithm specified by the
3095 * POSIX standard (assuming the platform follows the Standard) rather
3096 * than use "" as the locale. This will lead to results that differ
3097 * from native behavior if the native behavior differs from the
3098 * Standard's documented value, but khw believes it is better to know
3099 * what's going on, even if different from native, than to just guess.
3101 * glibc systems differ from this standard in having a LANGUAGE
3102 * environment variable used for just LC_MESSAGES. This function does
3105 * Another option for the POSIX 2008 case would be, in a critical
3106 * section, to save the global locale's current value, and do a
3107 * straight setlocale(LC_ALL, ""). That would return our desired
3108 * values, destroying the global locale's, which we would then
3109 * restore. But that could cause races with any other thread that is
3110 * using the global locale and isn't using the mutex. And, the only
3111 * reason someone would have done that is because they are calling a
3112 * library function, like in gtk, that calls setlocale(), and which
3113 * can't be changed to use the mutex. That wouldn't be a problem if
3114 * this were to be done before any threads had switched, say during
3115 * perl construction time. But this code would still be needed for
3118 * The Windows and POSIX 2008 differ in that the ultimate fallback is "C"
3119 * in POSIX, and is the system default locale in Windows. To get that
3120 * system default value, we actually have to call setlocale() on Windows.
3123 const char * const lc_all = PerlEnv_getenv("LC_ALL");
3124 const char * locale_names[LC_ALL_INDEX_] = { NULL };
3126 /* Use any "LC_ALL" environment variable, as it overrides everything else.
3128 if (lc_all && strNE(lc_all, "")) {
3132 /* Here, no usable LC_ALL environment variable. We have to handle each
3133 * category separately. If all categories are desired, we loop through
3134 * them all. If only an individual category is desired, to avoid
3135 * duplicating logic, we use the same loop, but set up the limits so it is
3136 * only executed once, for that particular category. */
3137 locale_category_index lower, upper, offset;
3138 if (index == LC_ALL_INDEX_) {
3139 lower = (locale_category_index) 0;
3140 upper = (locale_category_index) ((int) LC_ALL_INDEX_ - 1);
3141 offset = (locale_category_index) 0;
3147 /* 'offset' is used so that the result of the single loop iteration is
3148 * stored into output[0] */
3152 /* When no LC_ALL environment variable, LANG is used as a default, but
3153 * overridden for individual categories that have corresponding environment
3154 * variables. If no LANG exists, the default is "C" on POSIX 2008, or the
3155 * system default for the category on Windows. */
3156 const char * env_lang = NULL;
3158 /* For each desired category, use any corresponding environment variable;
3159 * or the default if none such exists. */
3160 bool is_disparate = false; /* Assume is uniform until proven otherwise */
3161 for (unsigned i = lower; i <= upper; i++) {
3162 const char * const env_override = PerlEnv_getenv(category_names[i]);
3163 unsigned int j = i - offset;
3165 if (env_override && strNE(env_override, "")) {
3166 locale_names[j] = env_override;
3168 else { /* Here, no corresponding environment variable, see if LANG
3169 exists and is usable. Done this way to avoid fetching LANG
3170 unless it is actually needed */
3171 if (env_lang == NULL) {
3172 env_lang = PerlEnv_getenv("LANG");
3174 /* If not usable, set it to a non-NULL illegal value so won't
3175 * try to use it below */
3176 if (env_lang == NULL || strEQ(env_lang, "")) {
3177 env_lang = (const char *) 1;
3181 /* If a usable LANG exists, use it. */
3182 if (env_lang != NULL && env_lang != (const char *) 1) {
3183 locale_names[j] = env_lang;
3188 /* If no LANG, use the system default on Windows. */
3189 locale_names[j] = wrap_wsetlocale(categories[i], ".ACP");
3190 if (locale_names[j]) {
3191 SAVEFREEPV(locale_names[j]);
3195 { /* If nothing was found or worked, use C */
3196 locale_names[j] = "C";
3201 if (j > 0 && ! is_disparate && strNE(locale_names[0], locale_names[j]))
3203 is_disparate = true;
3206 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3207 "find_locale_from_environment i=%u, j=%u, name=%s,"
3208 " locale=%s, locale of 0th category=%s, disparate=%d\n",
3209 i, j, category_names[i],
3210 locale_names[j], locale_names[0], is_disparate));
3213 if (! is_disparate) {
3214 return locale_names[0];
3217 return calculate_LC_ALL_string(locale_names, INTERNAL_FORMAT,
3223 # if defined(DEBUGGING) || defined(USE_PERL_SWITCH_LOCALE_CONTEXT)
3226 S_get_LC_ALL_display(pTHX)
3228 return calculate_LC_ALL_string(NULL, INTERNAL_FORMAT,
3236 S_setlocale_failure_panic_via_i(pTHX_
3237 const locale_category_index cat_index,
3238 const char * current,
3239 const char * failed,
3240 const line_t proxy_caller_line,
3241 const line_t immediate_caller_line,
3242 const char * const higher_caller_file,
3243 const line_t higher_caller_line)
3245 PERL_ARGS_ASSERT_SETLOCALE_FAILURE_PANIC_VIA_I;
3247 /* Called to panic when a setlocale form unexpectedly failed for the
3248 * category determined by 'cat_index', and the locale that was in effect
3249 * (and likely still is) is 'current'. 'current' may be NULL, which causes
3250 * this function to query what it is.
3252 * The extra caller information is used for when a function acts as a
3253 * stand-in for another function, which a typical reader would more likely
3254 * think would be the caller
3256 * If a line number is 0, its stack (sort-of) frame is omitted; same if
3257 * it's the same line number as the next higher caller. */
3259 const int cat = categories[cat_index];
3260 const char * name = category_names[cat_index];
3264 if (current == NULL) {
3265 current = querylocale_i(cat_index);
3268 const char * proxy_text = "";
3269 if (proxy_caller_line != 0 && proxy_caller_line != immediate_caller_line)
3271 proxy_text = Perl_form(aTHX_ "\nCalled via %s: %" LINE_Tf,
3272 __FILE__, proxy_caller_line);
3274 if ( strNE(__FILE__, higher_caller_file)
3275 || ( immediate_caller_line != 0
3276 && immediate_caller_line != higher_caller_line))
3278 proxy_text = Perl_form(aTHX_ "%s\nCalled via %s: %" LINE_Tf,
3279 proxy_text, __FILE__,
3280 immediate_caller_line);
3283 /* 'false' in the get_displayable_string() calls makes it not think the
3284 * locale is UTF-8, so just dumps bytes. Actually figuring it out can be
3285 * too complicated for a panic situation. */
3286 const char * msg = Perl_form(aTHX_
3287 "Can't change locale for %s (%d) from '%s' to '%s'"
3290 get_displayable_string(current,
3291 current + strlen(current),
3293 get_displayable_string(failed,
3294 failed + strlen(failed),
3299 Perl_locale_panic(msg, __LINE__, higher_caller_file, higher_caller_line);
3300 NOT_REACHED; /* NOTREACHED */
3303 /* Any of these will allow us to find the RADIX */
3304 # if defined(USE_LOCALE_NUMERIC) && ( defined(HAS_SOME_LANGINFO) \
3305 || defined(HAS_LOCALECONV) \
3306 || defined(HAS_SNPRINTF))
3307 # define CAN_CALCULATE_RADIX
3309 # ifdef USE_LOCALE_NUMERIC
3312 S_new_numeric(pTHX_ const char *newnum, bool force)
3314 PERL_ARGS_ASSERT_NEW_NUMERIC;
3316 /* Called after each libc setlocale() or uselocale() call affecting
3317 * LC_NUMERIC, to tell core Perl this and that 'newnum' is the name of the
3318 * new locale, and we are switched into it. It installs this locale as the
3319 * current underlying default, and then switches to the C locale, if
3320 * necessary, so that the code that has traditionally expected the radix
3321 * character to be a dot may continue to do so.
3323 * The default locale and the C locale can be toggled between by use of the
3324 * set_numeric_underlying() and set_numeric_standard() functions, which
3325 * should probably not be called directly, but only via macros like
3326 * SET_NUMERIC_STANDARD() in perl.h.
3328 * The toggling is necessary mainly so that a non-dot radix decimal point
3329 * character can be input and output, while allowing internal calculations
3332 * This sets several interpreter-level variables:
3333 * PL_numeric_name The underlying locale's name: a copy of 'newnum'
3334 * PL_numeric_underlying A boolean indicating if the toggled state is
3335 * such that the current locale is the program's
3337 * PL_numeric_standard An int indicating if the toggled state is such
3338 * that the current locale is the C locale or
3339 * indistinguishable from the C locale. If non-zero, it
3340 * is in C; if > 1, it means it may not be toggled away
3342 * PL_numeric_underlying_is_standard A bool kept by this function
3343 * indicating that the underlying locale and the standard
3344 * C locale are indistinguishable for the purposes of
3345 * LC_NUMERIC. This happens when both of the above two
3346 * variables are true at the same time. (Toggling is a
3347 * no-op under these circumstances.) This variable is
3348 * used to avoid having to recalculate.
3349 * PL_numeric_radix_sv Contains the string that code should use for the
3350 * decimal point. It is set to either a dot or the
3351 * program's underlying locale's radix character string,
3352 * depending on the situation.
3353 * PL_underlying_radix_sv Contains the program's underlying locale's
3354 * radix character string. This is copied into
3355 * PL_numeric_radix_sv when the situation warrants. It
3356 * exists to avoid having to recalculate it when toggling.
3359 DEBUG_L( PerlIO_printf(Perl_debug_log,
3360 "Called new_numeric with %s, PL_numeric_name=%s\n",
3361 newnum, PL_numeric_name));
3363 /* If not forcing this procedure, and there isn't actually a change from
3364 * our records, do nothing. (Our records can be wrong when sync'ing to the
3365 * locale set up by an external library, hence the 'force' parameter) */
3366 if (! force && strEQ(PL_numeric_name, newnum)) {
3370 Safefree(PL_numeric_name);
3371 PL_numeric_name = savepv(newnum);
3373 /* Handle the trivial case. Since this is called at process
3374 * initialization, be aware that this bit can't rely on much being
3376 if (isNAME_C_OR_POSIX(PL_numeric_name)) {
3377 PL_numeric_standard = TRUE;
3378 PL_numeric_underlying_is_standard = TRUE;
3379 PL_numeric_underlying = TRUE;
3380 sv_setpv(PL_numeric_radix_sv, C_decimal_point);
3381 SvUTF8_off(PL_numeric_radix_sv);
3382 sv_setpv(PL_underlying_radix_sv, C_decimal_point);
3383 SvUTF8_off(PL_underlying_radix_sv);
3387 /* We are in the underlying locale until changed at the end of this
3389 PL_numeric_underlying = TRUE;
3391 char * radix = NULL;
3392 utf8ness_t utf8ness = UTF8NESS_IMMATERIAL;
3394 /* Find and save this locale's radix character. */
3395 my_langinfo_c(RADIXCHAR, LC_NUMERIC, PL_numeric_name,
3396 &radix, NULL, &utf8ness);
3397 sv_setpv(PL_underlying_radix_sv, radix);
3399 if (utf8ness == UTF8NESS_YES) {
3400 SvUTF8_on(PL_underlying_radix_sv);
3403 SvUTF8_off(PL_underlying_radix_sv);
3406 DEBUG_L(PerlIO_printf(Perl_debug_log,
3407 "Locale radix is '%s', ?UTF-8=%d\n",
3408 SvPVX(PL_underlying_radix_sv),
3409 cBOOL(SvUTF8(PL_underlying_radix_sv))));
3411 /* This locale is indistinguishable from C (for numeric purposes) if both
3412 * the radix character and the thousands separator are the same as C's.
3413 * Start with the radix. */
3414 PL_numeric_underlying_is_standard = strEQ(C_decimal_point, radix);
3417 # ifndef TS_W32_BROKEN_LOCALECONV
3419 /* If the radix isn't the same as C's, we know it is distinguishable from
3420 * C; otherwise check the thousands separator too. Only if both are the
3421 * same as C's is the locale indistinguishable from C.
3423 * But on earlier Windows versions, there is a potential race. This code
3424 * knows that localeconv() (elsewhere in this file) will be used to extract
3425 * the needed value, and localeconv() was buggy for quite a while, and that
3426 * code in this file hence uses a workaround. And that workaround may have
3427 * an (unlikely) race. Gathering the radix uses a different workaround on
3428 * Windows that doesn't involve a race. It might be possible to do the
3429 * same for this (patches welcome).
3431 * Until then khw doesn't think it's worth even the small risk of a race to
3432 * get this value, which doesn't appear to be used in any of the Microsoft
3433 * library routines anyway. */
3435 char * scratch_buffer = NULL;
3436 if (PL_numeric_underlying_is_standard) {
3437 PL_numeric_underlying_is_standard = strEQ(C_thousands_sep,
3438 my_langinfo_c(THOUSEP, LC_NUMERIC,
3443 Safefree(scratch_buffer);
3447 PL_numeric_standard = PL_numeric_underlying_is_standard;
3449 /* Keep LC_NUMERIC so that it has the C locale radix and thousands
3450 * separator. This is for XS modules, so they don't have to worry about
3451 * the radix being a non-dot. (Core operations that need the underlying
3452 * locale change to it temporarily). */
3453 if (! PL_numeric_standard) {
3454 set_numeric_standard(__FILE__, __LINE__);
3461 Perl_set_numeric_standard(pTHX_ const char * const file, const line_t line)
3463 PERL_ARGS_ASSERT_SET_NUMERIC_STANDARD;
3464 PERL_UNUSED_ARG(file); /* Some Configurations ignore these */
3465 PERL_UNUSED_ARG(line);
3467 # ifdef USE_LOCALE_NUMERIC
3469 /* Unconditionally toggle the LC_NUMERIC locale to the C locale
3471 * Most code should use the macro SET_NUMERIC_STANDARD() in perl.h
3472 * instead of calling this directly. The macro avoids calling this routine
3473 * if toggling isn't necessary according to our records (which could be
3474 * wrong if some XS code has changed the locale behind our back) */
3476 DEBUG_L(PerlIO_printf(Perl_debug_log, "Setting LC_NUMERIC locale to"
3477 " standard C; called from %s: %"
3478 LINE_Tf "\n", file, line));
3480 void_setlocale_c_with_caller(LC_NUMERIC, "C", file, line);
3481 PL_numeric_standard = TRUE;
3482 sv_setpv(PL_numeric_radix_sv, C_decimal_point);
3483 SvUTF8_off(PL_numeric_radix_sv);
3485 PL_numeric_underlying = PL_numeric_underlying_is_standard;
3487 # endif /* USE_LOCALE_NUMERIC */
3492 Perl_set_numeric_underlying(pTHX_ const char * const file, const line_t line)
3494 PERL_ARGS_ASSERT_SET_NUMERIC_UNDERLYING;
3495 PERL_UNUSED_ARG(file); /* Some Configurations ignore these */
3496 PERL_UNUSED_ARG(line);
3498 # ifdef USE_LOCALE_NUMERIC
3500 /* Unconditionally toggle the LC_NUMERIC locale to the current underlying
3503 * Most code should use the macro SET_NUMERIC_UNDERLYING() in perl.h
3504 * instead of calling this directly. The macro avoids calling this routine
3505 * if toggling isn't necessary according to our records (which could be
3506 * wrong if some XS code has changed the locale behind our back) */
3508 DEBUG_L(PerlIO_printf(Perl_debug_log, "Setting LC_NUMERIC locale to %s;"
3509 " called from %s: %" LINE_Tf "\n",
3510 PL_numeric_name, file, line));
3511 /* Maybe not in init? assert(PL_locale_mutex_depth > 0);*/
3513 void_setlocale_c_with_caller(LC_NUMERIC, PL_numeric_name, file, line);
3514 PL_numeric_underlying = TRUE;
3515 sv_setsv_nomg(PL_numeric_radix_sv, PL_underlying_radix_sv);
3517 PL_numeric_standard = PL_numeric_underlying_is_standard;
3519 # endif /* USE_LOCALE_NUMERIC */
3523 # ifdef USE_LOCALE_CTYPE
3526 S_new_ctype(pTHX_ const char *newctype, bool force)
3528 PERL_ARGS_ASSERT_NEW_CTYPE;
3529 PERL_UNUSED_ARG(force);
3531 /* Called after each libc setlocale() call affecting LC_CTYPE, to tell
3532 * core Perl this and that 'newctype' is the name of the new locale.
3534 * This function sets up the folding arrays for all 256 bytes, assuming
3535 * that tofold() is tolc() since fold case is not a concept in POSIX,
3538 DEBUG_L(PerlIO_printf(Perl_debug_log, "Entering new_ctype(%s)\n",
3541 /* No change means no-op */
3542 if (strEQ(PL_ctype_name, newctype)) {
3546 /* We will replace any bad locale warning with
3547 * 1) nothing if the new one is ok; or
3548 * 2) a new warning for the bad new locale */
3549 if (PL_warn_locale) {
3550 SvREFCNT_dec_NN(PL_warn_locale);
3551 PL_warn_locale = NULL;
3555 Safefree(PL_ctype_name);
3558 PL_in_utf8_turkic_locale = FALSE;
3560 /* For the C locale, just use the standard folds, and we know there are no
3561 * glitches possible, so return early. Since this is called at process
3562 * initialization, be aware that this bit can't rely on much being
3564 if (isNAME_C_OR_POSIX(newctype)) {
3565 Copy(PL_fold, PL_fold_locale, 256, U8);
3566 PL_ctype_name = savepv(newctype);
3567 PL_in_utf8_CTYPE_locale = FALSE;
3571 /* The cache being cleared signals the called function to compute a new
3573 PL_in_utf8_CTYPE_locale = is_locale_utf8(newctype);
3575 PL_ctype_name = savepv(newctype);
3576 bool maybe_utf8_turkic = FALSE;
3578 /* Don't check for problems if we are suppressing the warnings */
3579 bool check_for_problems = ckWARN_d(WARN_LOCALE) || UNLIKELY(DEBUG_L_TEST);
3581 if (PL_in_utf8_CTYPE_locale) {
3583 /* A UTF-8 locale gets standard rules. But note that code still has to
3584 * handle this specially because of the three problematic code points
3586 Copy(PL_fold_latin1, PL_fold_locale, 256, U8);
3588 /* UTF-8 locales can have special handling for 'I' and 'i' if they are
3589 * Turkic. Make sure these two are the only anomalies. (We don't
3590 * require towupper and towlower because they aren't in C89.) */
3592 # if defined(HAS_TOWUPPER) && defined (HAS_TOWLOWER)
3594 if (towupper('i') == 0x130 && towlower('I') == 0x131)
3598 if (toU8_UPPER_LC('i') == 'i' && toU8_LOWER_LC('I') == 'I')
3603 /* This is how we determine it really is Turkic */
3604 check_for_problems = TRUE;
3605 maybe_utf8_turkic = TRUE;
3608 else { /* Not a canned locale we know the values for. Compute them */
3612 bool has_non_ascii_fold = FALSE;
3613 bool found_unexpected = FALSE;
3615 /* Under -DLv, see if there are any folds outside the ASCII range.
3616 * This factoid is used below */
3617 if (DEBUG_Lv_TEST) {
3618 for (unsigned i = 128; i < 256; i++) {
3619 int j = LATIN1_TO_NATIVE(i);
3620 if (toU8_LOWER_LC(j) != j || toU8_UPPER_LC(j) != j) {
3621 has_non_ascii_fold = TRUE;
3629 for (unsigned i = 0; i < 256; i++) {
3630 if (isU8_UPPER_LC(i))
3631 PL_fold_locale[i] = (U8) toU8_LOWER_LC(i);
3632 else if (isU8_LOWER_LC(i))
3633 PL_fold_locale[i] = (U8) toU8_UPPER_LC(i);
3635 PL_fold_locale[i] = (U8) i;
3639 /* Most locales these days are supersets of ASCII. When debugging
3640 * with -DLv, it is helpful to know what the exceptions to that are
3642 if (DEBUG_Lv_TEST) {
3643 bool unexpected = FALSE;
3645 if (isUPPER_L1(i)) {
3647 if (PL_fold_locale[i] != toLOWER_A(i)) {
3651 else if (has_non_ascii_fold) {
3652 if (PL_fold_locale[i] != toLOWER_L1(i)) {
3656 else if (PL_fold_locale[i] != i) {
3660 else if ( isLOWER_L1(i)
3661 && i != LATIN_SMALL_LETTER_SHARP_S
3665 if (PL_fold_locale[i] != toUPPER_A(i)) {
3669 else if (has_non_ascii_fold) {
3670 if (PL_fold_locale[i] != toUPPER_LATIN1_MOD(i)) {
3674 else if (PL_fold_locale[i] != i) {
3678 else if (PL_fold_locale[i] != i) {
3683 found_unexpected = TRUE;
3684 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3685 "For %s, fold of %02x is %02x\n",
3686 newctype, i, PL_fold_locale[i]));
3691 if (found_unexpected) {
3692 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3693 "All bytes not mentioned above either fold to"
3694 " themselves or are the expected ASCII or"
3698 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
3699 "No nonstandard folds were found\n"));
3707 /* We only handle single-byte locales (outside of UTF-8 ones); so if this
3708 * locale requires more than one byte, there are going to be BIG problems.
3711 const int mb_cur_max = MB_CUR_MAX;
3713 if (mb_cur_max > 1 && ! PL_in_utf8_CTYPE_locale
3715 /* Some platforms return MB_CUR_MAX > 1 for even the "C" locale.
3716 * Just assume that the implementation for them (plus for POSIX) is
3717 * correct and the > 1 value is spurious. (Since these are
3718 * specially handled to never be considered UTF-8 locales, as long
3719 * as this is the only problem, everything should work fine */
3720 && ! isNAME_C_OR_POSIX(newctype))
3722 DEBUG_L(PerlIO_printf(Perl_debug_log,
3723 "Unsupported, MB_CUR_MAX=%d\n", mb_cur_max));
3725 Perl_ck_warner_d(aTHX_ packWARN(WARN_LOCALE),
3726 "Locale '%s' is unsupported, and may crash the"
3733 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "check_for_problems=%d\n",
3734 check_for_problems));
3736 /* We don't populate the other lists if a UTF-8 locale, but do check that
3737 * everything works as expected, unless checking turned off */
3738 if (check_for_problems) {
3739 /* Assume enough space for every character being bad. 4 spaces each
3740 * for the 94 printable characters that are output like "'x' "; and 5
3741 * spaces each for "'\\' ", "'\t' ", and "'\n' "; plus a terminating
3743 char bad_chars_list[ (94 * 4) + (3 * 5) + 1 ] = { '\0' };
3744 unsigned int bad_count = 0; /* Count of bad characters */
3746 for (unsigned i = 0; i < 256; i++) {
3748 /* If checking for locale problems, see if the native ASCII-range
3749 * printables plus \n and \t are in their expected categories in
3750 * the new locale. If not, this could mean big trouble, upending
3751 * Perl's and most programs' assumptions, like having a
3752 * metacharacter with special meaning become a \w. Fortunately,
3753 * it's very rare to find locales that aren't supersets of ASCII
3754 * nowadays. It isn't a problem for most controls to be changed
3755 * into something else; we check only \n and \t, though perhaps \r
3756 * could be an issue as well. */
3757 if (isGRAPH_A(i) || isBLANK_A(i) || i == '\n') {
3758 bool is_bad = FALSE;
3759 char name[4] = { '\0' };
3761 /* Convert the name into a string */
3766 else if (i == '\n') {
3767 my_strlcpy(name, "\\n", sizeof(name));
3769 else if (i == '\t') {
3770 my_strlcpy(name, "\\t", sizeof(name));
3774 my_strlcpy(name, "' '", sizeof(name));
3777 /* Check each possibe class */
3778 if (UNLIKELY(cBOOL(isU8_ALPHANUMERIC_LC(i)) !=
3779 cBOOL(isALPHANUMERIC_A(i))))
3782 DEBUG_L(PerlIO_printf(Perl_debug_log,
3783 "isalnum('%s') unexpectedly is %x\n",
3784 name, cBOOL(isU8_ALPHANUMERIC_LC(i))));
3786 if (UNLIKELY(cBOOL(isU8_ALPHA_LC(i)) != cBOOL(isALPHA_A(i)))) {
3788 DEBUG_L(PerlIO_printf(Perl_debug_log,
3789 "isalpha('%s') unexpectedly is %x\n",
3790 name, cBOOL(isU8_ALPHA_LC(i))));
3792 if (UNLIKELY(cBOOL(isU8_DIGIT_LC(i)) != cBOOL(isDIGIT_A(i)))) {
3794 DEBUG_L(PerlIO_printf(Perl_debug_log,
3795 "isdigit('%s') unexpectedly is %x\n",
3796 name, cBOOL(isU8_DIGIT_LC(i))));
3798 if (UNLIKELY(cBOOL(isU8_GRAPH_LC(i)) != cBOOL(isGRAPH_A(i)))) {
3800 DEBUG_L(PerlIO_printf(Perl_debug_log,
3801 "isgraph('%s') unexpectedly is %x\n",
3802 name, cBOOL(isU8_GRAPH_LC(i))));
3804 if (UNLIKELY(cBOOL(isU8_LOWER_LC(i)) != cBOOL(isLOWER_A(i)))) {
3806 DEBUG_L(PerlIO_printf(Perl_debug_log,
3807 "islower('%s') unexpectedly is %x\n",
3808 name, cBOOL(isU8_LOWER_LC(i))));
3810 if (UNLIKELY(cBOOL(isU8_PRINT_LC(i)) != cBOOL(isPRINT_A(i)))) {
3812 DEBUG_L(PerlIO_printf(Perl_debug_log,
3813 "isprint('%s') unexpectedly is %x\n",
3814 name, cBOOL(isU8_PRINT_LC(i))));
3816 if (UNLIKELY(cBOOL(isU8_PUNCT_LC(i)) != cBOOL(isPUNCT_A(i)))) {
3818 DEBUG_L(PerlIO_printf(Perl_debug_log,
3819 "ispunct('%s') unexpectedly is %x\n",
3820 name, cBOOL(isU8_PUNCT_LC(i))));
3822 if (UNLIKELY(cBOOL(isU8_SPACE_LC(i)) != cBOOL(isSPACE_A(i)))) {
3824 DEBUG_L(PerlIO_printf(Perl_debug_log,
3825 "isspace('%s') unexpectedly is %x\n",
3826 name, cBOOL(isU8_SPACE_LC(i))));
3828 if (UNLIKELY(cBOOL(isU8_UPPER_LC(i)) != cBOOL(isUPPER_A(i)))) {
3830 DEBUG_L(PerlIO_printf(Perl_debug_log,
3831 "isupper('%s') unexpectedly is %x\n",
3832 name, cBOOL(isU8_UPPER_LC(i))));
3834 if (UNLIKELY(cBOOL(isU8_XDIGIT_LC(i))!= cBOOL(isXDIGIT_A(i)))) {
3836 DEBUG_L(PerlIO_printf(Perl_debug_log,
3837 "isxdigit('%s') unexpectedly is %x\n",
3838 name, cBOOL(isU8_XDIGIT_LC(i))));
3840 if (UNLIKELY(toU8_LOWER_LC(i) != (int) toLOWER_A(i))) {
3842 DEBUG_L(PerlIO_printf(Perl_debug_log,
3843 "tolower('%s')=0x%x instead of the expected 0x%x\n",
3844 name, toU8_LOWER_LC(i), (int) toLOWER_A(i)));
3846 if (UNLIKELY(toU8_UPPER_LC(i) != (int) toUPPER_A(i))) {
3848 DEBUG_L(PerlIO_printf(Perl_debug_log,
3849 "toupper('%s')=0x%x instead of the expected 0x%x\n",
3850 name, toU8_UPPER_LC(i), (int) toUPPER_A(i)));
3852 if (UNLIKELY((i == '\n' && ! isCNTRL_LC(i)))) {
3854 DEBUG_L(PerlIO_printf(Perl_debug_log,
3855 "'\\n' (=%02X) is not a control\n", (int) i));
3858 /* Add to the list; Separate multiple entries with a blank */
3861 my_strlcat(bad_chars_list, " ", sizeof(bad_chars_list));
3863 my_strlcat(bad_chars_list, name, sizeof(bad_chars_list));
3869 if (bad_count == 2 && maybe_utf8_turkic) {
3871 *bad_chars_list = '\0';
3873 /* The casts are because otherwise some compilers warn:
3874 gcc.gnu.org/bugzilla/show_bug.cgi?id=99950
3875 gcc.gnu.org/bugzilla/show_bug.cgi?id=94182
3877 PL_fold_locale[ (U8) 'I' ] = 'I';
3878 PL_fold_locale[ (U8) 'i' ] = 'i';
3879 PL_in_utf8_turkic_locale = TRUE;
3880 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s is turkic\n", newctype));
3883 /* If we found problems and we want them output, do so */
3884 if ( (UNLIKELY(bad_count))
3885 && (LIKELY(ckWARN_d(WARN_LOCALE)) || UNLIKELY(DEBUG_L_TEST)))
3887 /* WARNING. If you change the wording of these; be sure to update
3888 * t/loc_tools.pl correspondingly */
3890 if (PL_in_utf8_CTYPE_locale) {
3891 PL_warn_locale = Perl_newSVpvf(aTHX_
3892 "Locale '%s' contains (at least) the following characters"
3893 " which have\nunexpected meanings: %s\nThe Perl program"
3894 " will use the expected meanings",
3895 newctype, bad_chars_list);
3900 "\nThe following characters (and maybe"
3901 " others) may not have the same meaning as"
3902 " the Perl program expects: %s\n",
3907 # if defined(HAS_SOME_LANGINFO) || defined(WIN32)
3909 char * scratch_buffer = NULL;
3910 Perl_sv_catpvf(aTHX_ PL_warn_locale, "; codeset=%s",
3911 my_langinfo_c(CODESET, LC_CTYPE,
3913 &scratch_buffer, NULL,
3915 Safefree(scratch_buffer);
3919 Perl_sv_catpvf(aTHX_ PL_warn_locale, "\n");
3921 /* If we are actually in the scope of the locale or are debugging,
3922 * output the message now. If not in that scope, we save the
3923 * message to be output at the first operation using this locale,
3924 * if that actually happens. Most programs don't use locales, so
3925 * they are immune to bad ones. */
3926 if (IN_LC(LC_CTYPE) || UNLIKELY(DEBUG_L_TEST)) {
3928 /* The '0' below suppresses a bogus gcc compiler warning */
3929 Perl_warner(aTHX_ packWARN(WARN_LOCALE), SvPVX(PL_warn_locale),
3931 if (IN_LC(LC_CTYPE)) {
3932 SvREFCNT_dec_NN(PL_warn_locale);
3933 PL_warn_locale = NULL;
3941 Perl_warn_problematic_locale()
3945 /* Core-only function that outputs the message in PL_warn_locale,
3946 * and then NULLS it. Should be called only through the macro
3947 * CHECK_AND_WARN_PROBLEMATIC_LOCALE_ */
3949 if (PL_warn_locale) {
3950 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
3951 SvPVX(PL_warn_locale),
3952 0 /* dummy to avoid compiler warning */ );
3953 SvREFCNT_dec_NN(PL_warn_locale);
3954 PL_warn_locale = NULL;
3958 # endif /* USE_LOCALE_CTYPE */
3964 S_new_LC_ALL(pTHX_ const char *lc_all, bool force)
3968 S_new_LC_ALL(pTHX_ const char ** individ_locales, bool force)
3973 PERL_ARGS_ASSERT_NEW_LC_ALL;
3975 /* new_LC_ALL() updates all the things we care about. Note that this is
3976 * called just after a change, so uses the actual underlying locale just
3977 * set, and not the nominal one (should they differ, as they may in
3982 const char * individ_locales[LC_ALL_INDEX_] = { NULL };
3984 switch (parse_LC_ALL_string(lc_all,
3986 override_if_ignored, /* Override any ignored
3988 true, /* Always fill array */
3989 true, /* Panic if fails, as to get here it
3990 earlier had to have succeeded */
3995 case only_element_0:
3996 locale_panic_("Unexpected return from parse_LC_ALL_string");
4004 for_all_individual_category_indexes(i) {
4005 if (update_functions[i]) {
4006 const char * this_locale = individ_locales[i];
4007 update_functions[i](aTHX_ this_locale, force);
4012 Safefree(individ_locales[i]);
4019 # ifdef USE_LOCALE_COLLATE
4022 S_new_collate(pTHX_ const char *newcoll, bool force)
4024 PERL_ARGS_ASSERT_NEW_COLLATE;
4025 PERL_UNUSED_ARG(force);
4027 /* Called after each libc setlocale() call affecting LC_COLLATE, to tell
4028 * core Perl this and that 'newcoll' is the name of the new locale.
4030 * The design of locale collation is that every locale change is given an
4031 * index 'PL_collation_ix'. The first time a string participates in an
4032 * operation that requires collation while locale collation is active, it
4033 * is given PERL_MAGIC_collxfrm magic (via sv_collxfrm_flags()). That
4034 * magic includes the collation index, and the transformation of the string
4035 * by strxfrm(), q.v. That transformation is used when doing comparisons,
4036 * instead of the string itself. If a string changes, the magic is
4037 * cleared. The next time the locale changes, the index is incremented,
4038 * and so we know during a comparison that the transformation is not
4039 * necessarily still valid, and so is recomputed. Note that if the locale
4040 * changes enough times, the index could wrap, and it is possible that a
4041 * transformation would improperly be considered valid, leading to an
4042 * unlikely bug. The value is declared to the widest possible type on this
4045 /* Return if the locale isn't changing */
4046 if (strEQ(PL_collation_name, newcoll)) {
4050 Safefree(PL_collation_name);
4051 PL_collation_name = savepv(newcoll);
4054 /* Set the new one up if trivial. Since this is called at process
4055 * initialization, be aware that this bit can't rely on much being
4057 PL_collation_standard = isNAME_C_OR_POSIX(newcoll);
4058 if (PL_collation_standard) {
4059 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
4060 "Setting PL_collation name='%s'\n",
4061 PL_collation_name));
4062 PL_collxfrm_base = 0;
4063 PL_collxfrm_mult = 2;
4064 PL_in_utf8_COLLATE_locale = FALSE;
4065 PL_strxfrm_NUL_replacement = '\0';
4066 PL_strxfrm_max_cp = 0;
4070 /* Flag that the remainder of the set up is being deferred until first
4072 PL_collxfrm_mult = 0;
4073 PL_collxfrm_base = 0;
4077 # endif /* USE_LOCALE_COLLATE */
4082 S_Win_byte_string_to_wstring(const UINT code_page, const char * byte_string)
4084 /* Caller must arrange to free the returned string */
4086 int req_size = MultiByteToWideChar(code_page, 0, byte_string, -1, NULL, 0);
4093 Newx(wstring, req_size, wchar_t);
4095 if (! MultiByteToWideChar(code_page, 0, byte_string, -1, wstring, req_size))
4105 # define Win_utf8_string_to_wstring(s) \
4106 Win_byte_string_to_wstring(CP_UTF8, (s))
4109 S_Win_wstring_to_byte_string(const UINT code_page, const wchar_t * wstring)
4111 /* Caller must arrange to free the returned string */
4114 WideCharToMultiByte(code_page, 0, wstring, -1, NULL, 0, NULL, NULL);
4117 Newx(byte_string, req_size, char);
4119 if (! WideCharToMultiByte(code_page, 0, wstring, -1, byte_string,
4120 req_size, NULL, NULL))
4122 Safefree(byte_string);
4130 # define Win_wstring_to_utf8_string(ws) \
4131 Win_wstring_to_byte_string(CP_UTF8, (ws))
4134 S_wrap_wsetlocale(pTHX_ const int category, const char *locale)
4136 PERL_ARGS_ASSERT_WRAP_WSETLOCALE;
4138 /* Calls _wsetlocale(), converting the parameters/return to/from
4139 * Perl-expected forms as if plain setlocale() were being called instead.
4141 * Caller must arrange for the returned PV to be freed.
4144 const wchar_t * wlocale = NULL;
4147 wlocale = Win_utf8_string_to_wstring(locale);
4154 const wchar_t * wresult = _wsetlocale(category, wlocale);
4162 const char * result = Win_wstring_to_utf8_string(wresult);
4170 S_win32_setlocale(pTHX_ int category, const char* locale)
4172 /* This, for Windows, emulates POSIX setlocale() behavior. There is no
4173 * difference between the two unless the input locale is "", which normally
4174 * means on Windows to get the machine default, which is set via the
4175 * computer's "Regional and Language Options" (or its current equivalent).
4176 * In POSIX, it instead means to find the locale from the user's
4177 * environment. This routine changes the Windows behavior to try the POSIX
4178 * behavior first. Further details are in the called function
4179 * find_locale_from_environment().
4182 if (locale != NULL && strEQ(locale, "")) {
4183 /* Note this function may change the locale, but that's ok because we
4184 * are about to change it anyway */
4185 locale = find_locale_from_environment(get_category_index(category));
4186 if (locale == NULL) {
4192 const char * result = wrap_wsetlocale(category, locale);
4193 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s\n",
4194 setlocale_debug_string_r(category, locale, result)));
4201 save_to_buffer(result, &PL_setlocale_buf, &PL_setlocale_bufsize);
4203 # ifndef USE_PL_CUR_LC_ALL
4209 /* Here, we need to keep track of LC_ALL, so store the new value. but if
4210 * the input locale is NULL, we were just querying, so the original value
4212 if (locale == NULL) {
4217 /* If we set LC_ALL directly above, we already know its new value; but
4218 * if we changed just an individual category, find the new LC_ALL */
4219 if (category != LC_ALL) {
4221 result = wrap_wsetlocale(LC_ALL, NULL);
4224 Safefree(PL_cur_LC_ALL);
4225 PL_cur_LC_ALL = result;
4228 DEBUG_L(PerlIO_printf(Perl_debug_log, "new PL_cur_LC_ALL=%s\n",
4232 return PL_setlocale_buf;
4238 S_native_querylocale_i(pTHX_ const locale_category_index cat_index)
4240 /* Determine the current locale and return it in the form the platform's
4241 * native locale handling understands. This is different only from our
4242 * internal form for the LC_ALL category, as platforms differ in how they
4245 * This is only called from Perl_setlocale(). As such it returns in
4246 * PL_setlocale_buf */
4248 # ifdef USE_LOCALE_NUMERIC
4250 /* We have the LC_NUMERIC name saved, because we are normally switched into
4251 * the C locale (or equivalent) for it. */
4252 if (cat_index == LC_NUMERIC_INDEX_) {
4254 /* We don't have to copy this return value, as it is a per-thread
4255 * variable, and won't change until a future setlocale */
4256 return PL_numeric_name;
4262 if (cat_index != LC_ALL_INDEX_)
4267 /* Here, not LC_ALL, and not LC_NUMERIC: the actual and native values
4270 # ifdef setlocale_i /* Can shortcut if this is defined */
4272 return setlocale_i(cat_index, NULL);
4276 return save_to_buffer(querylocale_i(cat_index),
4277 &PL_setlocale_buf, &PL_setlocale_bufsize);
4282 /* Below, querying LC_ALL */
4285 # ifdef USE_PL_CURLOCALES
4286 # define LC_ALL_ARG PL_curlocales
4288 # define LC_ALL_ARG NULL /* Causes calculate_LC_ALL_string() to find the
4289 locale using a querylocale function */
4292 return calculate_LC_ALL_string(LC_ALL_ARG, EXTERNAL_FORMAT_FOR_QUERY,
4293 WANT_PL_setlocale_buf,
4296 # endif /* has LC_ALL */
4300 #endif /* USE_LOCALE */
4303 =for apidoc Perl_setlocale
4305 This is an (almost) drop-in replacement for the system L<C<setlocale(3)>>,
4306 taking the same parameters, and returning the same information, except that it
4307 returns the correct underlying C<LC_NUMERIC> locale. Regular C<setlocale> will
4308 instead return C<C> if the underlying locale has a non-dot decimal point
4309 character, or a non-empty thousands separator for displaying floating point
4310 numbers. This is because perl keeps that locale category such that it has a
4311 dot and empty separator, changing the locale briefly during the operations
4312 where the underlying one is required. C<Perl_setlocale> knows about this, and
4313 compensates; regular C<setlocale> doesn't.
4315 Another reason it isn't completely a drop-in replacement is that it is
4316 declared to return S<C<const char *>>, whereas the system setlocale omits the
4317 C<const> (presumably because its API was specified long ago, and can't be
4318 updated; it is illegal to change the information C<setlocale> returns; doing
4319 so leads to segfaults.)
4321 Finally, C<Perl_setlocale> works under all circumstances, whereas plain
4322 C<setlocale> can be completely ineffective on some platforms under some
4325 Changing the locale is not a good idea when more than one thread is running,
4326 except on systems where the predefined variable C<${^SAFE_LOCALES}> is
4327 non-zero. This is because on such systems the locale is global to the whole
4328 process and not local to just the thread calling the function. So changing it
4329 in one thread instantaneously changes it in all. On some such systems, the
4330 system C<setlocale()> is ineffective, returning the wrong information, and
4331 failing to actually change the locale. z/OS refuses to try to change the
4332 locale once a second thread is created. C<Perl_setlocale>, should give you
4333 accurate results of what actually happened on these problematic platforms,
4334 returning NULL if the system forbade the locale change.
4336 The return points to a per-thread static buffer, which is overwritten the next
4337 time C<Perl_setlocale> is called from the same thread.
4344 Perl_setlocale(const int category, const char * locale)
4346 /* This wraps POSIX::setlocale() */
4350 PERL_UNUSED_ARG(category);
4351 PERL_UNUSED_ARG(locale);
4359 DEBUG_L(PerlIO_printf(Perl_debug_log,
4360 "Entering Perl_setlocale(%d, \"%s\")\n",
4363 bool valid_category;
4364 locale_category_index cat_index = get_category_index_helper(category,
4367 if (! valid_category) {
4368 if (ckWARN(WARN_LOCALE)) {
4369 const char * conditional_warn_text;
4370 if (locale == NULL) {
4371 conditional_warn_text = "";
4375 conditional_warn_text = "; can't set it to ";
4378 /* diag_listed_as: Unknown locale category %d; can't set it to %s */
4380 packWARN(WARN_LOCALE),
4381 "Unknown locale category %d%s%s",
4382 category, conditional_warn_text, locale);
4391 /* setlocale_i() gets defined only on Configurations that use setlocale()
4392 * in a simple manner that adequately handles all cases. If this category
4393 * doesn't have any perl complications, just do that. */
4394 if (! update_functions[cat_index]) {
4395 return setlocale_i(cat_index, locale);
4400 /* Get current locale */
4401 const char * current_locale = native_querylocale_i(cat_index);
4403 /* A NULL locale means only query what the current one is. */
4404 if (locale == NULL) {
4405 return current_locale;
4408 if (strEQ(current_locale, locale)) {
4409 DEBUG_L(PerlIO_printf(Perl_debug_log,
4410 "Already in requested locale: no action taken\n"));
4411 return current_locale;
4414 /* Here, an actual change is being requested. Do it */
4415 if (! bool_setlocale_i(cat_index, locale)) {
4416 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s\n",
4417 setlocale_debug_string_i(cat_index, locale, "NULL")));
4421 /* At this point, the locale has been changed based on the requested value,
4422 * and the querylocale_i() will return the actual new value that the system
4423 * has for the category. That may not be the same as the input, as libc
4424 * may have returned a synonymous locale name instead of the input one; or,
4425 * if there are locale categories that we are compiled to ignore, any
4426 * attempt to change them away from "C" is overruled */
4427 current_locale = querylocale_i(cat_index);
4429 /* But certain categories need further work. For example we may need to
4430 * calculate new folding or collation rules. And for LC_NUMERIC, we have
4431 * to switch into a locale that has a dot radix. */
4432 if (update_functions[cat_index]) {
4433 update_functions[cat_index](aTHX_ current_locale,
4434 /* No need to force recalculation, as
4435 * aren't coming from a situation
4436 * where Perl hasn't been controlling
4437 * the locale, so has accurate
4442 /* Make sure the result is in a stable buffer for the caller's use, and is
4443 * in the expected format */
4444 current_locale = native_querylocale_i(cat_index);
4446 DEBUG_L(PerlIO_printf(Perl_debug_log, "returning '%s'\n", current_locale));
4448 return current_locale;
4454 #if defined(USE_LOCALE) || defined(HAS_SOME_LANGINFO) || defined(HAS_LOCALECONV)
4457 S_get_locale_string_utf8ness_i(pTHX_ const char * string,
4458 const locale_utf8ness_t known_utf8,
4459 const char * locale,
4460 const locale_category_index cat_index)
4462 PERL_ARGS_ASSERT_GET_LOCALE_STRING_UTF8NESS_I;
4467 PERL_UNUSED_ARG(string);
4468 PERL_UNUSED_ARG(known_utf8);
4469 PERL_UNUSED_ARG(locale);
4470 PERL_UNUSED_ARG(cat_index);
4474 assert(cat_index <= LC_ALL_INDEX_);
4476 /* Return to indicate if 'string' in the locale given by the input
4477 * arguments should be considered UTF-8 or not.
4479 * If the input 'locale' is not NULL, use that for the locale; otherwise
4480 * use the current locale for the category specified by 'cat_index'.
4483 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
4484 "Entering get_locale_string_utf8ness_i; locale=%s,"
4485 " index=%u(%s), string=%s, known_utf8=%d\n",
4486 locale, cat_index, category_names[cat_index],
4488 ? _byte_dump_string((U8 *) string,
4493 if (string == NULL) {
4494 return UTF8NESS_IMMATERIAL;
4497 if (IN_BYTES) { /* respect 'use bytes' */
4501 Size_t len = strlen(string);
4503 /* UTF8ness is immaterial if the representation doesn't vary */
4504 const U8 * first_variant = NULL;
4505 if (is_utf8_invariant_string_loc((U8 *) string, len, &first_variant)) {
4506 return UTF8NESS_IMMATERIAL;
4509 /* Can't be UTF-8 if invalid */
4510 if (! is_utf8_string((U8 *) first_variant,
4511 len - ((char *) first_variant - string)))
4516 /* Here and below, we know the string is legal UTF-8, containing at least
4517 * one character requiring a sequence of two or more bytes. It is quite
4518 * likely to be UTF-8. But it pays to be paranoid and do further checking.
4520 * If we already know the UTF-8ness of the locale, then we immediately know
4521 * what the string is */
4522 if (UNLIKELY(known_utf8 != LOCALE_UTF8NESS_UNKNOWN)) {
4523 if (known_utf8 == LOCALE_IS_UTF8) {
4524 return UTF8NESS_YES;
4531 # ifdef HAS_RELIABLE_UTF8NESS_DETERMINATION
4533 /* Here, we have available the libc functions that can be used to
4534 * accurately determine the UTF8ness of the underlying locale. If it is a
4535 * UTF-8 locale, the string is UTF-8; otherwise it was coincidental that
4536 * the string is legal UTF-8
4538 * However, if the perl is compiled to not pay attention to the category
4539 * being passed in, you might think that that locale is essentially always
4540 * the C locale, so it would make sense to say it isn't UTF-8. But to get
4541 * here, the string has to contain characters unknown in the C locale. And
4542 * in fact, Windows boxes are compiled without LC_MESSAGES, as their
4543 * message catalog isn't really a part of the locale system. But those
4544 * messages really could be UTF-8, and given that the odds are rather small
4545 * of something not being UTF-8 but being syntactically valid UTF-8, khw
4546 * has decided to call such strings as UTF-8. */
4548 if (locale == NULL) {
4549 locale = querylocale_i(cat_index);
4552 if (is_locale_utf8(locale)) {
4553 return UTF8NESS_YES;
4560 /* Here, we have a valid UTF-8 string containing non-ASCII characters, and
4561 * don't have access to functions to check if the locale is UTF-8 or not.
4562 * Assume that it is. khw tried adding a check that the string is entirely
4563 * in a single Unicode script, but discovered the strftime() timezone is
4564 * user-settable through the environment, which may be in a different
4565 * script than the locale-expected value. */
4566 PERL_UNUSED_ARG(locale);
4567 PERL_UNUSED_ARG(cat_index);
4569 return UTF8NESS_YES;
4577 S_is_locale_utf8(pTHX_ const char * locale)
4579 /* Returns TRUE if the locale 'locale' is UTF-8; FALSE otherwise. It uses
4580 * my_langinfo(), which employs various methods to get this information
4581 * if nl_langinfo() isn't available, using heuristics as a last resort, in
4582 * which case, the result will very likely be correct for locales for
4583 * languages that have commonly used non-ASCII characters, but for notably
4584 * English, it comes down to if the locale's name ends in something like
4585 * "UTF-8". It errs on the side of not being a UTF-8 locale.
4587 * Systems conforming to C99 should have the needed libc calls to give us a
4588 * completely reliable result. */
4590 # if ! defined(USE_LOCALE) \
4591 || ! defined(USE_LOCALE_CTYPE) \
4592 || defined(EBCDIC) /* There aren't any real UTF-8 locales at this time */
4594 PERL_UNUSED_ARG(locale);
4600 char * scratch_buffer = NULL;
4601 const char * codeset;
4604 PERL_ARGS_ASSERT_IS_LOCALE_UTF8;
4606 if (strEQ(locale, PL_ctype_name)) {
4607 return PL_in_utf8_CTYPE_locale;
4610 codeset = my_langinfo_c(CODESET, LC_CTYPE, locale,
4611 &scratch_buffer, NULL, NULL);
4612 retval = is_codeset_name_UTF8(codeset);
4614 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
4615 "found codeset=%s, is_utf8=%d\n", codeset, retval));
4617 Safefree(scratch_buffer);
4619 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "is_locale_utf8(%s) returning %d\n",
4631 S_set_save_buffer_min_size(pTHX_ Size_t min_len,
4633 Size_t * buf_cursize)
4635 /* Make sure the buffer pointed to by *buf is at least as large 'min_len';
4636 * *buf_cursize is the size of 'buf' upon entry; it will be updated to the
4637 * new size on exit. 'buf_cursize' being NULL is to be used when this is a
4638 * single use buffer, which will shortly be freed by the caller. */
4640 if (buf_cursize == NULL) {
4641 Newx(*buf, min_len, char);
4643 else if (*buf_cursize == 0) {
4644 Newx(*buf, min_len, char);
4645 *buf_cursize = min_len;
4647 else if (min_len > *buf_cursize) {
4648 Renew(*buf, min_len, char);
4649 *buf_cursize = min_len;
4654 S_save_to_buffer(pTHX_ const char * string, char **buf, Size_t *buf_size)
4656 PERL_ARGS_ASSERT_SAVE_TO_BUFFER;
4658 /* Copy the NUL-terminated 'string' to a buffer whose address before this
4659 * call began at *buf, and whose available length before this call was
4662 * If the length of 'string' is greater than the space available, the
4663 * buffer is grown accordingly, which may mean that it gets relocated.
4664 * *buf and *buf_size will be updated to reflect this.
4666 * Regardless, the function returns a pointer to where 'string' is now
4669 * 'string' may be NULL, which means no action gets taken, and NULL is
4672 * 'buf_size' being NULL is to be used when this is a single use buffer,
4673 * which will shortly be freed by the caller.
4675 * If *buf or 'buf_size' are NULL or *buf_size is 0, the buffer is assumed
4676 * empty, and memory is malloc'd.
4683 /* No-op to copy over oneself */
4684 if (string == *buf) {
4688 Size_t string_size = strlen(string) + 1;
4689 set_save_buffer_min_size(string_size, buf, buf_size);
4693 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
4694 "Copying '%s' to %p\n",
4695 ((is_utf8_string((U8 *) string, 0))
4697 :_byte_dump_string((U8 *) string, strlen(string), 0)),
4700 /* Catch glitches. Usually this is because LC_CTYPE needs to be the same
4701 * locale as whatever is being worked on */
4702 if (UNLIKELY(instr(string, REPLACEMENT_CHARACTER_UTF8))) {
4703 locale_panic_(Perl_form(aTHX_
4704 "Unexpected REPLACEMENT_CHARACTER in '%s'\n%s",
4705 string, get_LC_ALL_display()));
4710 Copy(string, *buf, string_size, char);
4717 Perl_get_win32_message_utf8ness(pTHX_ const char * string)
4719 /* This is because Windows doesn't have LC_MESSAGES. */
4721 # ifdef USE_LOCALE_CTYPE
4723 return get_locale_string_utf8ness_i(string, LOCALE_IS_UTF8,
4724 NULL, LC_CTYPE_INDEX_);
4734 #endif /* USE_LOCALE */
4737 Perl_mbtowc_(pTHX_ const wchar_t * pwc, const char * s, const Size_t len)
4740 #if ! defined(HAS_MBRTOWC) && ! defined(HAS_MBTOWC)
4742 PERL_UNUSED_ARG(pwc);
4744 PERL_UNUSED_ARG(len);
4747 #else /* Below we have some form of mbtowc() */
4748 # if defined(HAS_MBRTOWC) \
4749 && (defined(USE_LOCALE_THREADS) || ! defined(HAS_MBTOWC))
4750 # define USE_MBRTOWC
4757 if (s == NULL) { /* Initialize the shift state to all zeros in
4760 # if defined(USE_MBRTOWC)
4762 memzero(&PL_mbrtowc_ps, sizeof(PL_mbrtowc_ps));
4769 retval = mbtowc(NULL, NULL, 0);
4777 # if defined(USE_MBRTOWC)
4781 retval = (SSize_t) mbrtowc((wchar_t *) pwc, s, len, &PL_mbrtowc_ps);
4786 /* Locking prevents races, but locales can be switched out without locking,
4787 * so this isn't a cure all */
4790 retval = mbtowc((wchar_t *) pwc, s, len);
4802 =for apidoc Perl_localeconv
4804 This is a thread-safe version of the libc L<localeconv(3)>. It is the same as
4805 L<POSIX::localeconv|POSIX/localeconv> (returning a hash of the C<localeconv()>
4806 fields), but directly callable from XS code.
4812 Perl_localeconv(pTHX)
4815 #if ! defined(HAS_LOCALECONV)
4821 return my_localeconv(0);
4827 #if defined(HAS_LOCALECONV)
4830 S_my_localeconv(pTHX_ const int item)
4832 PERL_ARGS_ASSERT_MY_LOCALECONV;
4834 /* This returns a mortalized hash containing all or certain elements
4835 * returned by localeconv(). It is used by Perl_localeconv() and
4836 * POSIX::localeconv() and is thread-safe.
4838 * There are two use cases:
4839 * 1) Called from POSIX::locale_conv(). This returns the lconv structure
4840 * copied to a hash, based on the current underlying locales for
4841 * LC_NUMERIC and LC_MONETARY. An input item==0 signifies this case, or
4842 * on many platforms it is the only use case compiled.
4843 * 2) Certain items that nl_langinfo() provides are also derivable from
4844 * the return of localeconv(). Windows notably doesn't have
4845 * nl_langinfo(), so on that, and actually any platform lacking it,
4846 * my_localeconv() is used also to emulate it for those particular
4847 * items. The code to do this is compiled only on such platforms.
4848 * Rather than going to the expense of creating a full hash when only
4849 * one item is needed, the returned hash has just the desired item in
4852 * To access all the localeconv() struct lconv fields, there is a data
4853 * structure that contains every commonly documented field in it. (Maybe
4854 * some minority platforms have extra fields. Those could be added here
4855 * without harm; they would just be ignored on platforms lacking them.)
4857 * Our structure is compiled to make looping through the fields easier by
4858 * pointing each name to its value's offset within lconv, e.g.,
4859 { "thousands_sep", STRUCT_OFFSET(struct lconv, thousands_sep) }
4861 # define LCONV_ENTRY(name) \
4862 {STRINGIFY(name), STRUCT_OFFSET(struct lconv, name)}
4864 /* These synonyms are just for clarity, and to make it easier in case
4865 * something needs to change in the future */
4866 # define LCONV_NUMERIC_ENTRY(name) LCONV_ENTRY(name)
4867 # define LCONV_MONETARY_ENTRY(name) LCONV_ENTRY(name)
4869 /* There are just a few fields for NUMERIC strings */
4870 const lconv_offset_t lconv_numeric_strings[] = {
4871 # ifndef NO_LOCALECONV_GROUPING
4872 LCONV_NUMERIC_ENTRY(grouping),
4874 LCONV_NUMERIC_ENTRY(thousands_sep),
4875 LCONV_NUMERIC_ENTRY(decimal_point),
4879 /* When used to implement nl_langinfo(), we save time by only populating
4880 * the hash with the field(s) needed. Thus we would need a data structure
4882 * LCONV_NUMERIC_ENTRY(decimal_point),
4885 * By placing the decimal_point field last in the full structure, we can
4886 * use just the tail for this bit of it, saving space. This macro yields
4887 * the address of the sub structure. */
4888 # define DECIMAL_POINT_ADDRESS \
4889 &lconv_numeric_strings[(C_ARRAY_LENGTH(lconv_numeric_strings) - 2)]
4891 /* And the MONETARY string fields */
4892 const lconv_offset_t lconv_monetary_strings[] = {
4893 LCONV_MONETARY_ENTRY(int_curr_symbol),
4894 LCONV_MONETARY_ENTRY(mon_decimal_point),
4895 # ifndef NO_LOCALECONV_MON_THOUSANDS_SEP
4896 LCONV_MONETARY_ENTRY(mon_thousands_sep),
4898 # ifndef NO_LOCALECONV_MON_GROUPING
4899 LCONV_MONETARY_ENTRY(mon_grouping),
4901 LCONV_MONETARY_ENTRY(positive_sign),
4902 LCONV_MONETARY_ENTRY(negative_sign),
4903 LCONV_MONETARY_ENTRY(currency_symbol),
4907 /* Like above, this field being last can be used as a sub structure */
4908 # define CURRENCY_SYMBOL_ADDRESS \
4909 &lconv_monetary_strings[(C_ARRAY_LENGTH(lconv_monetary_strings) - 2)]
4911 /* Finally there are integer fields, all are for monetary purposes */
4912 const lconv_offset_t lconv_integers[] = {
4913 LCONV_ENTRY(int_frac_digits),
4914 LCONV_ENTRY(frac_digits),
4915 LCONV_ENTRY(p_sep_by_space),
4916 LCONV_ENTRY(n_cs_precedes),
4917 LCONV_ENTRY(n_sep_by_space),
4918 LCONV_ENTRY(p_sign_posn),
4919 LCONV_ENTRY(n_sign_posn),
4920 # ifdef HAS_LC_MONETARY_2008
4921 LCONV_ENTRY(int_p_cs_precedes),
4922 LCONV_ENTRY(int_p_sep_by_space),
4923 LCONV_ENTRY(int_n_cs_precedes),
4924 LCONV_ENTRY(int_n_sep_by_space),
4925 LCONV_ENTRY(int_p_sign_posn),
4926 LCONV_ENTRY(int_n_sign_posn),
4928 LCONV_ENTRY(p_cs_precedes),
4932 /* Like above, this field being last can be used as a sub structure */
4933 # define P_CS_PRECEDES_ADDRESS \
4934 &lconv_integers[(C_ARRAY_LENGTH(lconv_integers) - 2)]
4936 /* If we aren't paying attention to a given category, use LC_CTYPE instead;
4937 * If not paying attention to that either, the code below should end up not
4938 * using this. Make sure that things blow up if that avoidance gets lost,
4939 * by setting the category to an out-of-bounds value */
4940 locale_category_index numeric_index;
4941 locale_category_index monetary_index;
4943 # ifdef USE_LOCALE_NUMERIC
4944 numeric_index = LC_NUMERIC_INDEX_;
4945 # elif defined(USE_LOCALE_CTYPE)
4946 numeric_index = LC_CTYPE_INDEX_;
4948 numeric_index = LC_ALL_INDEX_; /* Out-of-bounds */
4950 # ifdef USE_LOCALE_MONETARY
4951 monetary_index = LC_MONETARY_INDEX_;
4952 # elif defined(USE_LOCALE_CTYPE)
4953 monetary_index = LC_CTYPE_INDEX_;
4955 monetary_index = LC_ALL_INDEX_; /* Out-of-bounds */
4958 /* Some platforms, for correct non-mojibake results, require LC_CTYPE's
4959 * locale to match LC_NUMERIC's for the numeric fields, and LC_MONETARY's
4960 * for the monetary ones. What happens if LC_NUMERIC and LC_MONETARY
4961 * aren't compatible? Wrong results. To avoid that, we call localeconv()
4962 * twice, once for each locale, setting LC_CTYPE to match the category.
4963 * But if the locales of both categories are the same, there is no need for
4964 * a second call. Assume this is the case unless overridden below */
4965 bool requires_2nd_localeconv = false;
4967 /* The actual hash populating is done by S_populate_hash_from_localeconv().
4968 * It gets passed an array of length two containing the data structure it
4969 * is supposed to use to get the key names to fill the hash with. One
4970 * element is always for the NUMERIC strings (or NULL if none to use), and
4971 * the other element similarly for the MONETARY ones. */
4972 # define NUMERIC_STRING_OFFSET 0
4973 # define MONETARY_STRING_OFFSET 1
4974 const lconv_offset_t * strings[2] = { NULL, NULL };
4976 /* This is a mask, with one bit to tell S_populate_hash_from_localeconv to
4977 * populate the NUMERIC items; another bit for the MONETARY ones. This way
4978 * it can choose which (or both) to populate from */
4981 /* This converts from a locale index to its bit position in the above mask.
4983 # define INDEX_TO_BIT(i) (1 << (i))
4985 /* The two categories can have disparate locales. Initialize them to C and
4986 * override later whichever one(s) we pay attention to */
4987 const char * numeric_locale = "C";
4988 const char * monetary_locale = "C";
4990 /* This will be either 'numeric_locale' or 'monetary_locale' depending on
4991 * what we are working on at the moment */
4992 const char * locale;
4994 /* The LC_MONETARY category also has some integer-valued fields, whose
4995 * information is kept in a separate list */
4996 const lconv_offset_t * integers;
4998 # ifdef HAS_SOME_LANGINFO
5000 /* If the only use-case for this is the full localeconv(), the 'item'
5001 * parameter is ignored. */
5002 PERL_UNUSED_ARG(item);
5006 /* This only gets compiled for the use-case of using localeconv() to
5007 * emulate an nl_langinfo() missing from the platform. */
5009 # ifdef USE_LOCALE_NUMERIC
5011 /* We need this substructure to only return this field for the THOUSEP
5012 * item. The other items also need substructures, but they were handled
5013 * above by placing the substructure's item at the end of the full one, so
5014 * the data structure could do double duty. However, both this and
5015 * RADIXCHAR would need to be in the final position of the same full
5016 * structure; an impossibility. So make this into a separate structure */
5017 const lconv_offset_t thousands_sep_string[] = {
5018 LCONV_NUMERIC_ENTRY(thousands_sep),
5024 /* End of all the initialization of data structures. Now for actual code.
5026 * Without nl_langinfo(), the call to my_localeconv() could be for just one
5027 * of the following 3 items to emulate nl_langinfo(). This is compiled
5028 * only when using perl_langinfo.h, which we control, and it has been
5029 * constructed so that no item is numbered 0.
5031 * For each, set up the appropriate parameters for the call below to
5032 * S_populate_hash_from_localeconv() */
5033 if (item != 0) switch (item) {
5035 locale_panic_(Perl_form(aTHX_
5036 "Unexpected item passed to my_localeconv: %d", item));
5039 # ifdef USE_LOCALE_NUMERIC
5042 locale = numeric_locale = PL_numeric_name;
5043 index_bits = INDEX_TO_BIT(LC_NUMERIC_INDEX_);
5044 strings[NUMERIC_STRING_OFFSET] = DECIMAL_POINT_ADDRESS;
5049 index_bits = INDEX_TO_BIT(LC_NUMERIC_INDEX_);
5050 locale = numeric_locale = PL_numeric_name;
5051 strings[NUMERIC_STRING_OFFSET] = thousands_sep_string;
5056 # ifdef USE_LOCALE_MONETARY
5059 index_bits = INDEX_TO_BIT(LC_MONETARY_INDEX_);
5060 locale = monetary_locale = querylocale_i(LC_MONETARY_INDEX_);
5062 /* This item needs the values for both the currency symbol, and another
5063 * one used to construct the nl_langino()-compatible return */
5064 strings[MONETARY_STRING_OFFSET] = CURRENCY_SYMBOL_ADDRESS;
5065 integers = P_CS_PRECEDES_ADDRESS;
5070 } /* End of switch() */
5072 else /* End of for just one item to emulate nl_langinfo() */
5076 { /* Here, the call is for all of localeconv(). It has a bunch of
5077 * items. As in the individual item case, set up the parameters for
5078 * S_populate_hash_from_localeconv(); */
5080 # ifdef USE_LOCALE_NUMERIC
5081 numeric_locale = PL_numeric_name;
5082 # elif defined(USE_LOCALE_CTYPE)
5083 numeric_locale = querylocale_i(numeric_index);
5085 # if defined(USE_LOCALE_MONETARY) || defined(USE_LOCALE_CTYPE)
5086 monetary_locale = querylocale_i(monetary_index);
5089 /* The first call to S_populate_hash_from_localeconv() will be for the
5090 * MONETARY values */
5091 index_bits = INDEX_TO_BIT(monetary_index);
5092 locale = monetary_locale;
5094 /* And if the locales for the two categories are the same, we can also
5095 * do the NUMERIC values in the same call */
5096 if (strEQ(numeric_locale, monetary_locale)) {
5097 index_bits |= INDEX_TO_BIT(numeric_index);
5100 requires_2nd_localeconv = true;
5103 /* We always pass both sets of strings. 'index_bits' tells
5104 * S_populate_hash_from_localeconv which to actually look at */
5105 strings[NUMERIC_STRING_OFFSET] = lconv_numeric_strings;
5106 strings[MONETARY_STRING_OFFSET] = lconv_monetary_strings;
5108 /* And pass the integer values to populate; again 'index_bits' will
5109 * say to use them or not */
5110 integers = lconv_integers;
5112 } /* End of call is for localeconv() */
5114 /* The code above has determined the parameters to
5115 S_populate_hash_from_localeconv() for both cases of an individual item
5116 and for the entire structure. Below is code common to both */
5118 HV * hv = newHV(); /* The returned hash, initially empty */
5119 sv_2mortal((SV*)hv);
5121 /* Call localeconv() and copy its results into the hash. All the
5122 * parameters have been initialized above */
5123 populate_hash_from_localeconv(hv,
5130 /* The above call may have done all the hash fields, but not always, as
5131 * already explained. If we need a second call it is always for the
5133 if (requires_2nd_localeconv) {
5134 populate_hash_from_localeconv(hv,
5136 INDEX_TO_BIT(numeric_index),
5138 NULL /* There are no NUMERIC integer
5143 /* Here, the hash has been completely populated.
5145 * Now go through all the items and:
5146 * a) For string items, see if they should be marked as UTF-8 or not.
5147 * This would have been more convenient and faster to do while
5148 * populating the hash in the first place, but that operation has to be
5149 * done within a critical section, keeping other threads from
5150 * executing, so only the minimal amount of work necessary is done at
5152 * b) For integer items, convert the C CHAR_MAX value into -1. Again,
5153 * this could have been done in the critical section, but was deferred
5154 * to here to keep to the bare minimum amount the time spent owning the
5155 * processor. CHAR_MAX is a C concept for an 8-bit character type.
5156 * Perl has no such type; the closest fit is a -1.
5158 * XXX On unthreaded perls, this code could be #ifdef'd out, and the
5159 * corrections determined at hash population time, at an extra maintenance
5160 * cost which khw doesn't think is worth it
5162 for (unsigned int i = 0; i < 2; i++) { /* Try both types of strings */
5163 if (! strings[i]) { /* Skip if no strings of this type */
5167 locale = (i == NUMERIC_STRING_OFFSET)
5171 locale_utf8ness_t locale_is_utf8 = LOCALE_UTF8NESS_UNKNOWN;
5173 # ifdef HAS_RELIABLE_UTF8NESS_DETERMINATION
5175 /* It saves time in the loop below to have predetermined the UTF8ness
5176 * of the locale. But only do so if the platform reliably has this
5177 * information; otherwise it's better to do it only it should become
5178 * necessary, which happens on a per-element basis in the loop. */
5180 locale_is_utf8 = (is_locale_utf8(locale))
5184 if (locale_is_utf8 == LOCALE_NOT_UTF8) {
5185 continue; /* No string can be UTF-8 if the locale isn't */
5190 /* Examine each string */
5191 for (const lconv_offset_t *strp = strings[i]; strp->name; strp++) {
5192 const char * name = strp->name;
5194 /* 'value' will contain the string that may need to be marked as
5196 SV ** value = hv_fetch(hv, name, strlen(name), true);
5201 /* Determine if the string should be marked as UTF-8. */
5202 if (UTF8NESS_YES == (get_locale_string_utf8ness_i(SvPV_nolen(*value),
5205 (locale_category_index) 0)))
5210 } /* End of fixing up UTF8ness */
5213 /* Examine each integer */
5214 for (; integers; integers++) {
5215 const char * name = integers->name;
5217 if (! name) { /* Reached the end */
5221 SV ** value = hv_fetch(hv, name, strlen(name), true);
5226 /* Change CHAR_MAX to -1 */
5227 if (SvIV(*value) == CHAR_MAX) {
5228 sv_setiv(*value, -1);
5236 S_populate_hash_from_localeconv(pTHX_ HV * hv,
5238 /* Switch to this locale to run
5239 * localeconv() from */
5240 const char * locale,
5242 /* bit mask of which categories to
5244 const U32 which_mask,
5246 /* strings[0] points to the numeric
5247 * string fields; [1] to the monetary */
5248 const lconv_offset_t * strings[2],
5250 /* And to the monetary integer fields */
5251 const lconv_offset_t * integers)
5253 PERL_ARGS_ASSERT_POPULATE_HASH_FROM_LOCALECONV;
5254 PERL_UNUSED_ARG(which_mask); /* Some configurations don't use this;
5255 complicated to figure out which */
5257 PERL_UNUSED_ARG(locale);
5260 /* Run localeconv() and copy some or all of its results to the input 'hv'
5261 * hash. Most localeconv() implementations return the values in a global
5262 * static buffer, so the operation must be performed in a critical section,
5263 * ending only after the copy is completed. There are so many locks
5264 * because localeconv() deals with two categories, and returns in a single
5265 * global static buffer. Some locks might be no-ops on this platform, but
5266 * not others. We need to lock if any one isn't a no-op. */
5268 # ifdef USE_LOCALE_CTYPE
5270 /* Some platforms require LC_CTYPE to be congruent with the category we are
5272 const char * orig_CTYPE_locale = toggle_locale_c(LC_CTYPE, locale);
5275 # ifdef USE_LOCALE_NUMERIC
5277 /* We need to toggle to the underlying NUMERIC locale if we are getting
5278 * NUMERIC strings */
5279 const char * orig_NUMERIC_locale = NULL;
5280 if (which_mask & INDEX_TO_BIT(LC_NUMERIC_INDEX_)) {
5285 /* There is a bug in Windows in which setting LC_CTYPE after the others
5286 * doesn't actually take effect for localeconv(). See commit
5287 * 418efacd1950763f74ed3cc22f8cf9206661b892 for details. Thus we have
5288 * to make sure that the locale we want is set after LC_CTYPE. We
5289 * unconditionally toggle away from and back to the current locale
5290 * prior to calling localeconv().
5292 * This code will have no effect if we already are in C, but khw
5293 * hasn't seen any cases where this causes problems when we are in the
5295 orig_NUMERIC_locale = toggle_locale_i(LC_NUMERIC_INDEX_, "C");
5296 toggle_locale_i(LC_NUMERIC_INDEX_, locale);
5300 /* No need for the extra toggle when not on Windows */
5301 orig_NUMERIC_locale = toggle_locale_i(LC_NUMERIC_INDEX_, locale);
5308 # if defined(USE_LOCALE_MONETARY) && defined(WIN32)
5310 /* Same Windows bug as described just above for NUMERIC. Otherwise, no
5311 * need to toggle LC_MONETARY, as it is kept in the underlying locale */
5312 const char * orig_MONETARY_locale = NULL;
5313 if (which_mask & INDEX_TO_BIT(LC_MONETARY_INDEX_)) {
5314 orig_MONETARY_locale = toggle_locale_i(LC_MONETARY_INDEX_, "C");
5315 toggle_locale_i(LC_MONETARY_INDEX_, locale);
5320 /* Finally ready to do the actual localeconv(). Lock to prevent other
5321 * accesses until we have made a copy of its returned static buffer */
5324 # if defined(TS_W32_BROKEN_LOCALECONV) && defined(USE_THREAD_SAFE_LOCALE)
5326 /* This is a workaround for another bug in Windows. localeconv() was
5327 * broken with thread-safe locales prior to VS 15. It looks at the global
5328 * locale instead of the thread one. As a work-around, we toggle to the
5329 * global locale; populate the return; then toggle back. We have to use
5330 * LC_ALL instead of the individual categories because of yet another bug
5331 * in Windows. And this all has to be done in a critical section.
5333 * This introduces a potential race with any other thread that has also
5334 * converted to use the global locale, and doesn't protect its locale calls
5335 * with mutexes. khw can't think of any reason for a thread to do so on
5336 * Windows, as the locale API is the same regardless of thread-safety,
5337 * except if the code is ported from working on another platform where
5338 * there might be some reason to do this. But this is typically due to
5339 * some alien-to-Perl library that thinks it owns locale setting. Such a
5340 * library isn't likely to exist on Windows, so such an application is
5341 * unlikely to be run on Windows
5343 bool restore_per_thread = FALSE;
5345 /* Save the per-thread locale state */
5346 const char * save_thread = querylocale_c(LC_ALL);
5348 /* Change to the global locale, and note if we already were there */
5349 int config_return = _configthreadlocale(_DISABLE_PER_THREAD_LOCALE);
5350 if (config_return != _DISABLE_PER_THREAD_LOCALE) {
5351 if (config_return == -1) {
5352 locale_panic_("_configthreadlocale returned an error");
5355 restore_per_thread = TRUE;
5358 /* Save the state of the global locale; then convert to our desired
5360 const char * save_global = querylocale_c(LC_ALL);
5361 void_setlocale_c(LC_ALL, save_thread);
5363 # endif /* TS_W32_BROKEN_LOCALECONV */
5365 /* Finally, do the actual localeconv */
5366 const char *lcbuf_as_string = (const char *) localeconv();
5368 /* Fill in the string fields of the HV* */
5369 for (unsigned int i = 0; i < 2; i++) {
5371 /* One iteration is only for the numeric string fields. Skip these
5372 * unless we are compiled to care about those fields and the input
5373 * parameters indicate we want their values */
5374 if ( i == NUMERIC_STRING_OFFSET
5376 # ifdef USE_LOCALE_NUMERIC
5378 && (which_mask & INDEX_TO_BIT(LC_NUMERIC_INDEX_)) == 0
5386 /* The other iteration is only for the monetary string fields. Again
5387 * skip it unless we want those values */
5388 if ( i == MONETARY_STRING_OFFSET
5390 # ifdef USE_LOCALE_MONETARY
5392 && (which_mask & INDEX_TO_BIT(LC_MONETARY_INDEX_)) == 0
5400 /* For each field for the given category ... */
5401 const lconv_offset_t * category_strings = strings[i];
5403 const char * name = category_strings->name;
5404 if (! name) { /* Quit at the end */
5408 /* we have set things up so that we know where in the returned
5409 * structure, when viewed as a string, the corresponding value is.
5411 const char *value = *((const char **)( lcbuf_as_string
5412 + category_strings->offset));
5414 /* Set to get next string on next iteration */
5417 /* Skip if this platform doesn't have this field. */
5422 /* Copy to the hash */
5425 newSVpv(value, strlen(value)),
5429 /* Add any int fields to the HV* */
5430 if (i == MONETARY_STRING_OFFSET && integers) {
5431 while (integers->name) {
5432 const char value = *((const char *)( lcbuf_as_string
5433 + integers->offset));
5434 (void) hv_store(hv, integers->name,
5435 strlen(integers->name), newSViv(value), 0);
5439 } /* End of loop through the fields */
5441 /* Done with copying to the hash. Can unwind the critical section locks */
5443 # if defined(TS_W32_BROKEN_LOCALECONV) && defined(USE_THREAD_SAFE_LOCALE)
5445 /* Restore the global locale's prior state */
5446 void_setlocale_c(LC_ALL, save_global);
5448 /* And back to per-thread locales */
5449 if (restore_per_thread) {
5450 if (_configthreadlocale(_ENABLE_PER_THREAD_LOCALE) == -1) {
5451 locale_panic_("_configthreadlocale returned an error");
5455 /* Restore the per-thread locale state */
5456 void_setlocale_c(LC_ALL, save_thread);
5458 # endif /* TS_W32_BROKEN_LOCALECONV */
5460 gwLOCALE_UNLOCK; /* Finished with the critical section of a
5461 globally-accessible buffer */
5463 # if defined(USE_LOCALE_MONETARY) && defined(WIN32)
5465 restore_toggled_locale_i(LC_MONETARY_INDEX_, orig_MONETARY_locale);
5468 # ifdef USE_LOCALE_NUMERIC
5470 restore_toggled_locale_i(LC_NUMERIC_INDEX_, orig_NUMERIC_locale);
5471 if (which_mask & INDEX_TO_BIT(LC_NUMERIC_INDEX_)) {
5476 # ifdef USE_LOCALE_CTYPE
5478 restore_toggled_locale_c(LC_CTYPE, orig_CTYPE_locale);
5484 #endif /* defined(HAS_LOCALECONV) */
5485 #ifndef HAS_SOME_LANGINFO
5487 typedef int nl_item; /* Substitute 'int' for emulated nl_langinfo() */
5493 =for apidoc Perl_langinfo
5494 =for apidoc_item Perl_langinfo8
5496 C<Perl_langinfo> is an (almost) drop-in replacement for the system
5497 C<L<nl_langinfo(3)>>, taking the same C<item> parameter values, and returning
5498 the same information. But it is more thread-safe than regular
5499 C<nl_langinfo()>, and hides the quirks of Perl's locale handling from your
5500 code, and can be used on systems that lack a native C<nl_langinfo>.
5502 However, you should instead use the improved version of this:
5503 L</Perl_langinfo8>, which behaves identically except for an additional
5504 parameter, a pointer to a variable declared as L</C<utf8ness_t>>, into which it
5505 returns to you how you should treat the returned string with regards to it
5506 being encoded in UTF-8 or not.
5508 Concerning the differences between these and plain C<nl_langinfo()>:
5514 C<Perl_langinfo8> has an extra parameter, described above. Besides this, the
5515 other reason they aren't quite a drop-in replacement is actually an advantage.
5516 The C<const>ness of the return allows the compiler to catch attempts to write
5517 into the returned buffer, which is illegal and could cause run-time crashes.
5521 They deliver the correct results for the C<RADIXCHAR> and C<THOUSEP> items,
5522 without you having to write extra code. The reason for the extra code would be
5523 because these are from the C<LC_NUMERIC> locale category, which is normally
5524 kept set by Perl so that the radix is a dot, and the separator is the empty
5525 string, no matter what the underlying locale is supposed to be, and so to get
5526 the expected results, you have to temporarily toggle into the underlying
5527 locale, and later toggle back. (You could use plain C<nl_langinfo> and
5528 C<L</STORE_LC_NUMERIC_FORCE_TO_UNDERLYING>> for this but then you wouldn't get
5529 the other advantages of C<Perl_langinfo()>; not keeping C<LC_NUMERIC> in the C
5530 (or equivalent) locale would break a lot of CPAN, which is expecting the radix
5531 (decimal point) character to be a dot.)
5535 The system function they replace can have its static return buffer trashed,
5536 not only by a subsequent call to that function, but by a C<freelocale>,
5537 C<setlocale>, or other locale change. The returned buffer of these functions
5538 is not changed until the next call to one or the other, so the buffer is never
5543 The return buffer is per-thread, so it also is never overwritten by a call to
5544 these functions from another thread; unlike the function it replaces.
5548 But most importantly, they work on systems that don't have C<nl_langinfo>, such
5549 as Windows, hence making your code more portable. Of the fifty-some possible
5550 items specified by the POSIX 2008 standard,
5551 L<http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/langinfo.h.html>,
5552 only one is completely unimplemented, though on non-Windows platforms, another
5553 significant one is not fully implemented). They use various techniques to
5554 recover the other items, including calling C<L<localeconv(3)>>, and
5555 C<L<strftime(3)>>, both of which are specified in C89, so should be always be
5556 available. Later C<strftime()> versions have additional capabilities.
5557 If an item is not available on your system, this returns either the value
5558 associated with the C locale, or simply C<"">, whichever is more appropriate.
5560 It is important to note that, when called with an item that is recovered by
5561 using C<localeconv>, the buffer from any previous explicit call to
5562 C<L<localeconv(3)>> will be overwritten. But you shouldn't be using
5563 C<localeconv> anyway because it is is very much not thread-safe, and suffers
5564 from the same problems outlined in item 'b.' above for the fields it returns
5565 that are controlled by the LC_NUMERIC locale category. Instead, avoid all of
5566 those problems by calling L</Perl_localeconv>, which is thread-safe; or by
5567 using the methods given in L<perlcall> to call
5568 L<C<POSIX::localeconv()>|POSIX/localeconv>, which is also thread-safe.
5572 The details for those items which may deviate from what this emulation returns
5573 and what a native C<nl_langinfo()> would return are specified in
5576 When using C<Perl_langinfo8> (or plain C<Perl_langinfo>) on systems that don't
5577 have a native C<nl_langinfo()>, you must
5579 #include "perl_langinfo.h"
5581 before the C<perl.h> C<#include>. You can replace your F<langinfo.h>
5582 C<#include> with this one. (Doing it this way keeps out the symbols that plain
5583 F<langinfo.h> would try to import into the namespace for code that doesn't need
5591 Perl_langinfo(const nl_item item)
5593 return Perl_langinfo8(item, NULL);
5597 Perl_langinfo8(const nl_item item, utf8ness_t * utf8ness)
5600 locale_category_index cat_index;
5602 PERL_ARGS_ASSERT_PERL_LANGINFO8;
5604 if (utf8ness) { /* Assume for now */
5605 *utf8ness = UTF8NESS_IMMATERIAL;
5608 /* Find the locale category that controls the input 'item'. If we are not
5609 * paying attention to that category, instead return a default value. Also
5610 * return the default value if there is no way for us to figure out the
5611 * correct value. If we have some form of nl_langinfo(), we can always
5612 * figure it out, but lacking that, there may be alternative methods that
5613 * can be used to recover most of the possible items. Some of those
5614 * methods need libc functions, which may or may not be available. If
5615 * unavailable, we can't compute the correct value, so must here return the
5621 #ifdef USE_LOCALE_CTYPE
5623 cat_index = LC_CTYPE_INDEX_;
5629 #if defined(USE_LOCALE_MESSAGES) && defined(HAS_SOME_LANGINFO)
5631 case YESEXPR: case YESSTR: case NOEXPR: case NOSTR:
5632 cat_index = LC_MESSAGES_INDEX_;
5635 case YESEXPR: return "^[+1yY]";
5636 case YESSTR: return "yes";
5637 case NOEXPR: return "^[-0nN]";
5638 case NOSTR: return "no";
5643 #if defined(USE_LOCALE_MONETARY) \
5644 && (defined(HAS_SOME_LANGINFO) || defined(HAS_LOCALECONV))
5646 cat_index = LC_MONETARY_INDEX_;
5654 #ifdef CAN_CALCULATE_RADIX
5656 cat_index = LC_NUMERIC_INDEX_;
5659 return C_decimal_point;
5664 #if defined(USE_LOCALE_NUMERIC) \
5665 && (defined(HAS_SOME_LANGINFO) || defined(HAS_LOCALECONV))
5667 cat_index = LC_NUMERIC_INDEX_;
5670 return C_thousands_sep;
5673 /* The other possible items are all in LC_TIME. */
5674 #ifdef USE_LOCALE_TIME
5677 cat_index = LC_TIME_INDEX_;
5681 #if ! defined(USE_LOCALE_TIME) || ! defined(HAS_SOME_LANGINFO)
5683 /* If not using LC_TIME, hard code the rest. Or, if there is no
5684 * nl_langinfo(), we use strftime() as an alternative, and it is missing
5685 * functionality to get every single one, so hard-code those */
5687 case ERA: return ""; /* Unimplemented; for use with strftime() %E
5690 /* These formats are defined by C89, so we assume that strftime supports
5691 * them, and so are returned unconditionally; they may not be what the
5692 * locale actually says, but should give good enough results for someone
5693 * using them as formats (as opposed to trying to parse them to figure
5694 * out what the locale says). The other format items are actually tested
5695 * to verify they work on the platform */
5696 case D_FMT: return "%x";
5697 case T_FMT: return "%X";
5698 case D_T_FMT: return "%c";
5700 # if defined(WIN32) || ! defined(USE_LOCALE_TIME)
5702 /* strftime() on Windows doesn't have the POSIX (beyond C89) extensions
5703 * that would allow it to recover these */
5704 case ERA_D_FMT: return "%x";
5705 case ERA_T_FMT: return "%X";
5706 case ERA_D_T_FMT: return "%c";
5707 case ALT_DIGITS: return "0";
5710 # ifndef USE_LOCALE_TIME
5712 case T_FMT_AMPM: return "%r";
5713 case ABDAY_1: return "Sun";
5714 case ABDAY_2: return "Mon";
5715 case ABDAY_3: return "Tue";
5716 case ABDAY_4: return "Wed";
5717 case ABDAY_5: return "Thu";
5718 case ABDAY_6: return "Fri";
5719 case ABDAY_7: return "Sat";
5720 case AM_STR: return "AM";
5721 case PM_STR: return "PM";
5722 case ABMON_1: return "Jan";
5723 case ABMON_2: return "Feb";
5724 case ABMON_3: return "Mar";
5725 case ABMON_4: return "Apr";
5726 case ABMON_5: return "May";
5727 case ABMON_6: return "Jun";
5728 case ABMON_7: return "Jul";
5729 case ABMON_8: return "Aug";
5730 case ABMON_9: return "Sep";
5731 case ABMON_10: return "Oct";
5732 case ABMON_11: return "Nov";
5733 case ABMON_12: return "Dec";
5734 case DAY_1: return "Sunday";
5735 case DAY_2: return "Monday";
5736 case DAY_3: return "Tuesday";
5737 case DAY_4: return "Wednesday";
5738 case DAY_5: return "Thursday";
5739 case DAY_6: return "Friday";
5740 case DAY_7: return "Saturday";
5741 case MON_1: return "January";
5742 case MON_2: return "February";
5743 case MON_3: return "March";
5744 case MON_4: return "April";
5745 case MON_5: return "May";
5746 case MON_6: return "June";
5747 case MON_7: return "July";
5748 case MON_8: return "August";
5749 case MON_9: return "September";
5750 case MON_10: return "October";
5751 case MON_11: return "November";
5752 case MON_12: return "December";
5757 } /* End of switch on item */
5761 Perl_croak_nocontext("panic: Unexpected nl_langinfo() item %d", item);
5762 NOT_REACHED; /* NOTREACHED */
5763 PERL_UNUSED_VAR(cat_index);
5767 return my_langinfo_i(item, cat_index, query_nominal_locale_i(cat_index),
5768 &PL_langinfo_buf, &PL_langinfo_bufsize, utf8ness);
5774 Perl_my_strftime(pTHX_ const char *fmt, int sec, int min, int hour,
5775 int mday, int mon, int year, int wday, int yday,
5777 { /* Documented above */
5778 PERL_ARGS_ASSERT_MY_STRFTIME;
5781 ints_to_tm(&mytm, sec, min, hour, mday, mon, year, wday, yday, isdst);
5782 char * ret = strftime_tm(fmt, &mytm);
5787 Perl_sv_strftime_tm(pTHX_ SV * fmt, const struct tm * mytm)
5788 { /* Documented above */
5789 PERL_ARGS_ASSERT_SV_STRFTIME_TM;
5791 utf8ness_t fmt_utf8ness = (SvUTF8(fmt) && LIKELY(! IN_BYTES))
5795 utf8ness_t result_utf8ness;
5796 char * retval = strftime8(SvPV_nolen(fmt),
5800 true /* calling from sv_strftime */
5804 STRLEN len = strlen(retval);
5806 sv_usepvn_flags(sv, retval, len, SV_HAS_TRAILING_NUL);
5808 if (result_utf8ness == UTF8NESS_YES) {
5817 Perl_sv_strftime_ints(pTHX_ SV * fmt, int sec, int min, int hour,
5818 int mday, int mon, int year, int wday,
5819 int yday, int isdst)
5820 { /* Documented above */
5821 PERL_ARGS_ASSERT_SV_STRFTIME_INTS;
5824 ints_to_tm(&mytm, sec, min, hour, mday, mon, year, wday, yday, isdst);
5825 SV * ret = sv_strftime_tm(fmt, &mytm);
5831 /* There are several implementations of my_langinfo, depending on the
5832 * Configuration. They all share the same beginning of the function */
5834 S_my_langinfo_i(pTHX_
5835 const nl_item item, /* The item to look up */
5836 const locale_category_index cat_index, /* The locale category
5838 /* The locale to look up 'item' in. */
5839 const char * locale,
5841 /* Where to store the result, and where the size of that buffer
5842 * is stored, updated on exit. retbuf_sizep may be NULL for an
5843 * empty-on-entry, single use buffer whose size we don't need
5844 * to keep track of */
5846 Size_t * retbuf_sizep,
5848 /* If not NULL, the location to store the UTF8-ness of 'item's
5849 * value, as documented */
5850 utf8ness_t * utf8ness)
5852 const char * retval = NULL;
5854 PERL_ARGS_ASSERT_MY_LANGINFO_I;
5855 assert(cat_index < LC_ALL_INDEX_);
5857 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
5858 "Entering my_langinfo item=%ld, using locale %s\n",
5859 (long) item, locale));
5860 /*--------------------------------------------------------------------------*/
5861 /* Above is the common beginning to all the implementations of my_langinfo().
5862 * Below are the various completions.
5864 * Some platforms don't deal well with non-ASCII strings in locale X when
5865 * LC_CTYPE is not in X. (Actually it is probably when X is UTF-8 and LC_CTYPE
5866 * isn't, or vice versa). There is explicit code to bring the categories into
5867 * sync. This doesn't seem to be a problem with nl_langinfo(), so that
5868 * implementation doesn't currently worry about it. But it is a problem on
5869 * Windows boxes, which don't have nl_langinfo(). */
5871 /*--------------------------------------------------------------------------*/
5872 # if defined(HAS_NL_LANGINFO) /* nl_langinfo() is available. */
5873 # ifdef USE_LOCALE_CTYPE
5875 /* This function sorts out if things actually have to be switched or not,
5876 * for both save and restore. */
5877 const char * orig_CTYPE_locale = toggle_locale_c(LC_CTYPE, locale);
5881 const char * orig_switched_locale = toggle_locale_i(cat_index, locale);
5884 retval = save_to_buffer(nl_langinfo(item), retbufp, retbuf_sizep);
5888 *utf8ness = get_locale_string_utf8ness_i(retval,
5889 LOCALE_UTF8NESS_UNKNOWN,
5893 restore_toggled_locale_i(cat_index, orig_switched_locale);
5895 # ifdef USE_LOCALE_CTYPE
5897 restore_toggled_locale_c(LC_CTYPE, orig_CTYPE_locale);
5902 /*--------------------------------------------------------------------------*/
5903 # else /* Below, emulate nl_langinfo as best we can */
5905 /* The other completion is where we have to emulate nl_langinfo(). There
5906 * are various possibilities depending on the Configuration */
5908 # ifdef USE_LOCALE_CTYPE
5910 const char * orig_CTYPE_locale = toggle_locale_c(LC_CTYPE, locale);
5914 const char * orig_switched_locale = toggle_locale_i(cat_index, locale);
5916 /* Here, we are in the locale we want information about */
5918 /* Almost all the items will have ASCII return values. Set that here, and
5919 * override if necessary */
5920 utf8ness_t is_utf8 = UTF8NESS_IMMATERIAL;
5924 assert(item < 0); /* Make sure using perl_langinfo.h */
5930 # if defined(HAS_SNPRINTF) \
5931 && (! defined(HAS_LOCALECONV) || defined(TS_W32_BROKEN_LOCALECONV))
5934 /* snprintf() can be used to find the radix character by outputting
5935 * a known simple floating point number to a buffer, and parsing
5936 * it, inferring the radix as the bytes separating the integer and
5937 * fractional parts. But localeconv() is more direct, not
5938 * requiring inference, so use it instead of the code just below,
5939 * if (likely) it is available and works ok */
5941 char * floatbuf = NULL;
5942 const Size_t initial_size = 10;
5944 Newx(floatbuf, initial_size, char);
5946 /* 1.5 is exactly representable on binary computers */
5947 Size_t needed_size = snprintf(floatbuf, initial_size, "%.1f", 1.5);
5949 /* If our guess wasn't big enough, increase and try again, based on
5950 * the real number that snprintf() is supposed to return */
5951 if (UNLIKELY(needed_size >= initial_size)) {
5952 needed_size++; /* insurance */
5953 Renew(floatbuf, needed_size, char);
5954 Size_t new_needed = snprintf(floatbuf, needed_size, "%.1f", 1.5);
5955 assert(new_needed <= needed_size);
5956 needed_size = new_needed;
5959 char * s = floatbuf;
5960 char * e = floatbuf + needed_size;
5963 while (s < e && *s != '1') {
5967 if (LIKELY(s < e)) {
5972 char * item_start = s;
5973 while (s < e && *s != '5') {
5977 /* Everything in between is the radix string */
5978 if (LIKELY(s < e)) {
5980 retval = save_to_buffer(item_start, retbufp, retbuf_sizep);
5984 is_utf8 = get_locale_string_utf8ness_i(retval,
5985 LOCALE_UTF8NESS_UNKNOWN,
5995 # ifdef HAS_LOCALECONV /* snprintf() failed; drop down to use
6000 # else /* snprintf() failed and no localeconv() */
6002 retval = C_decimal_point;
6007 # ifdef HAS_LOCALECONV
6009 /* These items are available from localeconv(). (To avoid using
6010 * TS_W32_BROKEN_LOCALECONV, one could use GetNumberFormat and
6011 * GetCurrencyFormat; patches welcome) */
6013 # define P_CS_PRECEDES "p_cs_precedes"
6014 # define CURRENCY_SYMBOL "currency_symbol"
6016 /* case RADIXCHAR: // May drop down to here in some configurations */
6021 /* The hash gets populated with just the field(s) related to 'item'. */
6022 HV * result_hv = my_localeconv(item);
6025 if (item != CRNCYSTR) {
6027 /* These items have been populated with just one key => value */
6028 (void) hv_iterinit(result_hv);
6029 HE * entry = hv_iternext(result_hv);
6030 string = hv_iterval(result_hv, entry);
6034 /* But CRNCYSTR localeconv() returns a slightly different value
6035 * than the nl_langinfo() API calls for, so have to modify this one
6036 * to conform. We need another value from localeconv() to know
6037 * what to change it to. my_localeconv() has populated the hash
6038 * with exactly both fields. Delete this one, leaving just the
6039 * CRNCYSTR one in the hash */
6040 SV* precedes = hv_delete(result_hv,
6041 P_CS_PRECEDES, STRLENs(P_CS_PRECEDES),
6044 locale_panic_("my_localeconv() unexpectedly didn't return"
6045 " a value for " P_CS_PRECEDES);
6048 /* The modification is to prefix the localeconv() return with a
6049 * single byte, calculated as follows: */
6050 char prefix = (LIKELY(SvIV(precedes) != -1))
6051 ? ((precedes != 0) ? '-' : '+')
6053 /* khw couldn't find any documentation that
6054 * CHAR_MAX (which we modify to -1) is the signal,
6055 * but cygwin uses it thusly, and it makes sense
6056 * given that CHAR_MAX indicates the value isn't
6057 * used, so it neither precedes nor succeeds */
6060 /* Now get CRNCYSTR */
6061 (void) hv_iterinit(result_hv);
6062 HE * entry = hv_iternext(result_hv);
6063 string = hv_iterval(result_hv, entry);
6065 /* And perform the modification */
6066 Perl_sv_setpvf(aTHX_ string, "%c%s", prefix, SvPV_nolen(string));
6069 /* Here, 'string' contains the value we want to return */
6070 retval = save_to_buffer(SvPV_nolen(string), retbufp, retbuf_sizep);
6073 is_utf8 = (SvUTF8(string))
6075 : (is_utf8_invariant_string( (U8 *) retval,
6077 ? UTF8NESS_IMMATERIAL
6085 # endif /* Some form of localeconv */
6086 # ifdef HAS_STRFTIME
6088 /* These formats are only available in later strftime's */
6089 case ERA_D_FMT: case ERA_T_FMT: case ERA_D_T_FMT: case T_FMT_AMPM:
6091 /* The rest can be gotten from most versions of strftime(). */
6092 case ABDAY_1: case ABDAY_2: case ABDAY_3:
6093 case ABDAY_4: case ABDAY_5: case ABDAY_6: case ABDAY_7:
6095 case AM_STR: case PM_STR:
6096 case ABMON_1: case ABMON_2: case ABMON_3: case ABMON_4:
6097 case ABMON_5: case ABMON_6: case ABMON_7: case ABMON_8:
6098 case ABMON_9: case ABMON_10: case ABMON_11: case ABMON_12:
6099 case DAY_1: case DAY_2: case DAY_3: case DAY_4:
6100 case DAY_5: case DAY_6: case DAY_7:
6101 case MON_1: case MON_2: case MON_3: case MON_4:
6102 case MON_5: case MON_6: case MON_7: case MON_8:
6103 case MON_9: case MON_10: case MON_11: case MON_12:
6105 const char * format;
6106 bool return_format = FALSE;
6111 GCC_DIAG_IGNORE_STMT(-Wimplicit-fallthrough);
6115 locale_panic_(Perl_form(aTHX_ "switch case: %d problem", item));
6116 NOT_REACHED; /* NOTREACHED */
6118 case PM_STR: hour = 18;
6122 case ABDAY_7: mday++;
6123 case ABDAY_6: mday++;
6124 case ABDAY_5: mday++;
6125 case ABDAY_4: mday++;
6126 case ABDAY_3: mday++;
6127 case ABDAY_2: mday++;
6140 case ABMON_12: mon++;
6141 case ABMON_11: mon++;
6142 case ABMON_10: mon++;
6143 case ABMON_9: mon++;
6144 case ABMON_8: mon++;
6145 case ABMON_7: mon++;
6146 case ABMON_6: mon++;
6147 case ABMON_5: mon++;
6148 case ABMON_4: mon++;
6149 case ABMON_3: mon++;
6150 case ABMON_2: mon++;
6170 return_format = TRUE;
6174 return_format = TRUE;
6178 return_format = TRUE;
6182 return_format = TRUE;
6185 format = "%Ow"; /* Find the alternate digit for 0 */
6189 GCC_DIAG_RESTORE_STMT;
6191 /* The year was deliberately chosen so that January 1 is on the
6192 * first day of the week. Since we're only getting one thing at a
6193 * time, it all works */
6195 ints_to_tm(&mytm, 30, 30, hour, mday, mon, 2011, 0, 0, 0);
6198 temp = strftime8(format,
6200 UTF8NESS_IMMATERIAL, /* All possible formats
6204 false /* not calling from sv_strftime */
6208 temp = strftime_tm(format, &mytm);
6211 retval = save_to_buffer(temp, retbufp, retbuf_sizep);
6214 /* If the item is 'ALT_DIGITS', '*retbuf' contains the alternate
6215 * format for wday 0. If the value is the same as the normal 0,
6216 * there isn't an alternate, so clear the buffer.
6218 * (wday was chosen because its range is all a single digit.
6219 * Things like tm_sec have two digits as the minimum: '00'.) */
6220 if (item == ALT_DIGITS && strEQ(*retbufp, "0")) {
6225 /* ALT_DIGITS is problematic. Experiments on it showed that
6226 * strftime() did not always work properly when going from alt-9 to
6227 * alt-10. Only a few locales have this item defined, and in all
6228 * of them on Linux that khw was able to find, nl_langinfo() merely
6229 * returned the alt-0 character, possibly doubled. Most Unicode
6230 * digits are in blocks of 10 consecutive code points, so that is
6231 * sufficient information for such scripts, as we can infer alt-1,
6232 * alt-2, .... But for a Japanese locale, a CJK ideographic 0 is
6233 * returned, and the CJK digits are not in code point order, so you
6234 * can't really infer anything. The localedef for this locale did
6235 * specify the succeeding digits, so that strftime() works properly
6236 * on them, without needing to infer anything. But the
6237 * nl_langinfo() return did not give sufficient information for the
6238 * caller to understand what's going on. So until there is
6239 * evidence that it should work differently, this returns the alt-0
6240 * string for ALT_DIGITS. */
6242 if (return_format) {
6244 /* If to return the format, not the value, overwrite the buffer
6245 * with it. But some strftime()s will keep the original format
6246 * if illegal, so change those to "" */
6247 if (strEQ(*retbufp, format)) {
6254 /* A format is always in ASCII */
6255 is_utf8 = UTF8NESS_IMMATERIAL;
6262 # ifdef USE_LOCALE_CTYPE
6266 /* The trivial case */
6267 if (isNAME_C_OR_POSIX(locale)) {
6274 /* This function retrieves the code page. It is subject to change, but
6275 * is documented and has been stable for many releases */
6276 UINT ___lc_codepage_func(void);
6278 # ifndef WIN32_USE_FAKE_OLD_MINGW_LOCALES
6280 retval = save_to_buffer(Perl_form(aTHX_ "%d", ___lc_codepage_func()),
6281 retbufp, retbuf_sizep);
6284 retval = save_to_buffer(nl_langinfo(CODESET),
6285 retbufp, retbuf_sizep);
6288 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "locale='%s' cp=%s\n",
6294 /* The codeset is important, but khw did not figure out a way for it to
6295 * be retrieved on non-Windows boxes without nl_langinfo(). But even
6296 * if we can't get it directly, we can usually determine if it is a
6297 * UTF-8 locale or not. If it is UTF-8, we (correctly) use that for
6300 # if defined(HAS_MBTOWC) || defined(HAS_MBRTOWC)
6302 /* If libc mbtowc() evaluates the bytes that form the REPLACEMENT
6303 * CHARACTER as that Unicode code point, this has to be a UTF-8 locale.
6306 (void) Perl_mbtowc_(aTHX_ NULL, NULL, 0);/* Reset shift state */
6307 int mbtowc_ret = Perl_mbtowc_(aTHX_ &wc,
6308 STR_WITH_LEN(REPLACEMENT_CHARACTER_UTF8));
6309 if (mbtowc_ret >= 0 && wc == UNICODE_REPLACEMENT) {
6310 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
6311 "mbtowc returned REPLACEMENT\n"));
6316 /* Here, it isn't a UTF-8 locale. */
6318 # else /* mbtowc() is not available. The chances of this code getting
6319 compiled are very small, as it is a C99 required function,
6320 and we are now requiring C99; perhaps if it is a defective
6321 implementation. But if so, there are other libc functions
6322 that could be used instead. */
6324 /* Sling together several possibilities, depending on platform
6325 * capabilities and what we found.
6327 * For non-English locales or non-dollar currency locales, we likely
6328 * will find out whether a locale is UTF-8 or not */
6330 utf8ness_t is_utf8 = UTF8NESS_UNKNOWN;
6331 char * scratch_buf = NULL;
6333 # if defined(USE_LOCALE_MONETARY) && defined(HAS_LOCALECONV)
6334 # define LANGINFO_RECURSED_MONETARY 0x1
6335 # define LANGINFO_RECURSED_TIME 0x2
6337 /* Can't use this method unless localeconv() is available, as that's
6338 * the way we find out the currency symbol.
6340 * First try looking at the currency symbol (via a recursive call) to
6341 * see if it disambiguates things. Often that will be in the native
6342 * script, and if the symbol isn't legal UTF-8, we know that the locale
6345 * The recursion calls my_localeconv() to find CRNCYSTR, and that can
6346 * call is_locale_utf8() which will call my_langinfo(CODESET) which
6347 * will get to here again, ad infinitum. The guard prevents that.
6349 if ((PL_langinfo_recursed & LANGINFO_RECURSED_MONETARY) == 0) {
6350 PL_langinfo_recursed |= LANGINFO_RECURSED_MONETARY;
6351 (void) my_langinfo_c(CRNCYSTR, LC_MONETARY, locale, &scratch_buf,
6353 PL_langinfo_recursed &= ~LANGINFO_RECURSED_MONETARY;
6356 Safefree(scratch_buf);
6359 # ifdef USE_LOCALE_TIME
6361 /* If we have ruled out being UTF-8, no point in checking further. */
6362 if ( is_utf8 != UTF8NESS_NO
6363 && (PL_langinfo_recursed & LANGINFO_RECURSED_TIME) == 0)
6365 /* But otherwise do check more. This is done even if the currency
6366 * symbol looks to be UTF-8, just in case that's a false positive.
6368 * Look at the LC_TIME entries, like the names of the months or
6369 * weekdays. We quit at the first one that is illegal UTF-8
6371 * The recursion guard is because the recursed my_langinfo_c() will
6372 * call strftime8() to find the LC_TIME value passed to it, and
6373 * that will call my_langinfo(CODESET) for non-ASCII returns,
6374 * which will get here again, ad infinitum
6377 utf8ness_t this_is_utf8 = UTF8NESS_UNKNOWN;
6378 const int times[] = {
6379 DAY_1, DAY_2, DAY_3, DAY_4, DAY_5, DAY_6, DAY_7,
6380 MON_1, MON_2, MON_3, MON_4, MON_5, MON_6, MON_7, MON_8,
6381 MON_9, MON_10, MON_11, MON_12,
6382 ALT_DIGITS, AM_STR, PM_STR,
6383 ABDAY_1, ABDAY_2, ABDAY_3, ABDAY_4, ABDAY_5, ABDAY_6,
6385 ABMON_1, ABMON_2, ABMON_3, ABMON_4, ABMON_5, ABMON_6,
6386 ABMON_7, ABMON_8, ABMON_9, ABMON_10, ABMON_11, ABMON_12
6389 /* The code in the recursive call can handle switching the locales,
6390 * but by doing it here, we avoid switching each iteration of the
6392 const char * orig_TIME_locale = toggle_locale_c(LC_TIME, locale);
6394 PL_langinfo_recursed |= LANGINFO_RECURSED_TIME;
6395 for (PERL_UINT_FAST8_T i = 0; i < C_ARRAY_LENGTH(times); i++) {
6397 (void) my_langinfo_c(times[i], LC_TIME, locale, &scratch_buf,
6398 NULL, &this_is_utf8);
6399 Safefree(scratch_buf);
6400 if (this_is_utf8 == UTF8NESS_NO) {
6401 is_utf8 = UTF8NESS_NO;
6405 if (this_is_utf8 == UTF8NESS_YES) {
6406 is_utf8 = UTF8NESS_YES;
6409 PL_langinfo_recursed &= ~LANGINFO_RECURSED_TIME;
6411 /* Here we have gone through all the LC_TIME elements. is_utf8 has
6412 * been set as follows:
6413 * UTF8NESS_NO If at least one isn't legal UTF-8
6414 * UTF8NESS_IMMMATERIAL If all are ASCII
6415 * UTF8NESS_YES If all are legal UTF-8 (including
6416 * ASCII), and at least one isn't
6419 restore_toggled_locale_c(LC_TIME, orig_TIME_locale);
6422 # endif /* LC_TIME */
6424 /* If nothing examined above rules out it being UTF-8, and at least one
6425 * thing fits as UTF-8 (and not plain ASCII), assume the codeset is
6427 if (is_utf8 == UTF8NESS_YES) {
6432 /* Here, nothing examined indicates that the codeset is UTF-8. But
6433 * what is it? The other locale categories are not likely to be of
6436 * LC_NUMERIC Only a few locales in the world have a non-ASCII radix
6437 * or group separator.
6438 * LC_CTYPE This code wouldn't be compiled if mbtowc() existed and
6439 * was reliable. This is unlikely in C99. There are
6440 * other functions that could be used instead, but are
6441 * they going to exist, and be able to distinguish between
6442 * UTF-8 and 8859-1? Deal with this only if it becomes
6444 * LC_MESSAGES The strings returned from strerror() would seem likely
6445 * candidates, but experience has shown that many systems
6446 * don't actually have translations installed for them.
6447 * They are instead always in English, so everything in
6448 * them is ASCII, which is of no help to us. A Configure
6449 * probe could possibly be written to see if this platform
6450 * has non-ASCII error messages. But again, wait until it
6451 * turns out to be an actual problem. */
6453 # endif /* ! mbtowc() */
6455 /* Rejoin the mbtowc available/not-available cases.
6457 * We got here only because we haven't been able to find the codeset.
6458 * The only other option khw could think of is to see if the codeset is
6459 * part of the locale name. This is very less than ideal; often there
6460 * is no code set in the name; and at other times they even lie.
6462 * But there is an XPG standard syntax, which many locales follow:
6464 * language[_territory[.codeset]][@modifier]
6466 * So we take the part between the dot and any '@' */
6467 retval = (const char *) strchr(locale, '.');
6469 retval = ""; /* Alas, no dot */
6473 /* Don't include the dot */
6476 /* And stop before any '@' */
6477 const char * modifier = strchr(retval, '@');
6479 char * code_set_name;
6480 const Size_t name_len = modifier - retval;
6481 Newx(code_set_name, name_len + 1, char); /* +1 for NUL */
6482 my_strlcpy(code_set_name, retval, name_len + 1);
6483 SAVEFREEPV(code_set_name);
6484 retval = code_set_name;
6487 # if defined(HAS_MBTOWC) || defined(HAS_MBRTOWC)
6489 /* When these functions, are available, they were tried earlier and
6490 * indicated that the locale did not act like a proper UTF-8 one. So
6491 * if it claims to be UTF-8, it is a lie */
6492 if (is_codeset_name_UTF8(retval)) {
6499 /* Otherwise the code set name is considered to be everything between
6500 * the dot and the '@' */
6501 retval = save_to_buffer(retval, retbufp, retbuf_sizep);
6505 # endif /* ! WIN32 */
6506 # endif /* USE_LOCALE_CTYPE */
6508 } /* Giant switch() of nl_langinfo() items */
6510 restore_toggled_locale_i(cat_index, orig_switched_locale);
6512 # ifdef USE_LOCALE_CTYPE
6513 restore_toggled_locale_c(LC_CTYPE, orig_CTYPE_locale);
6517 *utf8ness = is_utf8;
6522 # endif /* All the implementations of my_langinfo() */
6524 /*--------------------------------------------------------------------------*/
6526 } /* my_langinfo() */
6528 #endif /* USE_LOCALE */
6531 =for apidoc_section $time
6532 =for apidoc sv_strftime_tm
6533 =for apidoc_item sv_strftime_ints
6534 =for apidoc_item my_strftime
6536 These implement the libc strftime(), but with a different API so that the return
6537 value is a pointer to the formatted result (which MUST be arranged to be FREED
6538 BY THE CALLER). This allows these functions to increase the buffer size as
6539 needed, so that the caller doesn't have to worry about that.
6541 On failure they return NULL, and set errno to C<EINVAL>.
6543 C<sv_strftime_tm> and C<sv_strftime_ints> are preferred, as they transparently
6544 handle the UTF-8ness of the current locale, the input C<fmt>, and the returned
6545 result. Only if the current C<LC_TIME> locale is a UTF-8 one (and S<C<use
6546 bytes>> is not in effect) will the result be marked as UTF-8. These differ
6547 only in the form of their inputs. C<sv_strftime_tm> takes a filled-in
6548 S<C<struct tm>> parameter. C<sv_strftime_ints> takes a bunch of integer
6549 parameters that together completely define a given time.
6551 C<my_strftime> is kept for backwards compatibility. Knowing if the result
6552 should be considered UTF-8 or not requires significant extra logic.
6554 Note that C<yday> and C<wday> effectively are ignored by C<sv_strftime_ints>
6555 and C<my_strftime>, as mini_mktime() overwrites them
6557 Also note that all three functions are always executed in the underlying
6558 C<LC_TIME> locale of the program, giving results based on that locale.
6564 S_ints_to_tm(pTHX_ struct tm * mytm,
6565 int sec, int min, int hour, int mday, int mon, int year,
6566 int wday, int yday, int isdst)
6568 /* Create a struct tm structure from the input time-related integer
6571 /* Override with the passed-in values */
6572 Zero(mytm, 1, struct tm);
6575 mytm->tm_hour = hour;
6576 mytm->tm_mday = mday;
6578 mytm->tm_year = year;
6579 mytm->tm_wday = wday;
6580 mytm->tm_yday = yday;
6581 mytm->tm_isdst = isdst;
6584 /* use libc to get the values for tm_gmtoff and tm_zone on platforms that
6585 * have them [perl #18238] */
6586 #if defined(HAS_MKTIME) \
6587 && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
6588 struct tm mytm2 = *mytm;
6592 # ifdef HAS_TM_TM_GMTOFF
6593 mytm->tm_gmtoff = mytm2.tm_gmtoff;
6595 # ifdef HAS_TM_TM_ZONE
6596 mytm->tm_zone = mytm2.tm_zone;
6604 S_strftime_tm(pTHX_ const char *fmt, const struct tm *mytm)
6606 PERL_ARGS_ASSERT_STRFTIME_TM;
6608 /* Execute strftime() based on the input struct tm */
6610 /* An empty format yields an empty result */
6611 const int fmtlen = strlen(fmt);
6614 Newxz (ret, 1, char);
6618 #ifndef HAS_STRFTIME
6619 Perl_croak(aTHX_ "panic: no strftime");
6621 # if defined(USE_LOCALE_CTYPE) && defined(USE_LOCALE_TIME)
6623 const char * orig_CTYPE_LOCALE = toggle_locale_c(LC_CTYPE,
6624 querylocale_c(LC_TIME));
6627 /* Guess an initial size for the returned string based on an expansion
6628 * factor of the input format, but with a minimum that should handle most
6629 * common cases. If this guess is too small, we will try again with a
6631 int bufsize = MAX(fmtlen * 2, 64);
6633 char *buf = NULL; /* Makes Renew() act as Newx() on the first iteration */
6635 Renew(buf, bufsize, char);
6637 /* allowing user-supplied (rather than literal) formats is normally
6638 * frowned upon as a potential security risk; but this is part of the
6639 * API so we have to allow it (and the available formats have a much
6640 * lower chance of doing something bad than the ones for printf etc. */
6641 GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
6644 int len = strftime(buf, bufsize, fmt, mytm);
6647 GCC_DIAG_RESTORE_STMT;
6649 /* A non-zero return indicates success. But to make sure we're not
6650 * dealing with some rogue strftime that returns how much space it
6651 * needs instead of 0 when there isn't enough, check that the return
6652 * indicates we have at least one byte of spare space (which will be
6653 * used for the terminating NUL). */
6654 if (inRANGE(len, 1, bufsize - 1)) {
6655 goto strftime_return;
6658 /* There are several possible reasons for a 0 return code for a
6659 * non-empty format, and they are not trivial to tease apart. This
6660 * issue is a known bug in the strftime() API. What we do to cope is
6661 * to assume that the reason is not enough space in the buffer, so
6662 * increase it and try again. */
6665 /* But don't just keep increasing the size indefinitely. Stop when it
6666 * becomes obvious that the reason for failure is something besides not
6667 * enough space. The most likely largest expanding format is %c. On
6668 * khw's Linux box, the maximum result of this is 67 characters, in the
6669 * km_KH locale. If a new script comes along that uses 4 UTF-8 bytes
6670 * per character, and with a similar expansion factor, that would be a
6671 * 268:2 byte ratio, or a bit more than 128:1 = 2**7:1. Some strftime
6672 * implementations allow you to say %1000c to pad to 1000 bytes. This
6673 * shows that it is impossible to implement this without a heuristic
6674 * (which can fail). But it indicates we need to be generous in the
6675 * upper limit before failing. The previous heuristic used was too
6676 * stingy. Since the size doubles per iteration, it doesn't take many
6677 * to reach the limit */
6678 } while (bufsize < ((1 << 11) + 1) * fmtlen);
6680 /* Here, strftime() returned 0, and it likely wasn't for lack of space.
6681 * There are two possible reasons:
6683 * First is that the result is legitimately 0 length. This can happen
6684 * when the format is precisely "%p". That is the only documented format
6685 * that can have an empty result. */
6686 if (strEQ(fmt, "%p")) {
6687 Renew(buf, 1, char);
6689 goto strftime_return;
6692 /* The other reason is that the format string is malformed. Probably it is
6693 * that the string is syntactically invalid for the locale. On some
6694 * platforms an invalid conversion specifier '%?' (for all illegal '?') is
6695 * treated as a literal, but others may fail when '?' is illegal */
6702 # if defined(USE_LOCALE_CTYPE) && defined(USE_LOCALE_TIME)
6704 restore_toggled_locale_c(LC_CTYPE, orig_CTYPE_LOCALE);
6715 S_strftime8(pTHX_ const char * fmt,
6716 const struct tm * mytm,
6717 const utf8ness_t fmt_utf8ness,
6718 utf8ness_t * result_utf8ness,
6719 const bool came_from_sv)
6721 PERL_ARGS_ASSERT_STRFTIME8;
6723 /* Wrap strftime_tm, taking into account the input and output UTF-8ness */
6725 #ifdef USE_LOCALE_TIME
6726 # define INDEX_TO_USE LC_TIME_INDEX_
6728 const char * locale = querylocale_c(LC_TIME);
6729 locale_utf8ness_t locale_utf8ness = LOCALE_UTF8NESS_UNKNOWN;
6732 # define INDEX_TO_USE LC_ALL_INDEX_ /* Effectively out of bounds */
6734 const char * locale = "C";
6735 locale_utf8ness_t locale_utf8ness = LOCALE_NOT_UTF8;
6739 switch (fmt_utf8ness) {
6740 case UTF8NESS_IMMATERIAL:
6743 case UTF8NESS_NO: /* Known not to be UTF-8; must not be UTF-8 locale */
6744 if (is_locale_utf8(locale)) {
6749 locale_utf8ness = LOCALE_NOT_UTF8;
6752 case UTF8NESS_YES: /* Known to be UTF-8; must be UTF-8 locale if can't
6753 downgrade. But downgrading assumes the locale
6754 is latin 1. Maybe just fail XXX */
6755 if (! is_locale_utf8(locale)) {
6756 locale_utf8ness = LOCALE_NOT_UTF8;
6758 bool is_utf8 = true;
6759 Size_t fmt_len = strlen(fmt);
6760 fmt = (char *) bytes_from_utf8((U8 *) fmt, &fmt_len, &is_utf8);
6769 locale_utf8ness = LOCALE_IS_UTF8;
6774 case UTF8NESS_UNKNOWN:
6775 if (! is_locale_utf8(locale)) {
6776 locale_utf8ness = LOCALE_NOT_UTF8;
6779 locale_utf8ness = LOCALE_IS_UTF8;
6782 /* Upgrade 'fmt' to UTF-8 for a UTF-8 locale. Otherwise the
6783 * locale would find any UTF-8 variant characters to be
6785 Size_t fmt_len = strlen(fmt);
6786 fmt = (char *) bytes_to_utf8((U8 *) fmt, &fmt_len);
6794 char * retval = strftime_tm(fmt, mytm);
6795 *result_utf8ness = get_locale_string_utf8ness_i(retval,
6799 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
6800 "fmt=%s, retval=%s; utf8ness=%d",
6802 ((is_utf8_string((U8 *) retval, 0))
6804 :_byte_dump_string((U8 *) retval, strlen(retval),0)),
6815 S_give_perl_locale_control(pTHX_
6817 const char * lc_all_string,
6819 const char ** locales,
6821 const line_t caller_line)
6823 PERL_UNUSED_ARG(caller_line);
6825 /* This is called when the program is in the global locale and are
6826 * switching to per-thread (if available). And it is called at
6827 * initialization time to do the same.
6830 # if defined(WIN32) && defined(USE_THREAD_SAFE_LOCALE)
6832 /* On Windows, convert to per-thread behavior. This isn't necessary in
6833 * POSIX 2008, as the conversion gets done automatically in the
6834 * void_setlocale_i() calls below. */
6835 if (_configthreadlocale(_ENABLE_PER_THREAD_LOCALE) == -1) {
6836 locale_panic_("_configthreadlocale returned an error");
6840 # if ! defined(USE_THREAD_SAFE_LOCALE) \
6841 && ! defined(USE_POSIX_2008_LOCALE)
6842 # if defined(LC_ALL)
6843 PERL_UNUSED_ARG(lc_all_string);
6845 PERL_UNUSED_ARG(locales);
6849 /* This platform has per-thread locale handling. Do the conversion. */
6851 # if defined(LC_ALL)
6853 void_setlocale_c_with_caller(LC_ALL, lc_all_string, __FILE__, caller_line);
6857 for_all_individual_category_indexes(i) {
6858 void_setlocale_i_with_caller(i, locales[i], __FILE__, caller_line);
6864 /* Finally, update our remaining records. 'true' => force recalculation.
6865 * This is needed because we don't know what's happened while Perl hasn't
6866 * had control, so we need to figure out the current state */
6868 # if defined(LC_ALL)
6870 new_LC_ALL(lc_all_string, true);
6874 new_LC_ALL(locales, true);
6880 S_output_check_environment_warning(pTHX_ const char * const language,
6881 const char * const lc_all,
6882 const char * const lang)
6884 PerlIO_printf(Perl_error_log,
6885 "perl: warning: Please check that your locale settings:\n");
6889 PerlIO_printf(Perl_error_log, "\tLANGUAGE = %c%s%c,\n",
6890 language ? '"' : '(',
6891 language ? language : "unset",
6892 language ? '"' : ')');
6894 PERL_UNUSED_ARG(language);
6897 PerlIO_printf(Perl_error_log, "\tLC_ALL = %c%s%c,\n",
6899 lc_all ? lc_all : "unset",
6900 lc_all ? '"' : ')');
6902 for_all_individual_category_indexes(i) {
6903 const char * value = PerlEnv_getenv(category_names[i]);
6904 PerlIO_printf(Perl_error_log,
6908 value ? value : "unset",
6912 PerlIO_printf(Perl_error_log, "\tLANG = %c%s%c\n",
6914 lang ? lang : "unset",
6916 PerlIO_printf(Perl_error_log,
6917 " are supported and installed on your system.\n");
6922 /* A helper macro for the next function. Needed because would be called in two
6923 * places. Knows about the internal workings of the function */
6924 #define GET_DESCRIPTION(trial, name) \
6925 ((isNAME_C_OR_POSIX(name)) \
6926 ? "the standard locale" \
6927 : ((trial == (system_default_trial) \
6928 ? "the system default locale" \
6929 : "a fallback locale")))
6932 * Initialize locale awareness.
6935 Perl_init_i18nl10n(pTHX_ int printwarn)
6938 * 0 if not to output warning when setup locale is bad
6939 * 1 if to output warning based on value of PERL_BADLANG
6940 * >1 if to output regardless of PERL_BADLANG
6943 * 1 = set ok or not applicable,
6944 * 0 = fallback to a locale of lower priority
6945 * -1 = fallback to all locales failed, not even to the C locale
6947 * Under -DDEBUGGING, if the environment variable PERL_DEBUG_LOCALE_INIT is
6948 * set, debugging information is output.
6950 * This routine effectively does the following in most cases:
6952 * basic initialization;
6953 * asserts that the compiled tables are consistent;
6954 * initialize data structures;
6955 * make sure we are in the global locale;
6956 * setlocale(LC_ALL, "");
6957 * switch to per-thread locale if applicable;
6959 * The "" causes the locale to be set to what the environment variables at
6960 * the time say it should be.
6962 * To handle possible failures, the setlocale is expanded to be like:
6964 * trial_locale = pre-first-trial;
6965 * while (has_another_trial()) {
6966 * trial_locale = next_trial();
6967 * if setlocale(LC_ALL, trial_locale) {
6972 * had_failure = true;
6976 * if (had_failure) {
6978 * if (! ok) warn_still_more();
6981 * The first trial is either:
6982 * "" to examine the environment variables for the locale
6983 * NULL to use the values already set for the locale by the program
6984 * embedding this perl instantiation.
6986 * Something is wrong if this trial fails, but there is a sequence of
6987 * fallbacks to try should that happen. They are given in the enum below.
6989 * If there is no LC_ALL defined on the system, the setlocale() above is
6990 * replaced by a loop setting each individual category separately.
6992 * In a non-embeded environment, this code is executed exactly once. It
6993 * sets up the global locale environment. At the end, if some sort of
6994 * thread-safety is in effect, it will turn thread 0 into using that, with
6995 * the same locale as the global initially. thread 0 can then change its
6996 * locale at will without affecting the global one.
6998 * At destruction time, thread 0 will revert to the global locale as the
6999 * other threads die.
7001 * Care must be taken in an embedded environment. This code will be
7002 * executed for each instantiation. Since it changes the global locale, it
7003 * could clash with another running instantiation that isn't using
7004 * per-thread locales. perlembed suggests having the controlling program
7005 * set each instantiation's locale and set PERL_SKIP_LOCALE_INIT so this
7006 * code uses that without actually changing anything. Then the onus is on
7007 * the controlling program to prevent any races. The code below does
7008 * enough locking so as to prevent system calls from overwriting data
7009 * before it is safely copied here, but that isn't a general solution.
7014 PERL_UNUSED_ARG(printwarn);
7017 #else /* USE_LOCALE to near the end of the routine */
7023 const char * const language = PerlEnv_getenv("LANGUAGE");
7026 const char * const language = NULL; /* Unused placeholder */
7029 /* A later getenv() could zap this, so only use here */
7030 const char * const bad_lang_use_once = PerlEnv_getenv("PERL_BADLANG");
7032 const bool locwarn = (printwarn > 1
7034 && ( ! bad_lang_use_once
7036 /* disallow with "" or "0" */
7038 && strNE("0", bad_lang_use_once)))));
7041 # define DEBUG_LOCALE_INIT(a,b,c)
7044 DEBUG_INITIALIZATION_set(cBOOL(PerlEnv_getenv("PERL_DEBUG_LOCALE_INIT")));
7046 # define DEBUG_LOCALE_INIT(cat_index, locale, result) \
7047 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s\n", \
7048 setlocale_debug_string_i(cat_index, locale, result)));
7051 assert(categories[LC_ALL_INDEX_] == LC_ALL);
7052 assert(strEQ(category_names[LC_ALL_INDEX_], "LC_ALL"));
7053 # ifdef USE_POSIX_2008_LOCALE
7054 assert(category_masks[LC_ALL_INDEX_] == LC_ALL_MASK);
7058 for_all_individual_category_indexes(i) {
7059 assert(category_name_lengths[i] == strlen(category_names[i]));
7062 # endif /* DEBUGGING */
7064 /* Initialize the per-thread mbrFOO() state variables. See POSIX.xs for
7065 * why these particular incantations are used. */
7067 memzero(&PL_mbrlen_ps, sizeof(PL_mbrlen_ps));
7070 memzero(&PL_mbrtowc_ps, sizeof(PL_mbrtowc_ps));
7073 wcrtomb(NULL, L'\0', &PL_wcrtomb_ps);
7075 # ifdef USE_PL_CURLOCALES
7077 for (unsigned int i = 0; i <= LC_ALL_INDEX_; i++) {
7078 PL_curlocales[i] = savepv("C");
7082 # ifdef USE_PL_CUR_LC_ALL
7084 PL_cur_LC_ALL = savepv("C");
7087 # if ! defined(PERL_LC_ALL_USES_NAME_VALUE_PAIRS) && defined(LC_ALL)
7091 /* If we haven't done so already, translate the LC_ALL positions of
7092 * categories into our internal indices. */
7093 if (map_LC_ALL_position_to_index[0] == LC_ALL_INDEX_) {
7095 /* Use this array, initialized by a config.h constant */
7096 int lc_all_category_positions[] = PERL_LC_ALL_CATEGORY_POSITIONS_INIT;
7097 STATIC_ASSERT_STMT( C_ARRAY_LENGTH(lc_all_category_positions)
7100 for (unsigned int i = 0;
7101 i < C_ARRAY_LENGTH(lc_all_category_positions);
7104 map_LC_ALL_position_to_index[i] =
7105 get_category_index(lc_all_category_positions[i]);
7112 # ifdef USE_POSIX_2008_LOCALE
7114 /* This is a global, so be sure to keep another instance from zapping it */
7116 if (PL_C_locale_obj) {
7120 PL_C_locale_obj = newlocale(LC_ALL_MASK, "C", (locale_t) 0);
7121 if (! PL_C_locale_obj) {
7123 locale_panic_(Perl_form(aTHX_
7124 "Cannot create POSIX 2008 C locale object"));
7128 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "created C object %p\n",
7132 /* Switch to using the POSIX 2008 interface now. This would happen below
7133 * anyway, but deferring it can lead to leaks of memory that would also get
7134 * malloc'd in the interim. We arbitrarily switch to the C locale,
7135 * overridden below */
7136 if (! uselocale(PL_C_locale_obj)) {
7137 locale_panic_(Perl_form(aTHX_
7138 "Can't uselocale(%p), LC_ALL supposed to"
7143 # ifdef MULTIPLICITY
7145 PL_cur_locale_obj = PL_C_locale_obj;
7150 /* Now initialize some data structures. This is entirely so that
7151 * later-executed code doesn't have to concern itself with things not being
7152 * initialized. Arbitrarily use the C locale (which we know has to exist
7153 * on the system). */
7155 # ifdef USE_LOCALE_NUMERIC
7157 PL_numeric_radix_sv = newSV(1);
7158 PL_underlying_radix_sv = newSV(1);
7159 Newxz(PL_numeric_name, 1, char); /* Single NUL character */
7162 # ifdef USE_LOCALE_COLLATE
7164 Newxz(PL_collation_name, 1, char);
7167 # ifdef USE_LOCALE_CTYPE
7169 Newxz(PL_ctype_name, 1, char);
7173 new_LC_ALL("C", true /* Don't shortcut */);
7175 /*===========================================================================*/
7177 /* Now ready to override the initialization with the values that the user
7178 * wants. This is done in the global locale as explained in the
7179 * introductory comments to this function */
7180 switch_to_global_locale();
7182 const char * const lc_all = PerlEnv_getenv("LC_ALL");
7183 const char * const lang = PerlEnv_getenv("LANG");
7185 /* We try each locale in the enum, in order, until we get one that works,
7186 * or exhaust the list. Normally the loop is executed just once.
7188 * Each enum value is +1 from the previous */
7191 environment_trial = 0, /* "" or NULL; code below assumes value
7192 0 is the first real trial */
7193 LC_ALL_trial, /* ENV{LC_ALL} */
7194 LANG_trial, /* ENV{LANG} */
7195 system_default_trial, /* Windows .ACP */
7196 C_trial, /* C locale */
7201 SSize_t already_checked = 0;
7202 const char * checked[C_trial];
7205 const char * lc_all_string;
7207 const char * curlocales[LC_ALL_INDEX_];
7210 /* Loop through the initial setting and all the possible fallbacks,
7211 * breaking out of the loop on success */
7212 trial = dummy_trial;
7213 while (trial != beyond_final_trial) {
7215 /* Each time through compute the next trial to use based on the one in
7216 * the previous iteration and switch to the new one. This enforces the
7217 * order in which the fallbacks are applied */
7219 trial = (trials) ((int) trial + 1); /* Casts are needed for g++ */
7221 const char * locale = NULL;
7223 /* Set up the parameters for this trial */
7226 locale_panic_("Unexpectedly got 'dummy_trial");
7229 case environment_trial:
7230 /* This is either "" to get the values from the environment, or
7231 * NULL if the calling program has initialized the values already.
7233 locale = (PerlEnv_getenv("PERL_SKIP_LOCALE_INIT"))
7239 if (! lc_all || strEQ(lc_all, "")) {
7240 continue; /* No-op */
7247 if (! lang || strEQ(lang, "")) {
7248 continue; /* No-op */
7254 case system_default_trial:
7256 # if ! defined(WIN32) || ! defined(LC_ALL)
7258 continue; /* No-op */
7261 /* For Windows, we also try the system default locale before "C".
7262 * (If there exists a Windows without LC_ALL we skip this because
7263 * it gets too complicated. For those, "C" is the next fallback
7273 case beyond_final_trial:
7274 continue; /* No-op, causes loop to exit */
7277 /* If the locale is a substantive name, don't try the same locale
7279 if (locale && strNE(locale, "")) {
7280 for (unsigned int i = 0; i < already_checked; i++) {
7281 if (strEQ(checked[i], locale)) {
7286 /* And, for future iterations, indicate we've tried this locale */
7287 checked[already_checked] = savepv(locale);
7288 SAVEFREEPV(checked[already_checked]);
7294 STDIZED_SETLOCALE_LOCK;
7295 lc_all_string = savepv(stdized_setlocale(LC_ALL, locale));
7296 STDIZED_SETLOCALE_UNLOCK;
7298 DEBUG_LOCALE_INIT(LC_ALL_INDEX_, locale, lc_all_string);
7300 if (LIKELY(lc_all_string)) { /* Succeeded */
7305 if (trial == 0 && locwarn) {
7306 PerlIO_printf(Perl_error_log,
7307 "perl: warning: Setting locale failed.\n");
7308 output_check_environment_warning(language, lc_all, lang);
7311 # else /* Below is ! LC_ALL */
7313 bool setlocale_failure = FALSE; /* This trial hasn't failed so far */
7314 bool dowarn = trial == 0 && locwarn;
7316 for_all_individual_category_indexes(j) {
7317 STDIZED_SETLOCALE_LOCK;
7318 curlocales[j] = savepv(stdized_setlocale(categories[j], locale));
7319 STDIZED_SETLOCALE_UNLOCK;
7321 DEBUG_LOCALE_INIT(j, locale, curlocales[j]);
7323 if (UNLIKELY(! curlocales[j])) {
7324 setlocale_failure = TRUE;
7326 /* If are going to warn below, continue to loop so all failures
7327 * are included in the message */
7334 if (LIKELY(! setlocale_failure)) { /* All succeeded */
7336 break; /* Exit trial_locales loop */
7339 /* Here, this trial failed */
7342 PerlIO_printf(Perl_error_log,
7343 "perl: warning: Setting locale failed for the categories:\n");
7345 for_all_individual_category_indexes(j) {
7346 if (! curlocales[j]) {
7347 PerlIO_printf(Perl_error_log, "\t%s\n", category_names[j]);
7351 output_check_environment_warning(language, lc_all, lang);
7352 } /* end of warning on first failure */
7354 # endif /* LC_ALL */
7356 } /* end of looping through the trial locales */
7358 /* If we had to do more than the first trial, it means that one failed, and
7359 * we may need to output a warning, and, if none worked, do more */
7360 if (UNLIKELY(trial != 0)) {
7362 const char * description = "a fallback locale";
7363 const char * name = NULL;;
7365 /* If we didn't find a good fallback, list all we tried */
7366 if (! ok && already_checked > 0) {
7367 PerlIO_printf(Perl_error_log, "perl: warning: Failed to fall"
7369 if (already_checked > 1) { /* more than one was tried */
7370 PerlIO_printf(Perl_error_log, "any of:\n");
7373 while (already_checked > 0) {
7374 name = checked[--already_checked];
7375 description = GET_DESCRIPTION(trial, name);
7376 PerlIO_printf(Perl_error_log, "%s (\"%s\")\n",
7383 /* Here, a fallback worked. So we have saved its name, and the
7384 * trial that succeeded is still valid */
7386 const char * individ_locales[LC_ALL_INDEX_] = { NULL };
7388 /* Even though we know the valid string for LC_ALL that worked,
7389 * translate it into our internal format, which is the
7390 * name=value pairs notation. This is easier for a human to
7391 * decipher than the positional notation. Some platforms
7392 * can return "C C C C C C" for LC_ALL. This code also
7393 * standardizes that result into plain "C". */
7394 switch (parse_LC_ALL_string(lc_all_string,
7395 (const char **) &individ_locales,
7397 false, /* Return only [0] if
7399 false, /* Don't panic on error */
7404 /* Here, the parse failed, which shouldn't happen, but if
7405 * it does, we have an easy fallback that allows us to keep
7407 name = lc_all_string;
7410 case no_array: /* The original is a single locale */
7411 name = lc_all_string;
7414 case only_element_0: /* element[0] is a single locale valid
7415 for all categories */
7416 SAVEFREEPV(individ_locales[0]);
7417 name = individ_locales[0];
7421 name = calculate_LC_ALL_string(individ_locales,
7425 for_all_individual_category_indexes(j) {
7426 Safefree(individ_locales[j]);
7430 name = calculate_LC_ALL_string(curlocales,
7435 description = GET_DESCRIPTION(trial, name);
7439 /* Nothing seems to be working, yet we want to continue
7440 * executing. It may well be that locales are mostly
7441 * irrelevant to this particular program, and there must be
7442 * some locale underlying the program. Figure it out as best
7443 * we can, by querying the system's current locale */
7447 STDIZED_SETLOCALE_LOCK;
7448 name = stdized_setlocale(LC_ALL, NULL);
7449 STDIZED_SETLOCALE_UNLOCK;
7451 if (UNLIKELY(! name)) {
7452 name = "locale name not determinable";
7455 # else /* Below is ! LC_ALL */
7457 const char * system_locales[LC_ALL_INDEX_] = { NULL };
7459 for_all_individual_category_indexes(j) {
7460 STDIZED_SETLOCALE_LOCK;
7461 system_locales[j] = savepv(stdized_setlocale(categories[j],
7463 STDIZED_SETLOCALE_UNLOCK;
7465 if (UNLIKELY(! system_locales[j])) {
7466 system_locales[j] = "not determinable";
7470 /* We use the name=value form for the string, as that is more
7471 * human readable than the positional notation */
7472 name = calculate_LC_ALL_string(system_locales,
7476 description = "what the system says";
7478 for_all_individual_category_indexes(j) {
7479 Safefree(system_locales[j]);
7484 PerlIO_printf(Perl_error_log,
7485 "perl: warning: Falling back to %s (\"%s\").\n",
7488 /* Here, ok being true indicates that the first attempt failed, but
7489 * a fallback succeeded; false => nothing working. Translate to
7490 * API return values. */
7497 give_perl_locale_control(lc_all_string, __LINE__);
7498 Safefree(lc_all_string);
7502 give_perl_locale_control((const char **) &curlocales, __LINE__);
7504 for_all_individual_category_indexes(j) {
7505 Safefree(curlocales[j]);
7509 # if defined(USE_PERLIO) && defined(USE_LOCALE_CTYPE)
7511 /* Set PL_utf8locale to TRUE if using PerlIO _and_ the current LC_CTYPE
7512 * locale is UTF-8. give_perl_locale_control() just above has already
7513 * calculated the latter value and saved it in PL_in_utf8_CTYPE_locale. If
7514 * both PL_utf8locale and PL_unicode (set by -C or by $ENV{PERL_UNICODE})
7515 * are true, perl.c:S_parse_body() will turn on the PerlIO :utf8 layer on
7516 * STDIN, STDOUT, STDERR, _and_ the default open discipline. */
7517 PL_utf8locale = PL_in_utf8_CTYPE_locale;
7519 /* Set PL_unicode to $ENV{PERL_UNICODE} if using PerlIO.
7520 This is an alternative to using the -C command line switch
7521 (the -C if present will override this). */
7523 const char *p = PerlEnv_getenv("PERL_UNICODE");
7524 PL_unicode = p ? parse_unicode_opts(&p) : 0;
7525 if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
7530 # if defined(USE_POSIX_2008_LOCALE) && defined(MULTIPLICITY)
7531 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
7532 "finished Perl_init_i18nl10n; actual obj=%p,"
7533 " expected obj=%p, initial=%s\n",
7534 uselocale(0), PL_cur_locale_obj,
7535 get_LC_ALL_display()));
7538 /* So won't continue to output stuff */
7539 DEBUG_INITIALIZATION_set(FALSE);
7541 #endif /* USE_LOCALE */
7546 #undef GET_DESCRIPTION
7547 #ifdef USE_LOCALE_COLLATE
7550 S_compute_collxfrm_coefficients(pTHX)
7553 /* A locale collation definition includes primary, secondary, tertiary,
7554 * etc. weights for each character. To sort, the primary weights are used,
7555 * and only if they compare equal, then the secondary weights are used, and
7556 * only if they compare equal, then the tertiary, etc.
7558 * strxfrm() works by taking the input string, say ABC, and creating an
7559 * output transformed string consisting of first the primary weights,
7560 * A¹B¹C¹ followed by the secondary ones, A²B²C²; and then the tertiary,
7561 * etc, yielding A¹B¹C¹ A²B²C² A³B³C³ .... Some characters may not have
7562 * weights at every level. In our example, let's say B doesn't have a
7563 * tertiary weight, and A doesn't have a secondary weight. The constructed
7564 * string is then going to be
7565 * A¹B¹C¹ B²C² A³C³ ....
7566 * This has the desired effect that strcmp() will look at the secondary or
7567 * tertiary weights only if the strings compare equal at all higher
7568 * priority weights. The spaces shown here, like in
7570 * are not just for readability. In the general case, these must actually
7571 * be bytes, which we will call here 'separator weights'; and they must be
7572 * smaller than any other weight value, but since these are C strings, only
7573 * the terminating one can be a NUL (some implementations may include a
7574 * non-NUL separator weight just before the NUL). Implementations tend to
7575 * reserve 01 for the separator weights. They are needed so that a shorter
7576 * string's secondary weights won't be misconstrued as primary weights of a
7577 * longer string, etc. By making them smaller than any other weight, the
7578 * shorter string will sort first. (Actually, if all secondary weights are
7579 * smaller than all primary ones, there is no need for a separator weight
7580 * between those two levels, etc.)
7582 * The length of the transformed string is roughly a linear function of the
7583 * input string. It's not exactly linear because some characters don't
7584 * have weights at all levels. When we call strxfrm() we have to allocate
7585 * some memory to hold the transformed string. The calculations below try
7586 * to find coefficients 'm' and 'b' for this locale so that m*x + b equals
7587 * how much space we need, given the size of the input string in 'x'. If
7588 * we calculate too small, we increase the size as needed, and call
7589 * strxfrm() again, but it is better to get it right the first time to
7590 * avoid wasted expensive string transformations.
7592 * We use the string below to find how long the transformation of it is.
7593 * Almost all locales are supersets of ASCII, or at least the ASCII
7594 * letters. We use all of them, half upper half lower, because if we used
7595 * fewer, we might hit just the ones that are outliers in a particular
7596 * locale. Most of the strings being collated will contain a preponderance
7597 * of letters, and even if they are above-ASCII, they are likely to have
7598 * the same number of weight levels as the ASCII ones. It turns out that
7599 * digits tend to have fewer levels, and some punctuation has more, but
7600 * those are relatively sparse in text, and khw believes this gives a
7601 * reasonable result, but it could be changed if experience so dictates. */
7602 const char longer[] = "ABCDEFGHIJKLMnopqrstuvwxyz";
7603 char * x_longer; /* Transformed 'longer' */
7604 Size_t x_len_longer; /* Length of 'x_longer' */
7606 char * x_shorter; /* We also transform a substring of 'longer' */
7607 Size_t x_len_shorter;
7609 PL_in_utf8_COLLATE_locale = (PL_collation_standard)
7611 : is_locale_utf8(PL_collation_name);
7612 PL_strxfrm_NUL_replacement = '\0';
7613 PL_strxfrm_max_cp = 0;
7615 /* mem_collxfrm_() is used get the transformation (though here we are
7616 * interested only in its length). It is used because it has the
7617 * intelligence to handle all cases, but to work, it needs some values of
7618 * 'm' and 'b' to get it started. For the purposes of this calculation we
7619 * use a very conservative estimate of 'm' and 'b'. This assumes a weight
7620 * can be multiple bytes, enough to hold any UV on the platform, and there
7621 * are 5 levels, 4 weight bytes, and a trailing NUL. */
7622 PL_collxfrm_base = 5;
7623 PL_collxfrm_mult = 5 * sizeof(UV);
7625 /* Find out how long the transformation really is */
7626 x_longer = mem_collxfrm_(longer,
7630 /* We avoid converting to UTF-8 in the called
7631 * function by telling it the string is in UTF-8
7632 * if the locale is a UTF-8 one. Since the string
7633 * passed here is invariant under UTF-8, we can
7634 * claim it's UTF-8 even if it isn't. */
7635 PL_in_utf8_COLLATE_locale);
7638 /* Find out how long the transformation of a substring of 'longer' is.
7639 * Together the lengths of these transformations are sufficient to
7640 * calculate 'm' and 'b'. The substring is all of 'longer' except the
7641 * first character. This minimizes the chances of being swayed by outliers
7643 x_shorter = mem_collxfrm_(longer + 1,
7646 PL_in_utf8_COLLATE_locale);
7647 Safefree(x_shorter);
7649 /* If the results are nonsensical for this simple test, the whole locale
7650 * definition is suspect. Mark it so that locale collation is not active
7651 * at all for it. XXX Should we warn? */
7652 if ( x_len_shorter == 0
7653 || x_len_longer == 0
7654 || x_len_shorter >= x_len_longer)
7656 PL_collxfrm_mult = 0;
7657 PL_collxfrm_base = 1;
7658 DEBUG_L(PerlIO_printf(Perl_debug_log,
7659 "Disabling locale collation for LC_COLLATE='%s';"
7660 " length for shorter sample=%zu; longer=%zu\n",
7661 PL_collation_name, x_len_shorter, x_len_longer));
7664 SSize_t base; /* Temporary */
7666 /* We have both: m * strlen(longer) + b = x_len_longer
7667 * m * strlen(shorter) + b = x_len_shorter;
7668 * subtracting yields:
7669 * m * (strlen(longer) - strlen(shorter))
7670 * = x_len_longer - x_len_shorter
7671 * But we have set things up so that 'shorter' is 1 byte smaller than
7673 * m = x_len_longer - x_len_shorter
7675 * But if something went wrong, make sure the multiplier is at least 1.
7677 if (x_len_longer > x_len_shorter) {
7678 PL_collxfrm_mult = (STRLEN) x_len_longer - x_len_shorter;
7681 PL_collxfrm_mult = 1;
7686 * but in case something has gone wrong, make sure it is non-negative
7688 base = x_len_longer - PL_collxfrm_mult * (sizeof(longer) - 1);
7693 /* Add 1 for the trailing NUL */
7694 PL_collxfrm_base = base + 1;
7697 DEBUG_L(PerlIO_printf(Perl_debug_log,
7698 "?UTF-8 locale=%d; x_len_shorter=%zu, "
7700 " collate multipler=%zu, collate base=%zu\n",
7701 PL_in_utf8_COLLATE_locale,
7702 x_len_shorter, x_len_longer,
7703 PL_collxfrm_mult, PL_collxfrm_base));
7707 Perl_mem_collxfrm_(pTHX_ const char *input_string,
7708 STRLEN len, /* Length of 'input_string' */
7709 STRLEN *xlen, /* Set to length of returned string
7710 (not including the collation index
7712 bool utf8 /* Is the input in UTF-8? */
7715 /* mem_collxfrm_() is like strxfrm() but with two important differences.
7716 * First, it handles embedded NULs. Second, it allocates a bit more memory
7717 * than needed for the transformed data itself. The real transformed data
7718 * begins at offset COLLXFRM_HDR_LEN. *xlen is set to the length of that,
7719 * and doesn't include the collation index size.
7721 * It is the caller's responsibility to eventually free the memory returned
7724 * Please see sv_collxfrm() to see how this is used. */
7726 # define COLLXFRM_HDR_LEN sizeof(PL_collation_ix)
7728 char * s = (char *) input_string;
7729 STRLEN s_strlen = strlen(input_string);
7731 STRLEN xAlloc; /* xalloc is a reserved word in VC */
7732 STRLEN length_in_chars;
7733 bool first_time = TRUE; /* Cleared after first loop iteration */
7735 # ifdef USE_LOCALE_CTYPE
7736 const char * orig_CTYPE_locale = NULL;
7739 # if defined(USE_POSIX_2008_LOCALE) && defined HAS_STRXFRM_L
7740 locale_t constructed_locale = (locale_t) 0;
7743 PERL_ARGS_ASSERT_MEM_COLLXFRM_;
7745 /* Must be NUL-terminated */
7746 assert(*(input_string + len) == '\0');
7748 if (PL_collxfrm_mult == 0) { /* unknown or bad */
7749 if (PL_collxfrm_base != 0) { /* bad collation => skip */
7750 DEBUG_L(PerlIO_printf(Perl_debug_log,
7751 "mem_collxfrm_: locale's collation is defective\n"));
7755 /* (mult, base) == (0,0) means we need to calculate mult and base
7756 * before proceeding */
7757 S_compute_collxfrm_coefficients(aTHX);
7760 /* Replace any embedded NULs with the control that sorts before any others.
7761 * This will give as good as possible results on strings that don't
7762 * otherwise contain that character, but otherwise there may be
7763 * less-than-perfect results with that character and NUL. This is
7764 * unavoidable unless we replace strxfrm with our own implementation. */
7765 if (UNLIKELY(s_strlen < len)) { /* Only execute if there is an embedded
7769 STRLEN sans_nuls_len;
7770 int try_non_controls;
7771 char this_replacement_char[] = "?\0"; /* Room for a two-byte string,
7772 making sure 2nd byte is NUL.
7774 STRLEN this_replacement_len;
7776 /* If we don't know what non-NUL control character sorts lowest for
7777 * this locale, find it */
7778 if (PL_strxfrm_NUL_replacement == '\0') {
7780 char * cur_min_x = NULL; /* The min_char's xfrm, (except it also
7781 includes the collation index
7784 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "Looking to replace NUL\n"));
7786 /* Unlikely, but it may be that no control will work to replace
7787 * NUL, in which case we instead look for any character. Controls
7788 * are preferred because collation order is, in general, context
7789 * sensitive, with adjoining characters affecting the order, and
7790 * controls are less likely to have such interactions, allowing the
7791 * NUL-replacement to stand on its own. (Another way to look at it
7792 * is to imagine what would happen if the NUL were replaced by a
7793 * combining character; it wouldn't work out all that well.) */
7794 for (try_non_controls = 0;
7795 try_non_controls < 2;
7799 # ifdef USE_LOCALE_CTYPE
7801 /* In this case we use isCNTRL_LC() below, which relies on
7802 * LC_CTYPE, so that must be switched to correspond with the
7803 * LC_COLLATE locale */
7804 if (! try_non_controls && ! PL_in_utf8_COLLATE_locale) {
7805 orig_CTYPE_locale = toggle_locale_c(LC_CTYPE,
7809 /* Look through all legal code points (NUL isn't) */
7810 for (j = 1; j < 256; j++) {
7811 char * x; /* j's xfrm plus collation index */
7812 STRLEN x_len; /* length of 'x' */
7813 STRLEN trial_len = 1;
7814 char cur_source[] = { '\0', '\0' };
7816 /* Skip non-controls the first time through the loop. The
7817 * controls in a UTF-8 locale are the L1 ones */
7818 if (! try_non_controls && (PL_in_utf8_COLLATE_locale)
7825 /* Create a 1-char string of the current code point */
7826 cur_source[0] = (char) j;
7828 /* Then transform it */
7829 x = mem_collxfrm_(cur_source, trial_len, &x_len,
7830 0 /* The string is not in UTF-8 */);
7832 /* Ignore any character that didn't successfully transform.
7838 /* If this character's transformation is lower than
7839 * the current lowest, this one becomes the lowest */
7840 if ( cur_min_x == NULL
7841 || strLT(x + COLLXFRM_HDR_LEN,
7842 cur_min_x + COLLXFRM_HDR_LEN))
7844 PL_strxfrm_NUL_replacement = j;
7845 Safefree(cur_min_x);
7851 } /* end of loop through all 255 characters */
7853 # ifdef USE_LOCALE_CTYPE
7854 restore_toggled_locale_c(LC_CTYPE, orig_CTYPE_locale);
7857 /* Stop looking if found */
7862 /* Unlikely, but possible, if there aren't any controls that
7863 * work in the locale, repeat the loop, looking for any
7864 * character that works */
7865 DEBUG_L(PerlIO_printf(Perl_debug_log,
7866 "mem_collxfrm_: No control worked. Trying non-controls\n"));
7867 } /* End of loop to try first the controls, then any char */
7870 DEBUG_L(PerlIO_printf(Perl_debug_log,
7871 "mem_collxfrm_: Couldn't find any character to replace"
7872 " embedded NULs in locale %s with", PL_collation_name));
7876 DEBUG_L(PerlIO_printf(Perl_debug_log,
7877 "mem_collxfrm_: Replacing embedded NULs in locale %s with "
7878 "0x%02X\n", PL_collation_name, PL_strxfrm_NUL_replacement));
7880 Safefree(cur_min_x);
7881 } /* End of determining the character that is to replace NULs */
7883 /* If the replacement is variant under UTF-8, it must match the
7884 * UTF8-ness of the original */
7885 if ( ! UVCHR_IS_INVARIANT(PL_strxfrm_NUL_replacement) && utf8) {
7886 this_replacement_char[0] =
7887 UTF8_EIGHT_BIT_HI(PL_strxfrm_NUL_replacement);
7888 this_replacement_char[1] =
7889 UTF8_EIGHT_BIT_LO(PL_strxfrm_NUL_replacement);
7890 this_replacement_len = 2;
7893 this_replacement_char[0] = PL_strxfrm_NUL_replacement;
7894 /* this_replacement_char[1] = '\0' was done at initialization */
7895 this_replacement_len = 1;
7898 /* The worst case length for the replaced string would be if every
7899 * character in it is NUL. Multiply that by the length of each
7900 * replacement, and allow for a trailing NUL */
7901 sans_nuls_len = (len * this_replacement_len) + 1;
7902 Newx(sans_nuls, sans_nuls_len, char);
7905 /* Replace each NUL with the lowest collating control. Loop until have
7906 * exhausted all the NULs */
7907 while (s + s_strlen < e) {
7908 my_strlcat(sans_nuls, s, sans_nuls_len);
7910 /* Do the actual replacement */
7911 my_strlcat(sans_nuls, this_replacement_char, sans_nuls_len);
7913 /* Move past the input NUL */
7915 s_strlen = strlen(s);
7918 /* And add anything that trails the final NUL */
7919 my_strlcat(sans_nuls, s, sans_nuls_len);
7921 /* Switch so below we transform this modified string */
7924 } /* End of replacing NULs */
7926 /* Make sure the UTF8ness of the string and locale match */
7927 if (utf8 != PL_in_utf8_COLLATE_locale) {
7928 /* XXX convert above Unicode to 10FFFF? */
7929 const char * const t = s; /* Temporary so we can later find where the
7932 /* Here they don't match. Change the string's to be what the locale is
7935 if (! utf8) { /* locale is UTF-8, but input isn't; upgrade the input */
7936 s = (char *) bytes_to_utf8((const U8 *) s, &len);
7939 else { /* locale is not UTF-8; but input is; downgrade the input */
7941 s = (char *) bytes_from_utf8((const U8 *) s, &len, &utf8);
7943 /* If the downgrade was successful we are done, but if the input
7944 * contains things that require UTF-8 to represent, have to do
7945 * damage control ... */
7946 if (UNLIKELY(utf8)) {
7948 /* What we do is construct a non-UTF-8 string with
7949 * 1) the characters representable by a single byte converted
7950 * to be so (if necessary);
7951 * 2) and the rest converted to collate the same as the
7952 * highest collating representable character. That makes
7953 * them collate at the end. This is similar to how we
7954 * handle embedded NULs, but we use the highest collating
7955 * code point instead of the smallest. Like the NUL case,
7956 * this isn't perfect, but is the best we can reasonably
7957 * do. Every above-255 code point will sort the same as
7958 * the highest-sorting 0-255 code point. If that code
7959 * point can combine in a sequence with some other code
7960 * points for weight calculations, us changing something to
7961 * be it can adversely affect the results. But in most
7962 * cases, it should work reasonably. And note that this is
7963 * really an illegal situation: using code points above 255
7964 * on a locale where only 0-255 are valid. If two strings
7965 * sort entirely equal, then the sort order for the
7966 * above-255 code points will be in code point order. */
7970 /* If we haven't calculated the code point with the maximum
7971 * collating order for this locale, do so now */
7972 if (! PL_strxfrm_max_cp) {
7975 /* The current transformed string that collates the
7976 * highest (except it also includes the prefixed collation
7978 char * cur_max_x = NULL;
7980 /* Look through all legal code points (NUL isn't) */
7981 for (j = 1; j < 256; j++) {
7984 char cur_source[] = { '\0', '\0' };
7986 /* Create a 1-char string of the current code point */
7987 cur_source[0] = (char) j;
7989 /* Then transform it */
7990 x = mem_collxfrm_(cur_source, 1, &x_len, FALSE);
7992 /* If something went wrong (which it shouldn't), just
7993 * ignore this code point */
7998 /* If this character's transformation is higher than
7999 * the current highest, this one becomes the highest */
8000 if ( cur_max_x == NULL
8001 || strGT(x + COLLXFRM_HDR_LEN,
8002 cur_max_x + COLLXFRM_HDR_LEN))
8004 PL_strxfrm_max_cp = j;
8005 Safefree(cur_max_x);
8014 DEBUG_L(PerlIO_printf(Perl_debug_log,
8015 "mem_collxfrm_: Couldn't find any character to"
8016 " replace above-Latin1 chars in locale %s with",
8017 PL_collation_name));
8021 DEBUG_L(PerlIO_printf(Perl_debug_log,
8022 "mem_collxfrm_: highest 1-byte collating character"
8023 " in locale %s is 0x%02X\n",
8025 PL_strxfrm_max_cp));
8027 Safefree(cur_max_x);
8030 /* Here we know which legal code point collates the highest.
8031 * We are ready to construct the non-UTF-8 string. The length
8032 * will be at least 1 byte smaller than the input string
8033 * (because we changed at least one 2-byte character into a
8034 * single byte), but that is eaten up by the trailing NUL */
8040 char * e = (char *) t + len;
8042 for (i = 0; i < len; i+= UTF8SKIP(t + i)) {
8044 if (UTF8_IS_INVARIANT(cur_char)) {
8047 else if (UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(t + i, e)) {
8048 s[d++] = EIGHT_BIT_UTF8_TO_NATIVE(cur_char, t[i+1]);
8050 else { /* Replace illegal cp with highest collating
8052 s[d++] = PL_strxfrm_max_cp;
8056 Renew(s, d, char); /* Free up unused space */
8061 /* Here, we have constructed a modified version of the input. It could
8062 * be that we already had a modified copy before we did this version.
8063 * If so, that copy is no longer needed */
8064 if (t != input_string) {
8069 length_in_chars = (utf8)
8070 ? utf8_length((U8 *) s, (U8 *) s + len)
8073 /* The first element in the output is the collation id, used by
8074 * sv_collxfrm(); then comes the space for the transformed string. The
8075 * equation should give us a good estimate as to how much is needed */
8076 xAlloc = COLLXFRM_HDR_LEN
8078 + (PL_collxfrm_mult * length_in_chars);
8079 Newx(xbuf, xAlloc, char);
8080 if (UNLIKELY(! xbuf)) {
8081 DEBUG_L(PerlIO_printf(Perl_debug_log,
8082 "mem_collxfrm_: Couldn't malloc %zu bytes\n", xAlloc));
8086 /* Store the collation id */
8087 *(PERL_UINTMAX_T *)xbuf = PL_collation_ix;
8089 # if defined(USE_POSIX_2008_LOCALE) && defined HAS_STRXFRM_L
8090 # ifdef USE_LOCALE_CTYPE
8092 constructed_locale = newlocale(LC_CTYPE_MASK, PL_collation_name,
8093 duplocale(use_curlocale_scratch()));
8096 constructed_locale = duplocale(use_curlocale_scratch());
8099 # define my_strxfrm(dest, src, n) strxfrm_l(dest, src, n, \
8101 # define CLEANUP_STRXFRM \
8103 if (constructed_locale != (locale_t) 0) \
8104 freelocale(constructed_locale); \
8107 # define my_strxfrm(dest, src, n) strxfrm(dest, src, n)
8108 # ifdef USE_LOCALE_CTYPE
8110 orig_CTYPE_locale = toggle_locale_c(LC_CTYPE, PL_collation_name);
8112 # define CLEANUP_STRXFRM \
8113 restore_toggled_locale_c(LC_CTYPE, orig_CTYPE_locale)
8115 # define CLEANUP_STRXFRM NOOP
8119 /* Then the transformation of the input. We loop until successful, or we
8124 *xlen = my_strxfrm(xbuf + COLLXFRM_HDR_LEN,
8126 xAlloc - COLLXFRM_HDR_LEN);
8129 /* If the transformed string occupies less space than we told strxfrm()
8130 * was available, it means it transformed the whole string. */
8131 if (*xlen < xAlloc - COLLXFRM_HDR_LEN) {
8133 /* But there still could have been a problem */
8135 DEBUG_L(PerlIO_printf(Perl_debug_log,
8136 "strxfrm failed for LC_COLLATE=%s; errno=%d, input=%s\n",
8137 PL_collation_name, errno,
8138 _byte_dump_string((U8 *) s, len, 0)));
8142 /* Here, the transformation was successful. Some systems include a
8143 * trailing NUL in the returned length. Ignore it, using a loop in
8144 * case multiple trailing NULs are returned. */
8146 && *(xbuf + COLLXFRM_HDR_LEN + (*xlen) - 1) == '\0')
8151 /* If the first try didn't get it, it means our prediction was low.
8152 * Modify the coefficients so that we predict a larger value in any
8153 * future transformations */
8155 STRLEN needed = *xlen + 1; /* +1 For trailing NUL */
8156 STRLEN computed_guess = PL_collxfrm_base
8157 + (PL_collxfrm_mult * length_in_chars);
8159 /* On zero-length input, just keep current slope instead of
8161 const STRLEN new_m = (length_in_chars != 0)
8162 ? needed / length_in_chars
8165 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
8166 "initial size of %zu bytes for a length "
8167 "%zu string was insufficient, %zu needed\n",
8168 computed_guess, length_in_chars, needed));
8170 /* If slope increased, use it, but discard this result for
8171 * length 1 strings, as we can't be sure that it's a real slope
8173 if (length_in_chars > 1 && new_m > PL_collxfrm_mult) {
8177 STRLEN old_m = PL_collxfrm_mult;
8178 STRLEN old_b = PL_collxfrm_base;
8182 PL_collxfrm_mult = new_m;
8183 PL_collxfrm_base = 1; /* +1 For trailing NUL */
8184 computed_guess = PL_collxfrm_base
8185 + (PL_collxfrm_mult * length_in_chars);
8186 if (computed_guess < needed) {
8187 PL_collxfrm_base += needed - computed_guess;
8190 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
8191 "slope is now %zu; was %zu, base "
8192 "is now %zu; was %zu\n",
8193 PL_collxfrm_mult, old_m,
8194 PL_collxfrm_base, old_b));
8196 else { /* Slope didn't change, but 'b' did */
8197 const STRLEN new_b = needed
8200 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
8201 "base is now %zu; was %zu\n", new_b, PL_collxfrm_base));
8202 PL_collxfrm_base = new_b;
8209 if (UNLIKELY(*xlen >= PERL_INT_MAX)) {
8210 DEBUG_L(PerlIO_printf(Perl_debug_log,
8211 "mem_collxfrm_: Needed %zu bytes, max permissible is %u\n",
8212 *xlen, PERL_INT_MAX));
8216 /* A well-behaved strxfrm() returns exactly how much space it needs
8217 * (usually not including the trailing NUL) when it fails due to not
8218 * enough space being provided. Assume that this is the case unless
8219 * it's been proven otherwise */
8220 if (LIKELY(PL_strxfrm_is_behaved) && first_time) {
8221 xAlloc = *xlen + COLLXFRM_HDR_LEN + 1;
8223 else { /* Here, either:
8224 * 1) The strxfrm() has previously shown bad behavior; or
8225 * 2) It isn't the first time through the loop, which means
8226 * that the strxfrm() is now showing bad behavior, because
8227 * we gave it what it said was needed in the previous
8228 * iteration, and it came back saying it needed still more.
8229 * (Many versions of cygwin fit this. When the buffer size
8230 * isn't sufficient, they return the input size instead of
8231 * how much is needed.)
8232 * Increase the buffer size by a fixed percentage and try again.
8234 xAlloc += (xAlloc / 4) + 1;
8235 PL_strxfrm_is_behaved = FALSE;
8237 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
8238 "mem_collxfrm_ required more space than previously"
8239 " calculated for locale %s, trying again with new"
8241 PL_collation_name, COLLXFRM_HDR_LEN,
8242 xAlloc - COLLXFRM_HDR_LEN));
8245 Renew(xbuf, xAlloc, char);
8246 if (UNLIKELY(! xbuf)) {
8247 DEBUG_L(PerlIO_printf(Perl_debug_log,
8248 "mem_collxfrm_: Couldn't realloc %zu bytes\n", xAlloc));
8257 DEBUG_L(print_collxfrm_input_and_return(s, s + len, xbuf, *xlen, utf8));
8259 /* Free up unneeded space; retain enough for trailing NUL */
8260 Renew(xbuf, COLLXFRM_HDR_LEN + *xlen + 1, char);
8262 if (s != input_string) {
8271 DEBUG_L(print_collxfrm_input_and_return(s, s + len, NULL, 0, utf8));
8274 if (s != input_string) {
8285 S_print_collxfrm_input_and_return(pTHX_
8293 PERL_ARGS_ASSERT_PRINT_COLLXFRM_INPUT_AND_RETURN;
8295 PerlIO_printf(Perl_debug_log,
8296 "mem_collxfrm_[ix %" UVuf "] for locale '%s':\n"
8297 " input=%s\n return=%s\n return len=%zu\n",
8298 (UV) PL_collation_ix, PL_collation_name,
8299 get_displayable_string(s, e, is_utf8),
8304 : _byte_dump_string((U8 *) xbuf + COLLXFRM_HDR_LEN,
8309 # endif /* DEBUGGING */
8312 Perl_strxfrm(pTHX_ SV * src)
8314 PERL_ARGS_ASSERT_STRXFRM;
8316 /* For use by POSIX::strxfrm(). If they differ, toggle LC_CTYPE to
8317 * LC_COLLATE to avoid potential mojibake.
8319 * If we can't calculate a collation, 'src' is instead returned, so that
8320 * future comparisons will be by code point order */
8322 # ifdef USE_LOCALE_CTYPE
8324 const char * orig_ctype = toggle_locale_c(LC_CTYPE,
8325 querylocale_c(LC_COLLATE));
8331 const char *p = SvPV_const(src, srclen);
8332 const U32 utf8_flag = SvUTF8(src);
8333 char *d = mem_collxfrm_(p, srclen, &dstlen, cBOOL(utf8_flag));
8335 assert(utf8_flag == 0 || utf8_flag == SVf_UTF8);
8339 dst =newSVpvn_flags(d + COLLXFRM_HDR_LEN,
8340 dstlen, SVs_TEMP|utf8_flag);
8344 # ifdef USE_LOCALE_CTYPE
8346 restore_toggled_locale_c(LC_CTYPE, orig_ctype);
8353 #endif /* USE_LOCALE_COLLATE */
8357 S_toggle_locale_i(pTHX_ const locale_category_index cat_index,
8358 const char * new_locale,
8359 const line_t caller_line)
8361 PERL_ARGS_ASSERT_TOGGLE_LOCALE_I;
8362 assert(cat_index <= LC_ALL_INDEX_);
8364 /* Changes the locale for the category specified by 'index' to 'new_locale,
8365 * if they aren't already the same.
8367 * Returns a copy of the name of the original locale for 'cat_index'
8368 * so can be switched back to with the companion function
8369 * restore_toggled_locale_i(), (NULL if no restoral is necessary.) */
8371 /* Find the original locale of the category we may need to change, so that
8372 * it can be restored to later */
8373 const char * locale_to_restore_to = querylocale_i(cat_index);
8375 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
8376 "(%" LINE_Tf "): toggle_locale_i: index=%d(%s), wanted=%s,"
8378 caller_line, cat_index, category_names[cat_index],
8379 new_locale, locale_to_restore_to));
8381 if (! locale_to_restore_to) {
8382 locale_panic_via_(Perl_form(aTHX_
8383 "Could not find current %s locale",
8384 category_names[cat_index]),
8385 __FILE__, caller_line);
8388 /* If the locales are the same, there's nothing to do */
8389 if (strEQ(locale_to_restore_to, new_locale)) {
8390 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
8391 "(%" LINE_Tf "): %s locale unchanged as %s\n",
8392 caller_line, category_names[cat_index],
8398 /* Finally, change the locale to the new one */
8399 void_setlocale_i_with_caller(cat_index, new_locale, __FILE__, caller_line);
8401 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
8402 "(%" LINE_Tf "): %s locale switched to %s\n",
8403 caller_line, category_names[cat_index], new_locale));
8405 return locale_to_restore_to;
8408 PERL_UNUSED_ARG(caller_line);
8414 S_restore_toggled_locale_i(pTHX_ const locale_category_index cat_index,
8415 const char * restore_locale,
8416 const line_t caller_line)
8418 /* Restores the locale for LC_category corresponding to cat_index to
8419 * 'restore_locale' (which is a copy that will be freed by this function),
8420 * or do nothing if the latter parameter is NULL */
8422 PERL_ARGS_ASSERT_RESTORE_TOGGLED_LOCALE_I;
8423 assert(cat_index <= LC_ALL_INDEX_);
8425 if (restore_locale == NULL) {
8426 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
8427 "(%" LINE_Tf "): No need to restore %s\n",
8428 caller_line, category_names[cat_index]));
8432 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
8433 "(%" LINE_Tf "): %s restoring locale to %s\n",
8434 caller_line, category_names[cat_index],
8437 void_setlocale_i_with_caller(cat_index, restore_locale,
8438 __FILE__, caller_line);
8441 PERL_UNUSED_ARG(caller_line);
8446 # ifdef USE_LOCALE_CTYPE
8449 S_is_codeset_name_UTF8(const char * name)
8451 /* Return a boolean as to if the passed-in name indicates it is a UTF-8
8452 * code set. Several variants are possible */
8453 const Size_t len = strlen(name);
8455 PERL_ARGS_ASSERT_IS_CODESET_NAME_UTF8;
8459 /* http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756.aspx */
8460 if (memENDs(name, len, "65001")) {
8465 /* 'UTF8' or 'UTF-8' */
8466 return ( inRANGE(len, 4, 5)
8467 && name[len-1] == '8'
8468 && ( memBEGINs(name, len, "UTF")
8469 || memBEGINs(name, len, "utf"))
8470 && (len == 4 || name[3] == '-'));
8474 #endif /* USE_LOCALE */
8477 Perl__is_in_locale_category(pTHX_ const bool compiling, const int category)
8479 /* Internal function which returns if we are in the scope of a pragma that
8480 * enables the locale category 'category'. 'compiling' should indicate if
8481 * this is during the compilation phase (TRUE) or not (FALSE). */
8483 const COP * const cop = (compiling) ? &PL_compiling : PL_curcop;
8485 SV *these_categories = cop_hints_fetch_pvs(cop, "locale", 0);
8486 if (! these_categories || these_categories == &PL_sv_placeholder) {
8490 /* The pseudo-category 'not_characters' is -1, so just add 1 to each to get
8491 * a valid unsigned */
8492 assert(category >= -1);
8493 return cBOOL(SvUV(these_categories) & (1U << (category + 1)));
8496 /* my_strerror() returns a mortalized copy of the text of the error message
8497 * associated with 'errnum'.
8499 * If not called from within the scope of 'use locale', it uses the text from
8500 * the C locale. If Perl is compiled to not pay attention to LC_CTYPE nor
8501 * LC_MESSAGES, it uses whatever strerror() returns. Otherwise the text is
8502 * derived from the locale, LC_MESSAGES if we have that; LC_CTYPE if not.
8504 * It returns in *utf8ness the result's UTF-8ness
8506 * The function just calls strerror(), but temporarily switches locales, if
8507 * needed. Many platforms require LC_CTYPE and LC_MESSAGES to be in the same
8508 * CODESET in order for the return from strerror() to not contain '?' symbols,
8509 * or worse, mojibaked. It's cheaper to just use the stricter criteria of
8510 * being in the same locale. So the code below uses a common locale for both
8511 * categories. Again, that is C if not within 'use locale' scope; or the
8512 * LC_MESSAGES locale if in scope and we have that category; and LC_CTYPE if we
8513 * don't have LC_MESSAGES; and whatever strerror returns if we don't have
8516 * There are two sets of implementations. The first below is if we have
8517 * strerror_l(). This is the simpler. We just use the already-built C locale
8518 * object if not in locale scope, or build up a custom one otherwise.
8520 * When strerror_l() is not available, we may have to swap locales temporarily
8521 * to bring the two categories into sync with each other, and possibly to the C
8524 * Because the prepropessing directives to conditionally compile this function
8525 * would greatly obscure the logic of the various implementations, the whole
8526 * function is repeated for each configuration, with some common macros. */
8528 /* Used to shorten the definitions of the following implementations of
8530 #define DEBUG_STRERROR_ENTER(errnum, in_locale) \
8531 DEBUG_Lv(PerlIO_printf(Perl_debug_log, \
8532 "my_strerror called with errnum %d;" \
8533 " Within locale scope=%d\n", \
8536 #define DEBUG_STRERROR_RETURN(errstr, utf8ness) \
8537 DEBUG_Lv(PerlIO_printf(Perl_debug_log, \
8538 "Strerror returned; saving a copy: '%s';" \
8540 get_displayable_string(errstr, \
8541 errstr + strlen(errstr), \
8545 /* On platforms that have precisely one of these categories (Windows
8546 * qualifies), these yield the correct one */
8547 #if defined(USE_LOCALE_CTYPE)
8548 # define WHICH_LC_INDEX LC_CTYPE_INDEX_
8549 #elif defined(USE_LOCALE_MESSAGES)
8550 # define WHICH_LC_INDEX LC_MESSAGES_INDEX_
8553 /*===========================================================================*/
8554 /* First set of implementations, when have strerror_l() */
8556 #if defined(USE_POSIX_2008_LOCALE) && defined(HAS_STRERROR_L)
8558 # if ! defined(USE_LOCALE_CTYPE) && ! defined(USE_LOCALE_MESSAGES)
8560 /* Here, neither category is defined: use the C locale */
8562 Perl_my_strerror(pTHX_ const int errnum, utf8ness_t * utf8ness)
8564 PERL_ARGS_ASSERT_MY_STRERROR;
8566 DEBUG_STRERROR_ENTER(errnum, 0);
8568 const char *errstr = savepv(strerror_l(errnum, PL_C_locale_obj));
8569 *utf8ness = UTF8NESS_IMMATERIAL;
8571 DEBUG_STRERROR_RETURN(errstr, utf8ness);
8577 # elif ! defined(USE_LOCALE_CTYPE) || ! defined(USE_LOCALE_MESSAGES)
8579 /*--------------------------------------------------------------------------*/
8581 /* Here one or the other of CTYPE or MESSAGES is defined, but not both. If we
8582 * are not within 'use locale' scope of the only one defined, we use the C
8583 * locale; otherwise use the current locale object */
8586 Perl_my_strerror(pTHX_ const int errnum, utf8ness_t * utf8ness)
8588 PERL_ARGS_ASSERT_MY_STRERROR;
8590 DEBUG_STRERROR_ENTER(errnum, IN_LC(categories[WHICH_LC_INDEX]));
8592 /* Use C if not within locale scope; Otherwise, use current locale */
8593 const locale_t which_obj = (IN_LC(categories[WHICH_LC_INDEX]))
8595 : use_curlocale_scratch();
8597 const char *errstr = savepv(strerror_l(errnum, which_obj));
8598 *utf8ness = get_locale_string_utf8ness_i(errstr, LOCALE_UTF8NESS_UNKNOWN,
8599 NULL, WHICH_LC_INDEX);
8600 DEBUG_STRERROR_RETURN(errstr, utf8ness);
8606 /*--------------------------------------------------------------------------*/
8607 # else /* Are using both categories. Place them in the same CODESET,
8608 * either C or the LC_MESSAGES locale */
8611 Perl_my_strerror(pTHX_ const int errnum, utf8ness_t * utf8ness)
8613 PERL_ARGS_ASSERT_MY_STRERROR;
8615 DEBUG_STRERROR_ENTER(errnum, IN_LC(LC_MESSAGES));
8618 if (! IN_LC(LC_MESSAGES)) { /* Use C if not within locale scope */
8619 errstr = savepv(strerror_l(errnum, PL_C_locale_obj));
8620 *utf8ness = UTF8NESS_IMMATERIAL;
8622 else { /* Otherwise, use the LC_MESSAGES locale, making sure LC_CTYPE
8624 locale_t cur = duplocale(use_curlocale_scratch());
8626 cur = newlocale(LC_CTYPE_MASK, querylocale_c(LC_MESSAGES), cur);
8627 errstr = savepv(strerror_l(errnum, cur));
8628 *utf8ness = get_locale_string_utf8ness_i(errstr,
8629 LOCALE_UTF8NESS_UNKNOWN,
8630 NULL, LC_MESSAGES_INDEX_);
8634 DEBUG_STRERROR_RETURN(errstr, utf8ness);
8639 # endif /* Above is using strerror_l */
8640 /*===========================================================================*/
8641 #else /* Below is not using strerror_l */
8642 # if ! defined(USE_LOCALE_CTYPE) && ! defined(USE_LOCALE_MESSAGES)
8644 /* If not using using either of the categories, return plain, unadorned
8648 Perl_my_strerror(pTHX_ const int errnum, utf8ness_t * utf8ness)
8650 PERL_ARGS_ASSERT_MY_STRERROR;
8652 DEBUG_STRERROR_ENTER(errnum, 0);
8654 const char *errstr = savepv(Strerror(errnum));
8655 *utf8ness = UTF8NESS_IMMATERIAL;
8657 DEBUG_STRERROR_RETURN(errstr, utf8ness);
8663 /*--------------------------------------------------------------------------*/
8664 # elif ! defined(USE_LOCALE_CTYPE) || ! defined(USE_LOCALE_MESSAGES)
8666 /* Here one or the other of CTYPE or MESSAGES is defined, but not both. If we
8667 * are not within 'use locale' scope of the only one defined, we use the C
8668 * locale; otherwise use the current locale */
8671 Perl_my_strerror(pTHX_ const int errnum, utf8ness_t * utf8ness)
8673 PERL_ARGS_ASSERT_MY_STRERROR;
8675 DEBUG_STRERROR_ENTER(errnum, IN_LC(categories[WHICH_LC_INDEX]));
8678 if (IN_LC(categories[WHICH_LC_INDEX])) {
8679 errstr = savepv(Strerror(errnum));
8680 *utf8ness = get_locale_string_utf8ness_i(errstr,
8681 LOCALE_UTF8NESS_UNKNOWN,
8682 NULL, WHICH_LC_INDEX);
8688 const char * orig_locale = toggle_locale_i(WHICH_LC_INDEX, "C");
8690 errstr = savepv(Strerror(errnum));
8692 restore_toggled_locale_i(WHICH_LC_INDEX, orig_locale);
8696 *utf8ness = UTF8NESS_IMMATERIAL;
8699 DEBUG_STRERROR_RETURN(errstr, utf8ness);
8705 /*--------------------------------------------------------------------------*/
8708 /* Below, have both LC_CTYPE and LC_MESSAGES. Place them in the same CODESET,
8709 * either C or the LC_MESSAGES locale */
8712 Perl_my_strerror(pTHX_ const int errnum, utf8ness_t * utf8ness)
8714 PERL_ARGS_ASSERT_MY_STRERROR;
8716 DEBUG_STRERROR_ENTER(errnum, IN_LC(LC_MESSAGES));
8718 const char * desired_locale = (IN_LC(LC_MESSAGES))
8719 ? querylocale_c(LC_MESSAGES)
8721 /* XXX Can fail on z/OS */
8725 const char* orig_CTYPE_locale = toggle_locale_c(LC_CTYPE,
8727 const char* orig_MESSAGES_locale = toggle_locale_c(LC_MESSAGES,
8729 const char *errstr = savepv(Strerror(errnum));
8731 restore_toggled_locale_c(LC_MESSAGES, orig_MESSAGES_locale);
8732 restore_toggled_locale_c(LC_CTYPE, orig_CTYPE_locale);
8736 *utf8ness = get_locale_string_utf8ness_i(errstr, LOCALE_UTF8NESS_UNKNOWN,
8737 NULL, LC_MESSAGES_INDEX_);
8738 DEBUG_STRERROR_RETURN(errstr, utf8ness);
8744 /*--------------------------------------------------------------------------*/
8745 # endif /* end of not using strerror_l() */
8746 #endif /* end of all the my_strerror() implementations */
8750 =for apidoc switch_to_global_locale
8752 This function copies the locale state of the calling thread into the program's
8753 global locale, and converts the thread to use that global locale.
8755 It is intended so that Perl can safely be used with C libraries that access the
8756 global locale and which can't be converted to not access it. Effectively, this
8757 means libraries that call C<L<setlocale(3)>> on non-Windows systems. (For
8758 portability, it is a good idea to use it on Windows as well.)
8760 A downside of using it is that it disables the services that Perl provides to
8761 hide locale gotchas from your code. The service you most likely will miss
8762 regards the radix character (decimal point) in floating point numbers. Code
8763 executed after this function is called can no longer just assume that this
8764 character is correct for the current circumstances.
8766 To return to Perl control, and restart the gotcha prevention services, call
8767 C<L</sync_locale>>. Behavior is undefined for any pure Perl code that executes
8768 while the switch is in effect.
8770 The global locale and the per-thread locales are independent. As long as just
8771 one thread converts to the global locale, everything works smoothly. But if
8772 more than one does, they can easily interfere with each other, and races are
8773 likely. On Windows systems prior to Visual Studio 15 (at which point Microsoft
8774 fixed a bug), races can occur (even if only one thread has been converted to
8775 the global locale), but only if you use the following operations:
8779 =item L<POSIX::localeconv|POSIX/localeconv>
8781 =item L<I18N::Langinfo>, items C<CRNCYSTR> and C<THOUSEP>
8783 =item L<perlapi/Perl_langinfo>, items C<CRNCYSTR> and C<THOUSEP>
8787 The first item is not fixable (except by upgrading to a later Visual Studio
8788 release), but it would be possible to work around the latter two items by
8789 having Perl change its algorithm for calculating these to use Windows API
8790 functions (likely C<GetNumberFormat> and C<GetCurrencyFormat>); patches
8793 XS code should never call plain C<setlocale>, but should instead be converted
8794 to either call L<C<Perl_setlocale>|perlapi/Perl_setlocale> (which is a drop-in
8795 for the system C<setlocale>) or use the methods given in L<perlcall> to call
8796 L<C<POSIX::setlocale>|POSIX/setlocale>. Either one will transparently properly
8797 handle all cases of single- vs multi-thread, POSIX 2008-supported or not.
8802 #if defined(WIN32) && defined(USE_THREAD_SAFE_LOCALE)
8803 # define CHANGE_SYSTEM_LOCALE_TO_GLOBAL \
8805 if (_configthreadlocale(_DISABLE_PER_THREAD_LOCALE) == -1) { \
8806 locale_panic_("_configthreadlocale returned an error"); \
8809 #elif defined(USE_POSIX_2008_LOCALE)
8810 # define CHANGE_SYSTEM_LOCALE_TO_GLOBAL \
8812 locale_t old_locale = uselocale(LC_GLOBAL_LOCALE); \
8813 if (! old_locale) { \
8814 locale_panic_("Could not change to global locale"); \
8817 /* Free the per-thread memory */ \
8818 if ( old_locale != LC_GLOBAL_LOCALE \
8819 && old_locale != PL_C_locale_obj) \
8821 freelocale(old_locale); \
8825 # define CHANGE_SYSTEM_LOCALE_TO_GLOBAL
8829 Perl_switch_to_global_locale(pTHX)
8834 DEBUG_L(PerlIO_printf(Perl_debug_log, "Entering switch_to_global; %s\n",
8835 get_LC_ALL_display()));
8837 /* In these cases, we use the system state to determine if we are in the
8838 * global locale or not. */
8839 # ifdef USE_POSIX_2008_LOCALE
8841 const bool perl_controls = (LC_GLOBAL_LOCALE != uselocale((locale_t) 0));
8843 # elif defined(USE_THREAD_SAFE_LOCALE) && defined(WIN32)
8845 int config_return = _configthreadlocale(0);
8846 if (config_return == -1) {
8847 locale_panic_("_configthreadlocale returned an error");
8849 const bool perl_controls = (config_return == _ENABLE_PER_THREAD_LOCALE);
8853 const bool perl_controls = false;
8857 /* No-op if already in global */
8858 if (! perl_controls) {
8864 const char * thread_locale = calculate_LC_ALL_string(NULL,
8865 EXTERNAL_FORMAT_FOR_SET,
8868 CHANGE_SYSTEM_LOCALE_TO_GLOBAL;
8869 posix_setlocale(LC_ALL, thread_locale);
8871 # else /* Must be USE_POSIX_2008_LOCALE) */
8873 const char * cur_thread_locales[LC_ALL_INDEX_];
8875 /* Save each category's current per-thread state */
8876 for_all_individual_category_indexes(i) {
8877 cur_thread_locales[i] = querylocale_i(i);
8880 CHANGE_SYSTEM_LOCALE_TO_GLOBAL;
8882 /* Set the global to what was our per-thread state */
8883 POSIX_SETLOCALE_LOCK;
8884 for_all_individual_category_indexes(i) {
8885 posix_setlocale(categories[i], cur_thread_locales[i]);
8887 POSIX_SETLOCALE_UNLOCK;
8890 # ifdef USE_LOCALE_NUMERIC
8892 /* Switch to the underlying C numeric locale; the application is on its
8894 POSIX_SETLOCALE_LOCK;
8895 posix_setlocale(LC_NUMERIC, PL_numeric_name);
8896 POSIX_SETLOCALE_UNLOCK;
8905 =for apidoc sync_locale
8907 This function copies the state of the program global locale into the calling
8908 thread, and converts that thread to using per-thread locales, if it wasn't
8909 already, and the platform supports them. The LC_NUMERIC locale is toggled into
8910 the standard state (using the C locale's conventions), if not within the
8911 lexical scope of S<C<use locale>>.
8913 Perl will now consider itself to have control of the locale.
8915 Since unthreaded perls have only a global locale, this function is a no-op
8918 This function is intended for use with C libraries that do locale manipulation.
8919 It allows Perl to accommodate the use of them. Call this function before
8920 transferring back to Perl space so that it knows what state the C code has left
8923 XS code should not manipulate the locale on its own. Instead,
8924 L<C<Perl_setlocale>|perlapi/Perl_setlocale> can be used at any time to query or
8925 change the locale (though changing the locale is antisocial and dangerous on
8926 multi-threaded systems that don't have multi-thread safe locale operations.
8927 (See L<perllocale/Multi-threaded operation>).
8929 Using the libc L<C<setlocale(3)>> function should be avoided. Nevertheless,
8930 certain non-Perl libraries called from XS, do call it, and their behavior may
8931 not be able to be changed. This function, along with
8932 C<L</switch_to_global_locale>>, can be used to get seamless behavior in these
8933 circumstances, as long as only one thread is involved.
8935 If the library has an option to turn off its locale manipulation, doing that is
8936 preferable to using this mechanism. C<Gtk> is such a library.
8938 The return value is a boolean: TRUE if the global locale at the time of call
8939 was in effect for the caller; and FALSE if a per-thread locale was in effect.
8945 Perl_sync_locale(pTHX)
8954 bool was_in_global = TRUE;
8956 # ifdef USE_THREAD_SAFE_LOCALE
8959 int config_return = _configthreadlocale(_DISABLE_PER_THREAD_LOCALE);
8960 if (config_return == -1) {
8961 locale_panic_("_configthreadlocale returned an error");
8963 was_in_global = (config_return == _DISABLE_PER_THREAD_LOCALE);
8965 # elif defined(USE_POSIX_2008_LOCALE)
8967 was_in_global = (LC_GLOBAL_LOCALE == uselocale(LC_GLOBAL_LOCALE));
8970 # error Unexpected Configuration
8972 # endif /* USE_THREAD_SAFE_LOCALE */
8974 /* Here, we are in the global locale. Get and save the values for each
8975 * category, and convert the current thread to use them */
8979 STDIZED_SETLOCALE_LOCK;
8980 const char * lc_all_string = savepv(stdized_setlocale(LC_ALL, NULL));
8981 STDIZED_SETLOCALE_UNLOCK;
8983 give_perl_locale_control(lc_all_string, __LINE__);
8984 Safefree(lc_all_string);
8988 const char * current_globals[LC_ALL_INDEX_];
8989 for_all_individual_category_indexes(i) {
8990 STDIZED_SETLOCALE_LOCK;
8991 current_globals[i] = savepv(stdized_setlocale(categories[i], NULL));
8992 STDIZED_SETLOCALE_UNLOCK;
8995 give_perl_locale_control((const char **) ¤t_globals, __LINE__);
8997 for_all_individual_category_indexes(i) {
8998 Safefree(current_globals[i]);
9003 return was_in_global;
9009 #if defined(DEBUGGING) && defined(USE_LOCALE)
9012 S_my_setlocale_debug_string_i(pTHX_
9013 const locale_category_index cat_index,
9014 const char* locale, /* Optional locale name */
9016 /* return value from setlocale() when attempting
9017 * to set 'category' to 'locale' */
9022 /* Returns a pointer to a NUL-terminated string in static storage with
9023 * added text about the info passed in. This is not thread safe and will
9024 * be overwritten by the next call, so this should be used just to
9025 * formulate a string to immediately print or savepv() on. */
9027 const char * locale_quote;
9028 const char * retval_quote;
9030 assert(cat_index <= LC_ALL_INDEX_);
9032 if (locale == NULL) {
9037 locale_quote = "\"";
9040 if (retval == NULL) {
9045 retval_quote = "\"";
9048 # ifdef USE_LOCALE_THREADS
9049 # define THREAD_FORMAT "%p:"
9050 # define THREAD_ARGUMENT aTHX_
9052 # define THREAD_FORMAT
9053 # define THREAD_ARGUMENT
9056 return Perl_form(aTHX_
9057 "%s:%" LINE_Tf ": " THREAD_FORMAT
9058 " setlocale(%s[%d], %s%s%s) returned %s%s%s\n",
9060 __FILE__, line, THREAD_ARGUMENT
9061 category_names[cat_index], categories[cat_index],
9062 locale_quote, locale, locale_quote,
9063 retval_quote, retval, retval_quote);
9067 #ifdef USE_PERL_SWITCH_LOCALE_CONTEXT
9070 Perl_switch_locale_context(pTHX)
9072 /* libc keeps per-thread locale status information in some configurations.
9073 * So, we can't just switch out aTHX to switch to a new thread. libc has
9074 * to follow along. This routine does that based on per-interpreter
9075 * variables we keep just for this purpose.
9077 * There are two implementations where this is an issue. For the other
9078 * implementations, it doesn't matter because libc is using global values
9079 * that all threads know about.
9081 * The two implementations are where libc keeps thread-specific information
9082 * on its own. These are
9084 * POSIX 2008: The current locale is kept by libc as an object. We save
9085 * a copy of that in the per-thread PL_cur_locale_obj, and so
9086 * this routine uses that copy to tell the thread it should be
9087 * operating with that object
9088 * Windows thread-safe locales: A given thread in Windows can be being run
9089 * with per-thread locales, or not. When the thread context
9090 * changes, libc doesn't automatically know if the thread is
9091 * using per-thread locales, nor does it know what the new
9092 * thread's locale is. We keep that information in the
9093 * per-thread variables:
9094 * PL_controls_locale indicates if this thread is using
9095 * per-thread locales or not
9096 * PL_cur_LC_ALL indicates what the the locale
9097 * should be if it is a per-thread
9101 if (UNLIKELY( PL_veto_switch_non_tTHX_context
9102 || PL_phase == PERL_PHASE_CONSTRUCT))
9107 # ifdef USE_POSIX_2008_LOCALE
9109 if (! uselocale(PL_cur_locale_obj)) {
9110 locale_panic_(Perl_form(aTHX_
9111 "Can't uselocale(%p), LC_ALL supposed to"
9113 PL_cur_locale_obj, get_LC_ALL_display()));
9116 # elif defined(WIN32)
9118 if (! bool_setlocale_c(LC_ALL, PL_cur_LC_ALL)) {
9119 locale_panic_(Perl_form(aTHX_ "Can't setlocale(%s)", PL_cur_LC_ALL));
9129 Perl_thread_locale_init(pTHX)
9132 #ifdef USE_THREAD_SAFE_LOCALE
9133 # ifdef USE_POSIX_2008_LOCALE
9135 /* Called from a thread on startup.
9137 * The operations here have to be done from within the calling thread, as
9138 * they affect libc's knowledge of the thread; libc has no knowledge of
9141 DEBUG_L(PerlIO_printf(Perl_debug_log,
9142 "new thread, initial locale is %s;"
9143 " calling setlocale(LC_ALL, \"C\")\n",
9144 get_LC_ALL_display()));
9146 if (! uselocale(PL_C_locale_obj)) {
9148 /* Not being able to change to the C locale is severe; don't keep
9150 locale_panic_(Perl_form(aTHX_
9151 "Can't uselocale(%p), 'C'", PL_C_locale_obj));
9152 NOT_REACHED; /* NOTREACHED */
9155 # ifdef MULTIPLICITY
9157 PL_cur_locale_obj = PL_C_locale_obj;
9160 # elif defined(WIN32)
9162 /* On Windows, make sure new thread has per-thread locales enabled */
9163 if (_configthreadlocale(_ENABLE_PER_THREAD_LOCALE) == -1) {
9164 locale_panic_("_configthreadlocale returned an error");
9166 void_setlocale_c(LC_ALL, "C");
9174 Perl_thread_locale_term(pTHX)
9176 /* Called from a thread as it gets ready to terminate.
9178 * The operations here have to be done from within the calling thread, as
9179 * they affect libc's knowledge of the thread; libc has no knowledge of
9182 #if defined(USE_POSIX_2008_LOCALE) && defined(USE_THREADS)
9184 /* Switch to the global locale, so can free up the per-thread object */
9185 locale_t actual_obj = uselocale(LC_GLOBAL_LOCALE);
9186 if (actual_obj != LC_GLOBAL_LOCALE && actual_obj != PL_C_locale_obj) {
9187 freelocale(actual_obj);
9190 /* Prevent leaks even if something has gone wrong */
9191 locale_t expected_obj = PL_cur_locale_obj;
9192 if (UNLIKELY( expected_obj != actual_obj
9193 && expected_obj != LC_GLOBAL_LOCALE
9194 && expected_obj != PL_C_locale_obj))
9196 freelocale(expected_obj);
9199 PL_cur_locale_obj = LC_GLOBAL_LOCALE;
9202 #ifdef WIN32_USE_FAKE_OLD_MINGW_LOCALES
9204 /* When faking the mingw implementation, we coerce this function into doing
9205 * something completely different from its intent -- namely to free up our
9206 * static buffer to avoid a leak. This function gets called for each
9207 * thread that is terminating, so will give us a chance to free the buffer
9208 * from the appropriate pool. On unthreaded systems, it gets called by the
9209 * mutex termination code. */
9211 # ifdef MULTIPLICITY
9213 if (aTHX != wsetlocale_buf_aTHX) {
9219 if (wsetlocale_buf_size > 0) {
9220 Safefree(wsetlocale_buf);
9221 wsetlocale_buf_size = 0;
9229 * ex: set ts=8 sts=4 sw=4 et: