This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
add Perl_op_class(o) API function
[perl5.git] / locale.c
CommitLineData
98994639
HS
1/* locale.c
2 *
1129b882
NC
3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
4 * 2002, 2003, 2005, 2006, 2007, 2008 by Larry Wall and others
98994639
HS
5 *
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
8 *
9 */
10
11/*
4ac71550 12 * A Elbereth Gilthoniel,
cdad3b53 13 * silivren penna míriel
4ac71550 14 * o menel aglar elenath!
cdad3b53 15 * Na-chaered palan-díriel
4ac71550
TC
16 * o galadhremmin ennorath,
17 * Fanuilos, le linnathon
18 * nef aear, si nef aearon!
19 *
20 * [p.238 of _The Lord of the Rings_, II/i: "Many Meetings"]
98994639
HS
21 */
22
166f8a29
DM
23/* utility functions for handling locale-specific stuff like what
24 * character represents the decimal point.
0d071d52
KW
25 *
26 * All C programs have an underlying locale. Perl generally doesn't pay any
27 * 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
a9ad02a8
KW
32 * the desired behavior of those functions at the moment. And, LC_MESSAGES is
33 * switched to the C locale for outputting the message unless within the scope
34 * of 'use locale'.
166f8a29
DM
35 */
36
98994639
HS
37#include "EXTERN.h"
38#define PERL_IN_LOCALE_C
39#include "perl.h"
40
b310b053
JH
41#ifdef I_LANGINFO
42# include <langinfo.h>
43#endif
44
a4af207c
JH
45#include "reentr.h"
46
2fcc0ca9
KW
47/* If the environment says to, we can output debugging information during
48 * initialization. This is done before option parsing, and before any thread
49 * creation, so can be a file-level static */
50#ifdef DEBUGGING
27cdc72e
DM
51# ifdef PERL_GLOBAL_STRUCT
52 /* no global syms allowed */
53# define debug_initialization 0
54# define DEBUG_INITIALIZATION_set(v)
55# else
2fcc0ca9 56static bool debug_initialization = FALSE;
27cdc72e
DM
57# define DEBUG_INITIALIZATION_set(v) (debug_initialization = v)
58# endif
2fcc0ca9
KW
59#endif
60
8ef6e574
KW
61#ifdef USE_LOCALE
62
98994639 63/*
0d071d52
KW
64 * Standardize the locale name from a string returned by 'setlocale', possibly
65 * modifying that string.
98994639 66 *
0ef2a2b2 67 * The typical return value of setlocale() is either
98994639
HS
68 * (1) "xx_YY" if the first argument of setlocale() is not LC_ALL
69 * (2) "xa_YY xb_YY ..." if the first argument of setlocale() is LC_ALL
70 * (the space-separated values represent the various sublocales,
0ef2a2b2 71 * in some unspecified order). This is not handled by this function.
98994639
HS
72 *
73 * In some platforms it has a form like "LC_SOMETHING=Lang_Country.866\n",
0ef2a2b2
KW
74 * which is harmful for further use of the string in setlocale(). This
75 * function removes the trailing new line and everything up through the '='
98994639
HS
76 *
77 */
78STATIC char *
79S_stdize_locale(pTHX_ char *locs)
80{
7452cf6a 81 const char * const s = strchr(locs, '=');
98994639
HS
82 bool okay = TRUE;
83
7918f24d
NC
84 PERL_ARGS_ASSERT_STDIZE_LOCALE;
85
8772537c
AL
86 if (s) {
87 const char * const t = strchr(s, '.');
98994639 88 okay = FALSE;
8772537c
AL
89 if (t) {
90 const char * const u = strchr(t, '\n');
91 if (u && (u[1] == 0)) {
92 const STRLEN len = u - s;
93 Move(s + 1, locs, len, char);
94 locs[len] = 0;
95 okay = TRUE;
98994639
HS
96 }
97 }
98 }
99
100 if (!okay)
101 Perl_croak(aTHX_ "Can't fix broken locale name \"%s\"", locs);
102
103 return locs;
104}
105
8ef6e574
KW
106#endif
107
98994639
HS
108void
109Perl_set_numeric_radix(pTHX)
110{
111#ifdef USE_LOCALE_NUMERIC
112# ifdef HAS_LOCALECONV
7452cf6a 113 const struct lconv* const lc = localeconv();
98994639 114
98994639
HS
115 if (lc && lc->decimal_point) {
116 if (lc->decimal_point[0] == '.' && lc->decimal_point[1] == 0) {
117 SvREFCNT_dec(PL_numeric_radix_sv);
a0714e2c 118 PL_numeric_radix_sv = NULL;
98994639
HS
119 }
120 else {
121 if (PL_numeric_radix_sv)
122 sv_setpv(PL_numeric_radix_sv, lc->decimal_point);
123 else
124 PL_numeric_radix_sv = newSVpv(lc->decimal_point, 0);
c5f058df 125 if (! is_utf8_invariant_string((U8 *) lc->decimal_point, 0)
28acfe03 126 && is_utf8_string((U8 *) lc->decimal_point, 0)
c1284011 127 && _is_cur_LC_category_utf8(LC_NUMERIC))
28acfe03
KW
128 {
129 SvUTF8_on(PL_numeric_radix_sv);
130 }
98994639
HS
131 }
132 }
133 else
a0714e2c 134 PL_numeric_radix_sv = NULL;
69014004 135
2fcc0ca9
KW
136#ifdef DEBUGGING
137 if (DEBUG_L_TEST || debug_initialization) {
138 PerlIO_printf(Perl_debug_log, "Locale radix is '%s', ?UTF-8=%d\n",
69014004 139 (PL_numeric_radix_sv)
37b7e435
KW
140 ? SvPVX(PL_numeric_radix_sv)
141 : "NULL",
142 (PL_numeric_radix_sv)
39eb7305 143 ? cBOOL(SvUTF8(PL_numeric_radix_sv))
2fcc0ca9
KW
144 : 0);
145 }
146#endif
69014004 147
98994639
HS
148# endif /* HAS_LOCALECONV */
149#endif /* USE_LOCALE_NUMERIC */
150}
151
a39edc4c
KW
152/* Is the C string input 'name' "C" or "POSIX"? If so, and 'name' is the
153 * return of setlocale(), then this is extremely likely to be the C or POSIX
154 * locale. However, the output of setlocale() is documented to be opaque, but
155 * the odds are extremely small that it would return these two strings for some
156 * other locale. Note that VMS in these two locales includes many non-ASCII
157 * characters as controls and punctuation (below are hex bytes):
158 * cntrl: 00-1F 7F 84-97 9B-9F
159 * punct: 21-2F 3A-40 5B-60 7B-7E A1-A3 A5 A7-AB B0-B3 B5-B7 B9-BD BF-CF D1-DD DF-EF F1-FD
160 * Oddly, none there are listed as alphas, though some represent alphabetics
161 * http://www.nntp.perl.org/group/perl.perl5.porters/2013/02/msg198753.html */
98b630b3
KW
162#define isNAME_C_OR_POSIX(name) ((name) != NULL \
163 && ((*(name) == 'C' && (*(name + 1)) == '\0') \
a39edc4c
KW
164 || strEQ((name), "POSIX")))
165
98994639 166void
8772537c 167Perl_new_numeric(pTHX_ const char *newnum)
98994639
HS
168{
169#ifdef USE_LOCALE_NUMERIC
0d071d52
KW
170
171 /* Called after all libc setlocale() calls affecting LC_NUMERIC, to tell
172 * core Perl this and that 'newnum' is the name of the new locale.
173 * It installs this locale as the current underlying default.
174 *
175 * The default locale and the C locale can be toggled between by use of the
176 * set_numeric_local() and set_numeric_standard() functions, which should
177 * probably not be called directly, but only via macros like
178 * SET_NUMERIC_STANDARD() in perl.h.
179 *
180 * The toggling is necessary mainly so that a non-dot radix decimal point
181 * character can be output, while allowing internal calculations to use a
182 * dot.
183 *
184 * This sets several interpreter-level variables:
bb304765 185 * PL_numeric_name The underlying locale's name: a copy of 'newnum'
0d071d52 186 * PL_numeric_local A boolean indicating if the toggled state is such
7738054c
KW
187 * that the current locale is the program's underlying
188 * locale
189 * PL_numeric_standard An int indicating if the toggled state is such
190 * that the current locale is the C locale. If non-zero,
191 * it is in C; if > 1, it means it may not be toggled away
192 * from C.
0d071d52
KW
193 * Note that both of the last two variables can be true at the same time,
194 * if the underlying locale is C. (Toggling is a no-op under these
195 * circumstances.)
196 *
197 * Any code changing the locale (outside this file) should use
198 * POSIX::setlocale, which calls this function. Therefore this function
199 * should be called directly only from this file and from
200 * POSIX::setlocale() */
201
b03f34cf 202 char *save_newnum;
98994639
HS
203
204 if (! newnum) {
43c5f42d
NC
205 Safefree(PL_numeric_name);
206 PL_numeric_name = NULL;
98994639
HS
207 PL_numeric_standard = TRUE;
208 PL_numeric_local = TRUE;
209 return;
210 }
211
b03f34cf 212 save_newnum = stdize_locale(savepv(newnum));
abe1abcf
KW
213
214 PL_numeric_standard = isNAME_C_OR_POSIX(save_newnum);
215 PL_numeric_local = TRUE;
216
b03f34cf 217 if (! PL_numeric_name || strNE(PL_numeric_name, save_newnum)) {
98994639 218 Safefree(PL_numeric_name);
b03f34cf 219 PL_numeric_name = save_newnum;
b03f34cf 220 }
abe1abcf
KW
221 else {
222 Safefree(save_newnum);
223 }
4c28b29c
KW
224
225 /* Keep LC_NUMERIC in the C locale. This is for XS modules, so they don't
226 * have to worry about the radix being a non-dot. (Core operations that
227 * need the underlying locale change to it temporarily). */
228 set_numeric_standard();
229
e19f01cb 230 set_numeric_radix();
6959d69d 231
f2ce9e1c
JH
232#else
233 PERL_UNUSED_ARG(newnum);
98994639
HS
234#endif /* USE_LOCALE_NUMERIC */
235}
236
237void
238Perl_set_numeric_standard(pTHX)
239{
240#ifdef USE_LOCALE_NUMERIC
28c1bf33
KW
241 /* Toggle the LC_NUMERIC locale to C. Most code should use the macros like
242 * SET_NUMERIC_STANDARD() in perl.h instead of calling this directly. The
243 * macro avoids calling this routine if toggling isn't necessary according
244 * to our records (which could be wrong if some XS code has changed the
245 * locale behind our back) */
0d071d52 246
a9b8c0d8
KW
247 setlocale(LC_NUMERIC, "C");
248 PL_numeric_standard = TRUE;
249 PL_numeric_local = isNAME_C_OR_POSIX(PL_numeric_name);
250 set_numeric_radix();
2fcc0ca9
KW
251#ifdef DEBUGGING
252 if (DEBUG_L_TEST || debug_initialization) {
253 PerlIO_printf(Perl_debug_log,
254 "Underlying LC_NUMERIC locale now is C\n");
255 }
256#endif
98994639
HS
257
258#endif /* USE_LOCALE_NUMERIC */
259}
260
261void
262Perl_set_numeric_local(pTHX)
263{
264#ifdef USE_LOCALE_NUMERIC
28c1bf33
KW
265 /* Toggle the LC_NUMERIC locale to the current underlying default. Most
266 * code should use the macros like SET_NUMERIC_LOCAL() in perl.h instead of
267 * calling this directly. The macro avoids calling this routine if
268 * toggling isn't necessary according to our records (which could be wrong
269 * if some XS code has changed the locale behind our back) */
a9b8c0d8
KW
270
271 setlocale(LC_NUMERIC, PL_numeric_name);
272 PL_numeric_standard = isNAME_C_OR_POSIX(PL_numeric_name);
273 PL_numeric_local = TRUE;
274 set_numeric_radix();
2fcc0ca9
KW
275#ifdef DEBUGGING
276 if (DEBUG_L_TEST || debug_initialization) {
277 PerlIO_printf(Perl_debug_log,
69014004 278 "Underlying LC_NUMERIC locale now is %s\n",
2fcc0ca9
KW
279 PL_numeric_name);
280 }
281#endif
98994639
HS
282
283#endif /* USE_LOCALE_NUMERIC */
284}
285
286/*
287 * Set up for a new ctype locale.
288 */
289void
8772537c 290Perl_new_ctype(pTHX_ const char *newctype)
98994639
HS
291{
292#ifdef USE_LOCALE_CTYPE
0d071d52
KW
293
294 /* Called after all libc setlocale() calls affecting LC_CTYPE, to tell
295 * core Perl this and that 'newctype' is the name of the new locale.
296 *
297 * This function sets up the folding arrays for all 256 bytes, assuming
298 * that tofold() is tolc() since fold case is not a concept in POSIX,
299 *
300 * Any code changing the locale (outside this file) should use
301 * POSIX::setlocale, which calls this function. Therefore this function
302 * should be called directly only from this file and from
303 * POSIX::setlocale() */
304
27da23d5 305 dVAR;
68067e4e 306 UV i;
98994639 307
7918f24d
NC
308 PERL_ARGS_ASSERT_NEW_CTYPE;
309
215c5139
KW
310 /* We will replace any bad locale warning with 1) nothing if the new one is
311 * ok; or 2) a new warning for the bad new locale */
312 if (PL_warn_locale) {
313 SvREFCNT_dec_NN(PL_warn_locale);
314 PL_warn_locale = NULL;
315 }
316
c1284011 317 PL_in_utf8_CTYPE_locale = _is_cur_LC_category_utf8(LC_CTYPE);
31f05a37
KW
318
319 /* A UTF-8 locale gets standard rules. But note that code still has to
320 * handle this specially because of the three problematic code points */
321 if (PL_in_utf8_CTYPE_locale) {
322 Copy(PL_fold_latin1, PL_fold_locale, 256, U8);
323 }
324 else {
8c6180a9
KW
325 /* Assume enough space for every character being bad. 4 spaces each
326 * for the 94 printable characters that are output like "'x' "; and 5
327 * spaces each for "'\\' ", "'\t' ", and "'\n' "; plus a terminating
328 * NUL */
329 char bad_chars_list[ (94 * 4) + (3 * 5) + 1 ];
330
cc9eaeb0
KW
331 /* Don't check for problems if we are suppressing the warnings */
332 bool check_for_problems = ckWARN_d(WARN_LOCALE)
333 || UNLIKELY(DEBUG_L_TEST);
8c6180a9
KW
334 bool multi_byte_locale = FALSE; /* Assume is a single-byte locale
335 to start */
336 unsigned int bad_count = 0; /* Count of bad characters */
337
baa60164
KW
338 for (i = 0; i < 256; i++) {
339 if (isUPPER_LC((U8) i))
340 PL_fold_locale[i] = (U8) toLOWER_LC((U8) i);
341 else if (isLOWER_LC((U8) i))
342 PL_fold_locale[i] = (U8) toUPPER_LC((U8) i);
343 else
344 PL_fold_locale[i] = (U8) i;
8c6180a9
KW
345
346 /* If checking for locale problems, see if the native ASCII-range
347 * printables plus \n and \t are in their expected categories in
348 * the new locale. If not, this could mean big trouble, upending
349 * Perl's and most programs' assumptions, like having a
350 * metacharacter with special meaning become a \w. Fortunately,
351 * it's very rare to find locales that aren't supersets of ASCII
352 * nowadays. It isn't a problem for most controls to be changed
353 * into something else; we check only \n and \t, though perhaps \r
354 * could be an issue as well. */
355 if (check_for_problems
356 && (isGRAPH_A(i) || isBLANK_A(i) || i == '\n'))
357 {
358 if ((isALPHANUMERIC_A(i) && ! isALPHANUMERIC_LC(i))
359 || (isPUNCT_A(i) && ! isPUNCT_LC(i))
360 || (isBLANK_A(i) && ! isBLANK_LC(i))
361 || (i == '\n' && ! isCNTRL_LC(i)))
362 {
363 if (bad_count) { /* Separate multiple entries with a
364 blank */
365 bad_chars_list[bad_count++] = ' ';
366 }
367 bad_chars_list[bad_count++] = '\'';
368 if (isPRINT_A(i)) {
369 bad_chars_list[bad_count++] = (char) i;
370 }
371 else {
372 bad_chars_list[bad_count++] = '\\';
373 if (i == '\n') {
374 bad_chars_list[bad_count++] = 'n';
375 }
376 else {
377 assert(i == '\t');
378 bad_chars_list[bad_count++] = 't';
379 }
380 }
381 bad_chars_list[bad_count++] = '\'';
382 bad_chars_list[bad_count] = '\0';
383 }
384 }
385 }
386
387#ifdef MB_CUR_MAX
388 /* We only handle single-byte locales (outside of UTF-8 ones; so if
d35fca5f 389 * this locale requires more than one byte, there are going to be
8c6180a9 390 * problems. */
ba1a4362
KW
391 if (check_for_problems && MB_CUR_MAX > 1
392
393 /* Some platforms return MB_CUR_MAX > 1 for even the "C"
394 * locale. Just assume that the implementation for them (plus
395 * for POSIX) is correct and the > 1 value is spurious. (Since
396 * these are specially handled to never be considered UTF-8
397 * locales, as long as this is the only problem, everything
398 * should work fine */
399 && strNE(newctype, "C") && strNE(newctype, "POSIX"))
400 {
8c6180a9
KW
401 multi_byte_locale = TRUE;
402 }
403#endif
404
405 if (bad_count || multi_byte_locale) {
780fcc9f 406 PL_warn_locale = Perl_newSVpvf(aTHX_
8c6180a9 407 "Locale '%s' may not work well.%s%s%s\n",
780fcc9f 408 newctype,
8c6180a9
KW
409 (multi_byte_locale)
410 ? " Some characters in it are not recognized by"
411 " Perl."
412 : "",
413 (bad_count)
414 ? "\nThe following characters (and maybe others)"
415 " may not have the same meaning as the Perl"
416 " program expects:\n"
417 : "",
418 (bad_count)
419 ? bad_chars_list
420 : ""
421 );
cc9eaeb0 422 /* If we are actually in the scope of the locale or are debugging,
bddebb56
KW
423 * output the message now. If not in that scope, we save the
424 * message to be output at the first operation using this locale,
425 * if that actually happens. Most programs don't use locales, so
426 * they are immune to bad ones. */
cc9eaeb0 427 if (IN_LC(LC_CTYPE) || UNLIKELY(DEBUG_L_TEST)) {
780fcc9f
KW
428
429 /* We have to save 'newctype' because the setlocale() just
430 * below may destroy it. The next setlocale() further down
431 * should restore it properly so that the intermediate change
432 * here is transparent to this function's caller */
433 const char * const badlocale = savepv(newctype);
434
435 setlocale(LC_CTYPE, "C");
436
437 /* The '0' below suppresses a bogus gcc compiler warning */
438 Perl_warner(aTHX_ packWARN(WARN_LOCALE), SvPVX(PL_warn_locale), 0);
bddebb56 439
780fcc9f 440 setlocale(LC_CTYPE, badlocale);
c0f3a893 441 Safefree(badlocale);
bddebb56
KW
442
443 if (IN_LC(LC_CTYPE)) {
444 SvREFCNT_dec_NN(PL_warn_locale);
445 PL_warn_locale = NULL;
446 }
780fcc9f 447 }
baa60164 448 }
31f05a37 449 }
98994639
HS
450
451#endif /* USE_LOCALE_CTYPE */
7918f24d 452 PERL_ARGS_ASSERT_NEW_CTYPE;
8772537c 453 PERL_UNUSED_ARG(newctype);
96a5add6 454 PERL_UNUSED_CONTEXT;
98994639
HS
455}
456
98994639 457void
2726666d
KW
458Perl__warn_problematic_locale()
459{
2726666d
KW
460
461#ifdef USE_LOCALE_CTYPE
462
5f04a188
KW
463 dTHX;
464
465 /* Internal-to-core function that outputs the message in PL_warn_locale,
466 * and then NULLS it. Should be called only through the macro
467 * _CHECK_AND_WARN_PROBLEMATIC_LOCALE */
468
2726666d
KW
469 if (PL_warn_locale) {
470 /*GCC_DIAG_IGNORE(-Wformat-security); Didn't work */
471 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
472 SvPVX(PL_warn_locale),
473 0 /* dummy to avoid compiler warning */ );
474 /* GCC_DIAG_RESTORE; */
475 SvREFCNT_dec_NN(PL_warn_locale);
476 PL_warn_locale = NULL;
477 }
478
479#endif
480
481}
482
483void
8772537c 484Perl_new_collate(pTHX_ const char *newcoll)
98994639
HS
485{
486#ifdef USE_LOCALE_COLLATE
0d071d52
KW
487
488 /* Called after all libc setlocale() calls affecting LC_COLLATE, to tell
489 * core Perl this and that 'newcoll' is the name of the new locale.
490 *
491 * Any code changing the locale (outside this file) should use
492 * POSIX::setlocale, which calls this function. Therefore this function
493 * should be called directly only from this file and from
d35fca5f
KW
494 * POSIX::setlocale().
495 *
496 * The design of locale collation is that every locale change is given an
497 * index 'PL_collation_ix'. The first time a string particpates in an
498 * operation that requires collation while locale collation is active, it
499 * is given PERL_MAGIC_collxfrm magic (via sv_collxfrm_flags()). That
500 * magic includes the collation index, and the transformation of the string
501 * by strxfrm(), q.v. That transformation is used when doing comparisons,
502 * instead of the string itself. If a string changes, the magic is
503 * cleared. The next time the locale changes, the index is incremented,
504 * and so we know during a comparison that the transformation is not
505 * necessarily still valid, and so is recomputed. Note that if the locale
506 * changes enough times, the index could wrap (a U32), and it is possible
507 * that a transformation would improperly be considered valid, leading to
508 * an unlikely bug */
0d071d52 509
98994639
HS
510 if (! newcoll) {
511 if (PL_collation_name) {
512 ++PL_collation_ix;
513 Safefree(PL_collation_name);
514 PL_collation_name = NULL;
515 }
516 PL_collation_standard = TRUE;
00bf60ca 517 is_standard_collation:
98994639
HS
518 PL_collxfrm_base = 0;
519 PL_collxfrm_mult = 2;
165a1c52 520 PL_in_utf8_COLLATE_locale = FALSE;
f28f4d2a 521 PL_strxfrm_NUL_replacement = '\0';
a4a439fb 522 PL_strxfrm_max_cp = 0;
98994639
HS
523 return;
524 }
525
d35fca5f 526 /* If this is not the same locale as currently, set the new one up */
98994639
HS
527 if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
528 ++PL_collation_ix;
529 Safefree(PL_collation_name);
530 PL_collation_name = stdize_locale(savepv(newcoll));
a39edc4c 531 PL_collation_standard = isNAME_C_OR_POSIX(newcoll);
00bf60ca
KW
532 if (PL_collation_standard) {
533 goto is_standard_collation;
534 }
98994639 535
165a1c52 536 PL_in_utf8_COLLATE_locale = _is_cur_LC_category_utf8(LC_COLLATE);
f28f4d2a 537 PL_strxfrm_NUL_replacement = '\0';
a4a439fb 538 PL_strxfrm_max_cp = 0;
165a1c52 539
59c018b9
KW
540 /* A locale collation definition includes primary, secondary, tertiary,
541 * etc. weights for each character. To sort, the primary weights are
542 * used, and only if they compare equal, then the secondary weights are
543 * used, and only if they compare equal, then the tertiary, etc.
544 *
545 * strxfrm() works by taking the input string, say ABC, and creating an
546 * output transformed string consisting of first the primary weights,
547 * A¹B¹C¹ followed by the secondary ones, A²B²C²; and then the
548 * tertiary, etc, yielding A¹B¹C¹ A²B²C² A³B³C³ .... Some characters
549 * may not have weights at every level. In our example, let's say B
550 * doesn't have a tertiary weight, and A doesn't have a secondary
551 * weight. The constructed string is then going to be
552 * A¹B¹C¹ B²C² A³C³ ....
553 * This has the desired effect that strcmp() will look at the secondary
554 * or tertiary weights only if the strings compare equal at all higher
555 * priority weights. The spaces shown here, like in
c342d20e 556 * "A¹B¹C¹ A²B²C² "
59c018b9
KW
557 * are not just for readability. In the general case, these must
558 * actually be bytes, which we will call here 'separator weights'; and
559 * they must be smaller than any other weight value, but since these
560 * are C strings, only the terminating one can be a NUL (some
561 * implementations may include a non-NUL separator weight just before
562 * the NUL). Implementations tend to reserve 01 for the separator
563 * weights. They are needed so that a shorter string's secondary
564 * weights won't be misconstrued as primary weights of a longer string,
565 * etc. By making them smaller than any other weight, the shorter
566 * string will sort first. (Actually, if all secondary weights are
567 * smaller than all primary ones, there is no need for a separator
568 * weight between those two levels, etc.)
569 *
570 * The length of the transformed string is roughly a linear function of
571 * the input string. It's not exactly linear because some characters
572 * don't have weights at all levels. When we call strxfrm() we have to
573 * allocate some memory to hold the transformed string. The
574 * calculations below try to find coefficients 'm' and 'b' for this
575 * locale so that m*x + b equals how much space we need, given the size
576 * of the input string in 'x'. If we calculate too small, we increase
577 * the size as needed, and call strxfrm() again, but it is better to
578 * get it right the first time to avoid wasted expensive string
579 * transformations. */
580
98994639 581 {
79f120c8
KW
582 /* We use the string below to find how long the tranformation of it
583 * is. Almost all locales are supersets of ASCII, or at least the
584 * ASCII letters. We use all of them, half upper half lower,
585 * because if we used fewer, we might hit just the ones that are
586 * outliers in a particular locale. Most of the strings being
587 * collated will contain a preponderance of letters, and even if
588 * they are above-ASCII, they are likely to have the same number of
589 * weight levels as the ASCII ones. It turns out that digits tend
590 * to have fewer levels, and some punctuation has more, but those
591 * are relatively sparse in text, and khw believes this gives a
592 * reasonable result, but it could be changed if experience so
593 * dictates. */
594 const char longer[] = "ABCDEFGHIJKLMnopqrstuvwxyz";
595 char * x_longer; /* Transformed 'longer' */
596 Size_t x_len_longer; /* Length of 'x_longer' */
597
598 char * x_shorter; /* We also transform a substring of 'longer' */
599 Size_t x_len_shorter;
600
a4a439fb 601 /* _mem_collxfrm() is used get the transformation (though here we
79f120c8
KW
602 * are interested only in its length). It is used because it has
603 * the intelligence to handle all cases, but to work, it needs some
604 * values of 'm' and 'b' to get it started. For the purposes of
605 * this calculation we use a very conservative estimate of 'm' and
606 * 'b'. This assumes a weight can be multiple bytes, enough to
607 * hold any UV on the platform, and there are 5 levels, 4 weight
608 * bytes, and a trailing NUL. */
609 PL_collxfrm_base = 5;
610 PL_collxfrm_mult = 5 * sizeof(UV);
611
612 /* Find out how long the transformation really is */
a4a439fb
KW
613 x_longer = _mem_collxfrm(longer,
614 sizeof(longer) - 1,
615 &x_len_longer,
616
617 /* We avoid converting to UTF-8 in the
618 * called function by telling it the
619 * string is in UTF-8 if the locale is a
620 * UTF-8 one. Since the string passed
621 * here is invariant under UTF-8, we can
622 * claim it's UTF-8 even though it isn't.
623 * */
624 PL_in_utf8_COLLATE_locale);
79f120c8
KW
625 Safefree(x_longer);
626
627 /* Find out how long the transformation of a substring of 'longer'
628 * is. Together the lengths of these transformations are
629 * sufficient to calculate 'm' and 'b'. The substring is all of
630 * 'longer' except the first character. This minimizes the chances
631 * of being swayed by outliers */
a4a439fb 632 x_shorter = _mem_collxfrm(longer + 1,
79f120c8 633 sizeof(longer) - 2,
a4a439fb
KW
634 &x_len_shorter,
635 PL_in_utf8_COLLATE_locale);
79f120c8
KW
636 Safefree(x_shorter);
637
638 /* If the results are nonsensical for this simple test, the whole
639 * locale definition is suspect. Mark it so that locale collation
640 * is not active at all for it. XXX Should we warn? */
641 if ( x_len_shorter == 0
642 || x_len_longer == 0
643 || x_len_shorter >= x_len_longer)
644 {
645 PL_collxfrm_mult = 0;
646 PL_collxfrm_base = 0;
647 }
648 else {
649 SSize_t base; /* Temporary */
650
651 /* We have both: m * strlen(longer) + b = x_len_longer
652 * m * strlen(shorter) + b = x_len_shorter;
653 * subtracting yields:
654 * m * (strlen(longer) - strlen(shorter))
655 * = x_len_longer - x_len_shorter
656 * But we have set things up so that 'shorter' is 1 byte smaller
657 * than 'longer'. Hence:
658 * m = x_len_longer - x_len_shorter
659 *
660 * But if something went wrong, make sure the multiplier is at
661 * least 1.
662 */
663 if (x_len_longer > x_len_shorter) {
664 PL_collxfrm_mult = (STRLEN) x_len_longer - x_len_shorter;
665 }
666 else {
667 PL_collxfrm_mult = 1;
668 }
669
670 /* mx + b = len
671 * so: b = len - mx
672 * but in case something has gone wrong, make sure it is
673 * non-negative */
674 base = x_len_longer - PL_collxfrm_mult * (sizeof(longer) - 1);
675 if (base < 0) {
676 base = 0;
677 }
678
679 /* Add 1 for the trailing NUL */
680 PL_collxfrm_base = base + 1;
681 }
58eebef2
KW
682
683#ifdef DEBUGGING
684 if (DEBUG_L_TEST || debug_initialization) {
685 PerlIO_printf(Perl_debug_log,
b07929e4
KW
686 "%s:%d: ?UTF-8 locale=%d; x_len_shorter=%zu, "
687 "x_len_longer=%zu,"
688 " collate multipler=%zu, collate base=%zu\n",
58eebef2
KW
689 __FILE__, __LINE__,
690 PL_in_utf8_COLLATE_locale,
691 x_len_shorter, x_len_longer,
692 PL_collxfrm_mult, PL_collxfrm_base);
693 }
694#endif
98994639
HS
695 }
696 }
697
f2ce9e1c
JH
698#else
699 PERL_UNUSED_ARG(newcoll);
98994639
HS
700#endif /* USE_LOCALE_COLLATE */
701}
702
b385bb4d
KW
703#ifdef WIN32
704
705char *
706Perl_my_setlocale(pTHX_ int category, const char* locale)
707{
708 /* This, for Windows, emulates POSIX setlocale() behavior. There is no
709 * difference unless the input locale is "", which means on Windows to get
710 * the machine default, which is set via the computer's "Regional and
711 * Language Options" (or its current equivalent). In POSIX, it instead
712 * means to find the locale from the user's environment. This routine
713 * looks in the environment, and, if anything is found, uses that instead
714 * of going to the machine default. If there is no environment override,
715 * the machine default is used, as normal, by calling the real setlocale()
716 * with "". The POSIX behavior is to use the LC_ALL variable if set;
717 * otherwise to use the particular category's variable if set; otherwise to
718 * use the LANG variable. */
719
175c4cf9 720 bool override_LC_ALL = FALSE;
89f7b9aa
KW
721 char * result;
722
b385bb4d
KW
723 if (locale && strEQ(locale, "")) {
724# ifdef LC_ALL
725 locale = PerlEnv_getenv("LC_ALL");
726 if (! locale) {
727#endif
728 switch (category) {
729# ifdef LC_ALL
730 case LC_ALL:
481465ea 731 override_LC_ALL = TRUE;
b385bb4d
KW
732 break; /* We already know its variable isn't set */
733# endif
734# ifdef USE_LOCALE_TIME
735 case LC_TIME:
736 locale = PerlEnv_getenv("LC_TIME");
737 break;
738# endif
739# ifdef USE_LOCALE_CTYPE
740 case LC_CTYPE:
741 locale = PerlEnv_getenv("LC_CTYPE");
742 break;
743# endif
744# ifdef USE_LOCALE_COLLATE
745 case LC_COLLATE:
746 locale = PerlEnv_getenv("LC_COLLATE");
747 break;
748# endif
749# ifdef USE_LOCALE_MONETARY
750 case LC_MONETARY:
751 locale = PerlEnv_getenv("LC_MONETARY");
752 break;
753# endif
754# ifdef USE_LOCALE_NUMERIC
755 case LC_NUMERIC:
756 locale = PerlEnv_getenv("LC_NUMERIC");
757 break;
758# endif
759# ifdef USE_LOCALE_MESSAGES
760 case LC_MESSAGES:
761 locale = PerlEnv_getenv("LC_MESSAGES");
762 break;
763# endif
764 default:
765 /* This is a category, like PAPER_SIZE that we don't
766 * know about; and so can't provide a wrapper. */
767 break;
768 }
769 if (! locale) {
770 locale = PerlEnv_getenv("LANG");
481465ea 771 if (! locale) {
b385bb4d
KW
772 locale = "";
773 }
774 }
775# ifdef LC_ALL
776 }
777# endif
778 }
779
89f7b9aa 780 result = setlocale(category, locale);
bbc98134
KW
781 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n", __FILE__, __LINE__,
782 _setlocale_debug_string(category, locale, result)));
89f7b9aa 783
481465ea 784 if (! override_LC_ALL) {
89f7b9aa
KW
785 return result;
786 }
787
dfd77d7a 788 /* Here the input category was LC_ALL, and we have set it to what is in the
481465ea
KW
789 * LANG variable or the system default if there is no LANG. But these have
790 * lower priority than the other LC_foo variables, so override it for each
791 * one that is set. (If they are set to "", it means to use the same thing
792 * we just set LC_ALL to, so can skip) */
89f7b9aa
KW
793# ifdef USE_LOCALE_TIME
794 result = PerlEnv_getenv("LC_TIME");
730252b2 795 if (result && strNE(result, "")) {
89f7b9aa 796 setlocale(LC_TIME, result);
bbc98134
KW
797 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
798 __FILE__, __LINE__,
799 _setlocale_debug_string(LC_TIME, result, "not captured")));
89f7b9aa
KW
800 }
801# endif
802# ifdef USE_LOCALE_CTYPE
803 result = PerlEnv_getenv("LC_CTYPE");
730252b2 804 if (result && strNE(result, "")) {
89f7b9aa 805 setlocale(LC_CTYPE, result);
bbc98134
KW
806 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
807 __FILE__, __LINE__,
808 _setlocale_debug_string(LC_CTYPE, result, "not captured")));
89f7b9aa
KW
809 }
810# endif
811# ifdef USE_LOCALE_COLLATE
812 result = PerlEnv_getenv("LC_COLLATE");
730252b2 813 if (result && strNE(result, "")) {
89f7b9aa 814 setlocale(LC_COLLATE, result);
bbc98134
KW
815 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
816 __FILE__, __LINE__,
817 _setlocale_debug_string(LC_COLLATE, result, "not captured")));
89f7b9aa
KW
818 }
819# endif
820# ifdef USE_LOCALE_MONETARY
821 result = PerlEnv_getenv("LC_MONETARY");
730252b2 822 if (result && strNE(result, "")) {
89f7b9aa 823 setlocale(LC_MONETARY, result);
bbc98134
KW
824 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
825 __FILE__, __LINE__,
826 _setlocale_debug_string(LC_MONETARY, result, "not captured")));
89f7b9aa
KW
827 }
828# endif
829# ifdef USE_LOCALE_NUMERIC
830 result = PerlEnv_getenv("LC_NUMERIC");
730252b2 831 if (result && strNE(result, "")) {
89f7b9aa 832 setlocale(LC_NUMERIC, result);
bbc98134
KW
833 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
834 __FILE__, __LINE__,
835 _setlocale_debug_string(LC_NUMERIC, result, "not captured")));
89f7b9aa
KW
836 }
837# endif
838# ifdef USE_LOCALE_MESSAGES
839 result = PerlEnv_getenv("LC_MESSAGES");
730252b2 840 if (result && strNE(result, "")) {
89f7b9aa 841 setlocale(LC_MESSAGES, result);
bbc98134
KW
842 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
843 __FILE__, __LINE__,
844 _setlocale_debug_string(LC_MESSAGES, result, "not captured")));
89f7b9aa
KW
845 }
846# endif
847
bbc98134
KW
848 result = setlocale(LC_ALL, NULL);
849 DEBUG_L(PerlIO_printf(Perl_debug_log, "%s:%d: %s\n",
850 __FILE__, __LINE__,
851 _setlocale_debug_string(LC_ALL, NULL, result)));
89f7b9aa 852
bbc98134 853 return result;
b385bb4d
KW
854}
855
856#endif
857
858
98994639
HS
859/*
860 * Initialize locale awareness.
861 */
862int
863Perl_init_i18nl10n(pTHX_ int printwarn)
864{
0e92a118
KW
865 /* printwarn is
866 *
867 * 0 if not to output warning when setup locale is bad
868 * 1 if to output warning based on value of PERL_BADLANG
869 * >1 if to output regardless of PERL_BADLANG
870 *
871 * returns
98994639 872 * 1 = set ok or not applicable,
0e92a118
KW
873 * 0 = fallback to a locale of lower priority
874 * -1 = fallback to all locales failed, not even to the C locale
6b058d42
KW
875 *
876 * Under -DDEBUGGING, if the environment variable PERL_DEBUG_LOCALE_INIT is
877 * set, debugging information is output.
878 *
879 * This looks more complicated than it is, mainly due to the #ifdefs.
880 *
881 * We try to set LC_ALL to the value determined by the environment. If
882 * there is no LC_ALL on this platform, we try the individual categories we
883 * know about. If this works, we are done.
884 *
885 * But if it doesn't work, we have to do something else. We search the
886 * environment variables ourselves instead of relying on the system to do
887 * it. We look at, in order, LC_ALL, LANG, a system default locale (if we
888 * think there is one), and the ultimate fallback "C". This is all done in
889 * the same loop as above to avoid duplicating code, but it makes things
890 * more complex. After the original failure, we add the fallback
891 * possibilities to the list of locales to try, and iterate the loop
892 * through them all until one succeeds.
893 *
894 * On Ultrix, the locale MUST come from the environment, so there is
895 * preliminary code to set it. I (khw) am not sure that it is necessary,
896 * and that this couldn't be folded into the loop, but barring any real
897 * platforms to test on, it's staying as-is
898 *
899 * A slight complication is that in embedded Perls, the locale may already
900 * be set-up, and we don't want to get it from the normal environment
901 * variables. This is handled by having a special environment variable
902 * indicate we're in this situation. We simply set setlocale's 2nd
903 * parameter to be a NULL instead of "". That indicates to setlocale that
904 * it is not to change anything, but to return the current value,
905 * effectively initializing perl's db to what the locale already is.
906 *
907 * We play the same trick with NULL if a LC_ALL succeeds. We call
908 * setlocale() on the individual categores with NULL to get their existing
909 * values for our db, instead of trying to change them.
910 * */
98994639 911
0e92a118
KW
912 int ok = 1;
913
98994639 914#if defined(USE_LOCALE)
98994639
HS
915#ifdef USE_LOCALE_CTYPE
916 char *curctype = NULL;
917#endif /* USE_LOCALE_CTYPE */
918#ifdef USE_LOCALE_COLLATE
919 char *curcoll = NULL;
920#endif /* USE_LOCALE_COLLATE */
921#ifdef USE_LOCALE_NUMERIC
922 char *curnum = NULL;
923#endif /* USE_LOCALE_NUMERIC */
924#ifdef __GLIBC__
175c4cf9 925 const char * const language = savepv(PerlEnv_getenv("LANGUAGE"));
98994639 926#endif
65ebb059 927
ccd65d51
KW
928 /* NULL uses the existing already set up locale */
929 const char * const setlocale_init = (PerlEnv_getenv("PERL_SKIP_LOCALE_INIT"))
930 ? NULL
931 : "";
c3fcd832
KW
932 const char* trial_locales[5]; /* 5 = 1 each for "", LC_ALL, LANG, "", C */
933 unsigned int trial_locales_count;
175c4cf9
KW
934 const char * const lc_all = savepv(PerlEnv_getenv("LC_ALL"));
935 const char * const lang = savepv(PerlEnv_getenv("LANG"));
98994639 936 bool setlocale_failure = FALSE;
65ebb059
KW
937 unsigned int i;
938 char *p;
175c4cf9
KW
939
940 /* A later getenv() could zap this, so only use here */
941 const char * const bad_lang_use_once = PerlEnv_getenv("PERL_BADLANG");
942
943 const bool locwarn = (printwarn > 1
944 || (printwarn
945 && (! bad_lang_use_once
22ff3130
HS
946 || (
947 /* disallow with "" or "0" */
948 *bad_lang_use_once
949 && strNE("0", bad_lang_use_once)))));
0e92a118 950 bool done = FALSE;
5d1187d1
KW
951 char * sl_result; /* return from setlocale() */
952 char * locale_param;
6bce99ee
JH
953#ifdef WIN32
954 /* In some systems you can find out the system default locale
955 * and use that as the fallback locale. */
956# define SYSTEM_DEFAULT_LOCALE
957#endif
958#ifdef SYSTEM_DEFAULT_LOCALE
65ebb059 959 const char *system_default_locale = NULL;
6bce99ee 960#endif
98994639 961
2fcc0ca9 962#ifdef DEBUGGING
27cdc72e 963 DEBUG_INITIALIZATION_set((PerlEnv_getenv("PERL_DEBUG_LOCALE_INIT"))
2fcc0ca9 964 ? TRUE
27cdc72e 965 : FALSE);
2fcc0ca9
KW
966# define DEBUG_LOCALE_INIT(category, locale, result) \
967 STMT_START { \
968 if (debug_initialization) { \
969 PerlIO_printf(Perl_debug_log, \
970 "%s:%d: %s\n", \
971 __FILE__, __LINE__, \
972 _setlocale_debug_string(category, \
973 locale, \
974 result)); \
975 } \
976 } STMT_END
977#else
978# define DEBUG_LOCALE_INIT(a,b,c)
979#endif
980
0e92a118
KW
981#ifndef LOCALE_ENVIRON_REQUIRED
982 PERL_UNUSED_VAR(done);
5d1187d1 983 PERL_UNUSED_VAR(locale_param);
0e92a118 984#else
98994639
HS
985
986 /*
987 * Ultrix setlocale(..., "") fails if there are no environment
988 * variables from which to get a locale name.
989 */
990
b3e384bf 991# ifdef LC_ALL
98994639 992 if (lang) {
5d1187d1
KW
993 sl_result = my_setlocale(LC_ALL, setlocale_init);
994 DEBUG_LOCALE_INIT(LC_ALL, setlocale_init, sl_result);
995 if (sl_result)
98994639
HS
996 done = TRUE;
997 else
998 setlocale_failure = TRUE;
999 }
5d1187d1 1000 if (! setlocale_failure) {
b3e384bf 1001# ifdef USE_LOCALE_CTYPE
5d1187d1
KW
1002 locale_param = (! done && (lang || PerlEnv_getenv("LC_CTYPE")))
1003 ? setlocale_init
1004 : NULL;
1005 curctype = my_setlocale(LC_CTYPE, locale_param);
1006 DEBUG_LOCALE_INIT(LC_CTYPE, locale_param, sl_result);
1007 if (! curctype)
98994639
HS
1008 setlocale_failure = TRUE;
1009 else
1010 curctype = savepv(curctype);
b3e384bf
KW
1011# endif /* USE_LOCALE_CTYPE */
1012# ifdef USE_LOCALE_COLLATE
5d1187d1
KW
1013 locale_param = (! done && (lang || PerlEnv_getenv("LC_COLLATE")))
1014 ? setlocale_init
1015 : NULL;
1016 curcoll = my_setlocale(LC_COLLATE, locale_param);
1017 DEBUG_LOCALE_INIT(LC_COLLATE, locale_param, sl_result);
1018 if (! curcoll)
98994639
HS
1019 setlocale_failure = TRUE;
1020 else
1021 curcoll = savepv(curcoll);
b3e384bf
KW
1022# endif /* USE_LOCALE_COLLATE */
1023# ifdef USE_LOCALE_NUMERIC
5d1187d1
KW
1024 locale_param = (! done && (lang || PerlEnv_getenv("LC_NUMERIC")))
1025 ? setlocale_init
1026 : NULL;
1027 curnum = my_setlocale(LC_NUMERIC, locale_param);
1028 DEBUG_LOCALE_INIT(LC_NUMERIC, locale_param, sl_result);
1029 if (! curnum)
98994639
HS
1030 setlocale_failure = TRUE;
1031 else
1032 curnum = savepv(curnum);
b3e384bf 1033# endif /* USE_LOCALE_NUMERIC */
a782673d 1034# ifdef USE_LOCALE_MESSAGES
5d1187d1
KW
1035 locale_param = (! done && (lang || PerlEnv_getenv("LC_MESSAGES")))
1036 ? setlocale_init
1037 : NULL;
1038 sl_result = my_setlocale(LC_MESSAGES, locale_param);
1039 DEBUG_LOCALE_INIT(LC_MESSAGES, locale_param, sl_result);
9f42613c 1040 if (! sl_result) {
a782673d
KW
1041 setlocale_failure = TRUE;
1042 }
1043# endif /* USE_LOCALE_MESSAGES */
c835d6be 1044# ifdef USE_LOCALE_MONETARY
5d1187d1
KW
1045 locale_param = (! done && (lang || PerlEnv_getenv("LC_MONETARY")))
1046 ? setlocale_init
1047 : NULL;
1048 sl_result = my_setlocale(LC_MONETARY, locale_param);
1049 DEBUG_LOCALE_INIT(LC_MONETARY, locale_param, sl_result);
1050 if (! sl_result) {
c835d6be
KW
1051 setlocale_failure = TRUE;
1052 }
1053# endif /* USE_LOCALE_MONETARY */
98994639
HS
1054 }
1055
b3e384bf 1056# endif /* LC_ALL */
98994639
HS
1057
1058#endif /* !LOCALE_ENVIRON_REQUIRED */
1059
65ebb059 1060 /* We try each locale in the list until we get one that works, or exhaust
20a240df
KW
1061 * the list. Normally the loop is executed just once. But if setting the
1062 * locale fails, inside the loop we add fallback trials to the array and so
1063 * will execute the loop multiple times */
c3fcd832
KW
1064 trial_locales[0] = setlocale_init;
1065 trial_locales_count = 1;
65ebb059
KW
1066 for (i= 0; i < trial_locales_count; i++) {
1067 const char * trial_locale = trial_locales[i];
1068
1069 if (i > 0) {
1070
1071 /* XXX This is to preserve old behavior for LOCALE_ENVIRON_REQUIRED
1072 * when i==0, but I (khw) don't think that behavior makes much
1073 * sense */
1074 setlocale_failure = FALSE;
1075
6bce99ee
JH
1076#ifdef SYSTEM_DEFAULT_LOCALE
1077# ifdef WIN32
65ebb059
KW
1078 /* On Windows machines, an entry of "" after the 0th means to use
1079 * the system default locale, which we now proceed to get. */
1080 if (strEQ(trial_locale, "")) {
1081 unsigned int j;
1082
1083 /* Note that this may change the locale, but we are going to do
1084 * that anyway just below */
1085 system_default_locale = setlocale(LC_ALL, "");
5d1187d1 1086 DEBUG_LOCALE_INIT(LC_ALL, "", system_default_locale);
65ebb059
KW
1087
1088 /* Skip if invalid or it's already on the list of locales to
1089 * try */
1090 if (! system_default_locale) {
1091 goto next_iteration;
1092 }
1093 for (j = 0; j < trial_locales_count; j++) {
1094 if (strEQ(system_default_locale, trial_locales[j])) {
1095 goto next_iteration;
1096 }
1097 }
1098
1099 trial_locale = system_default_locale;
1100 }
6bce99ee
JH
1101# endif /* WIN32 */
1102#endif /* SYSTEM_DEFAULT_LOCALE */
65ebb059
KW
1103 }
1104
98994639 1105#ifdef LC_ALL
5d1187d1
KW
1106 sl_result = my_setlocale(LC_ALL, trial_locale);
1107 DEBUG_LOCALE_INIT(LC_ALL, trial_locale, sl_result);
1108 if (! sl_result) {
49c85077 1109 setlocale_failure = TRUE;
7cd8b568
KW
1110 }
1111 else {
1112 /* Since LC_ALL succeeded, it should have changed all the other
1113 * categories it can to its value; so we massage things so that the
1114 * setlocales below just return their category's current values.
1115 * This adequately handles the case in NetBSD where LC_COLLATE may
1116 * not be defined for a locale, and setting it individually will
1117 * fail, whereas setting LC_ALL suceeds, leaving LC_COLLATE set to
1118 * the POSIX locale. */
1119 trial_locale = NULL;
1120 }
98994639
HS
1121#endif /* LC_ALL */
1122
49c85077 1123 if (!setlocale_failure) {
98994639 1124#ifdef USE_LOCALE_CTYPE
49c85077 1125 Safefree(curctype);
5d1187d1
KW
1126 curctype = my_setlocale(LC_CTYPE, trial_locale);
1127 DEBUG_LOCALE_INIT(LC_CTYPE, trial_locale, curctype);
1128 if (! curctype)
49c85077
KW
1129 setlocale_failure = TRUE;
1130 else
1131 curctype = savepv(curctype);
98994639
HS
1132#endif /* USE_LOCALE_CTYPE */
1133#ifdef USE_LOCALE_COLLATE
49c85077 1134 Safefree(curcoll);
5d1187d1
KW
1135 curcoll = my_setlocale(LC_COLLATE, trial_locale);
1136 DEBUG_LOCALE_INIT(LC_COLLATE, trial_locale, curcoll);
1137 if (! curcoll)
49c85077
KW
1138 setlocale_failure = TRUE;
1139 else
1140 curcoll = savepv(curcoll);
98994639
HS
1141#endif /* USE_LOCALE_COLLATE */
1142#ifdef USE_LOCALE_NUMERIC
49c85077 1143 Safefree(curnum);
5d1187d1
KW
1144 curnum = my_setlocale(LC_NUMERIC, trial_locale);
1145 DEBUG_LOCALE_INIT(LC_NUMERIC, trial_locale, curnum);
1146 if (! curnum)
49c85077
KW
1147 setlocale_failure = TRUE;
1148 else
1149 curnum = savepv(curnum);
98994639 1150#endif /* USE_LOCALE_NUMERIC */
a782673d 1151#ifdef USE_LOCALE_MESSAGES
5d1187d1
KW
1152 sl_result = my_setlocale(LC_MESSAGES, trial_locale);
1153 DEBUG_LOCALE_INIT(LC_MESSAGES, trial_locale, sl_result);
1154 if (! (sl_result))
a782673d
KW
1155 setlocale_failure = TRUE;
1156#endif /* USE_LOCALE_MESSAGES */
c835d6be 1157#ifdef USE_LOCALE_MONETARY
5d1187d1
KW
1158 sl_result = my_setlocale(LC_MONETARY, trial_locale);
1159 DEBUG_LOCALE_INIT(LC_MONETARY, trial_locale, sl_result);
1160 if (! (sl_result))
c835d6be
KW
1161 setlocale_failure = TRUE;
1162#endif /* USE_LOCALE_MONETARY */
1163
49c85077
KW
1164 if (! setlocale_failure) { /* Success */
1165 break;
1166 }
65ebb059 1167 }
98994639 1168
49c85077
KW
1169 /* Here, something failed; will need to try a fallback. */
1170 ok = 0;
65ebb059 1171
49c85077
KW
1172 if (i == 0) {
1173 unsigned int j;
98994639 1174
65ebb059 1175 if (locwarn) { /* Output failure info only on the first one */
98994639
HS
1176#ifdef LC_ALL
1177
49c85077
KW
1178 PerlIO_printf(Perl_error_log,
1179 "perl: warning: Setting locale failed.\n");
98994639
HS
1180
1181#else /* !LC_ALL */
1182
49c85077
KW
1183 PerlIO_printf(Perl_error_log,
1184 "perl: warning: Setting locale failed for the categories:\n\t");
20a240df 1185# ifdef USE_LOCALE_CTYPE
49c85077
KW
1186 if (! curctype)
1187 PerlIO_printf(Perl_error_log, "LC_CTYPE ");
20a240df
KW
1188# endif /* USE_LOCALE_CTYPE */
1189# ifdef USE_LOCALE_COLLATE
49c85077
KW
1190 if (! curcoll)
1191 PerlIO_printf(Perl_error_log, "LC_COLLATE ");
20a240df
KW
1192# endif /* USE_LOCALE_COLLATE */
1193# ifdef USE_LOCALE_NUMERIC
49c85077
KW
1194 if (! curnum)
1195 PerlIO_printf(Perl_error_log, "LC_NUMERIC ");
20a240df 1196# endif /* USE_LOCALE_NUMERIC */
a782673d 1197 PerlIO_printf(Perl_error_log, "and possibly others\n");
98994639
HS
1198
1199#endif /* LC_ALL */
1200
49c85077
KW
1201 PerlIO_printf(Perl_error_log,
1202 "perl: warning: Please check that your locale settings:\n");
98994639
HS
1203
1204#ifdef __GLIBC__
49c85077
KW
1205 PerlIO_printf(Perl_error_log,
1206 "\tLANGUAGE = %c%s%c,\n",
1207 language ? '"' : '(',
1208 language ? language : "unset",
1209 language ? '"' : ')');
98994639
HS
1210#endif
1211
49c85077
KW
1212 PerlIO_printf(Perl_error_log,
1213 "\tLC_ALL = %c%s%c,\n",
1214 lc_all ? '"' : '(',
1215 lc_all ? lc_all : "unset",
1216 lc_all ? '"' : ')');
98994639
HS
1217
1218#if defined(USE_ENVIRON_ARRAY)
49c85077
KW
1219 {
1220 char **e;
1221 for (e = environ; *e; e++) {
0eb7f56a
YO
1222 if (strEQs(*e, "LC_")
1223 && strNEs(*e, "LC_ALL=")
49c85077
KW
1224 && (p = strchr(*e, '=')))
1225 PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
1226 (int)(p - *e), *e, p + 1);
1227 }
1228 }
98994639 1229#else
49c85077
KW
1230 PerlIO_printf(Perl_error_log,
1231 "\t(possibly more locale environment variables)\n");
98994639
HS
1232#endif
1233
49c85077
KW
1234 PerlIO_printf(Perl_error_log,
1235 "\tLANG = %c%s%c\n",
1236 lang ? '"' : '(',
1237 lang ? lang : "unset",
1238 lang ? '"' : ')');
98994639 1239
49c85077
KW
1240 PerlIO_printf(Perl_error_log,
1241 " are supported and installed on your system.\n");
1242 }
98994639 1243
65ebb059 1244 /* Calculate what fallback locales to try. We have avoided this
f6bab5f6 1245 * until we have to, because failure is quite unlikely. This will
65ebb059
KW
1246 * usually change the upper bound of the loop we are in.
1247 *
1248 * Since the system's default way of setting the locale has not
1249 * found one that works, We use Perl's defined ordering: LC_ALL,
1250 * LANG, and the C locale. We don't try the same locale twice, so
1251 * don't add to the list if already there. (On POSIX systems, the
1252 * LC_ALL element will likely be a repeat of the 0th element "",
6b058d42
KW
1253 * but there's no harm done by doing it explicitly.
1254 *
1255 * Note that this tries the LC_ALL environment variable even on
1256 * systems which have no LC_ALL locale setting. This may or may
1257 * not have been originally intentional, but there's no real need
1258 * to change the behavior. */
65ebb059
KW
1259 if (lc_all) {
1260 for (j = 0; j < trial_locales_count; j++) {
1261 if (strEQ(lc_all, trial_locales[j])) {
1262 goto done_lc_all;
1263 }
1264 }
1265 trial_locales[trial_locales_count++] = lc_all;
1266 }
1267 done_lc_all:
98994639 1268
65ebb059
KW
1269 if (lang) {
1270 for (j = 0; j < trial_locales_count; j++) {
1271 if (strEQ(lang, trial_locales[j])) {
1272 goto done_lang;
1273 }
1274 }
1275 trial_locales[trial_locales_count++] = lang;
1276 }
1277 done_lang:
1278
1279#if defined(WIN32) && defined(LC_ALL)
1280 /* For Windows, we also try the system default locale before "C".
1281 * (If there exists a Windows without LC_ALL we skip this because
1282 * it gets too complicated. For those, the "C" is the next
1283 * fallback possibility). The "" is the same as the 0th element of
1284 * the array, but the code at the loop above knows to treat it
1285 * differently when not the 0th */
1286 trial_locales[trial_locales_count++] = "";
1287#endif
1288
1289 for (j = 0; j < trial_locales_count; j++) {
1290 if (strEQ("C", trial_locales[j])) {
1291 goto done_C;
1292 }
1293 }
1294 trial_locales[trial_locales_count++] = "C";
98994639 1295
65ebb059
KW
1296 done_C: ;
1297 } /* end of first time through the loop */
98994639 1298
65ebb059
KW
1299#ifdef WIN32
1300 next_iteration: ;
1301#endif
1302
1303 } /* end of looping through the trial locales */
1304
1305 if (ok < 1) { /* If we tried to fallback */
1306 const char* msg;
1307 if (! setlocale_failure) { /* fallback succeeded */
1308 msg = "Falling back to";
1309 }
1310 else { /* fallback failed */
98994639 1311
65ebb059
KW
1312 /* We dropped off the end of the loop, so have to decrement i to
1313 * get back to the value the last time through */
1314 i--;
98994639 1315
65ebb059
KW
1316 ok = -1;
1317 msg = "Failed to fall back to";
1318
1319 /* To continue, we should use whatever values we've got */
98994639 1320#ifdef USE_LOCALE_CTYPE
49c85077
KW
1321 Safefree(curctype);
1322 curctype = savepv(setlocale(LC_CTYPE, NULL));
5d1187d1 1323 DEBUG_LOCALE_INIT(LC_CTYPE, NULL, curctype);
98994639
HS
1324#endif /* USE_LOCALE_CTYPE */
1325#ifdef USE_LOCALE_COLLATE
49c85077
KW
1326 Safefree(curcoll);
1327 curcoll = savepv(setlocale(LC_COLLATE, NULL));
5d1187d1 1328 DEBUG_LOCALE_INIT(LC_COLLATE, NULL, curcoll);
98994639
HS
1329#endif /* USE_LOCALE_COLLATE */
1330#ifdef USE_LOCALE_NUMERIC
49c85077
KW
1331 Safefree(curnum);
1332 curnum = savepv(setlocale(LC_NUMERIC, NULL));
5d1187d1 1333 DEBUG_LOCALE_INIT(LC_NUMERIC, NULL, curnum);
98994639 1334#endif /* USE_LOCALE_NUMERIC */
65ebb059
KW
1335 }
1336
1337 if (locwarn) {
1338 const char * description;
1339 const char * name = "";
1340 if (strEQ(trial_locales[i], "C")) {
1341 description = "the standard locale";
1342 name = "C";
1343 }
6bce99ee 1344#ifdef SYSTEM_DEFAULT_LOCALE
65ebb059
KW
1345 else if (strEQ(trial_locales[i], "")) {
1346 description = "the system default locale";
1347 if (system_default_locale) {
1348 name = system_default_locale;
1349 }
1350 }
6bce99ee 1351#endif /* SYSTEM_DEFAULT_LOCALE */
65ebb059
KW
1352 else {
1353 description = "a fallback locale";
1354 name = trial_locales[i];
1355 }
1356 if (name && strNE(name, "")) {
1357 PerlIO_printf(Perl_error_log,
1358 "perl: warning: %s %s (\"%s\").\n", msg, description, name);
1359 }
1360 else {
1361 PerlIO_printf(Perl_error_log,
1362 "perl: warning: %s %s.\n", msg, description);
1363 }
1364 }
1365 } /* End of tried to fallback */
98994639
HS
1366
1367#ifdef USE_LOCALE_CTYPE
1368 new_ctype(curctype);
1369#endif /* USE_LOCALE_CTYPE */
1370
1371#ifdef USE_LOCALE_COLLATE
1372 new_collate(curcoll);
1373#endif /* USE_LOCALE_COLLATE */
1374
1375#ifdef USE_LOCALE_NUMERIC
1376 new_numeric(curnum);
1377#endif /* USE_LOCALE_NUMERIC */
b310b053 1378
8ef6e574 1379#if defined(USE_PERLIO) && defined(USE_LOCALE_CTYPE)
49c85077
KW
1380 /* Set PL_utf8locale to TRUE if using PerlIO _and_ the current LC_CTYPE
1381 * locale is UTF-8. If PL_utf8locale and PL_unicode (set by -C or by
1382 * $ENV{PERL_UNICODE}) are true, perl.c:S_parse_body() will turn on the
1383 * PerlIO :utf8 layer on STDIN, STDOUT, STDERR, _and_ the default open
1384 * discipline. */
c1284011 1385 PL_utf8locale = _is_cur_LC_category_utf8(LC_CTYPE);
49c85077 1386
a05d7ebb 1387 /* Set PL_unicode to $ENV{PERL_UNICODE} if using PerlIO.
fde18df1
JH
1388 This is an alternative to using the -C command line switch
1389 (the -C if present will override this). */
1390 {
dd374669 1391 const char *p = PerlEnv_getenv("PERL_UNICODE");
a05d7ebb 1392 PL_unicode = p ? parse_unicode_opts(&p) : 0;
5a22a2bb
NC
1393 if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
1394 PL_utf8cache = -1;
b310b053 1395 }
ec71e770 1396#endif
b310b053 1397
98994639 1398#ifdef USE_LOCALE_CTYPE
43c5f42d 1399 Safefree(curctype);
98994639
HS
1400#endif /* USE_LOCALE_CTYPE */
1401#ifdef USE_LOCALE_COLLATE
43c5f42d 1402 Safefree(curcoll);
98994639
HS
1403#endif /* USE_LOCALE_COLLATE */
1404#ifdef USE_LOCALE_NUMERIC
43c5f42d 1405 Safefree(curnum);
98994639 1406#endif /* USE_LOCALE_NUMERIC */
8ef6e574 1407
175c4cf9
KW
1408#ifdef __GLIBC__
1409 Safefree(language);
1410#endif
1411
1412 Safefree(lc_all);
1413 Safefree(lang);
1414
e3305790
KW
1415#else /* !USE_LOCALE */
1416 PERL_UNUSED_ARG(printwarn);
1417#endif /* USE_LOCALE */
1418
2fcc0ca9
KW
1419#ifdef DEBUGGING
1420 /* So won't continue to output stuff */
27cdc72e 1421 DEBUG_INITIALIZATION_set(FALSE);
2fcc0ca9
KW
1422#endif
1423
98994639
HS
1424 return ok;
1425}
1426
98994639
HS
1427#ifdef USE_LOCALE_COLLATE
1428
a4a439fb 1429char *
a4a439fb
KW
1430Perl__mem_collxfrm(pTHX_ const char *input_string,
1431 STRLEN len, /* Length of 'input_string' */
1432 STRLEN *xlen, /* Set to length of returned string
1433 (not including the collation index
1434 prefix) */
1435 bool utf8 /* Is the input in UTF-8? */
6696cfa7 1436 )
98994639 1437{
a4a439fb
KW
1438
1439 /* _mem_collxfrm() is a bit like strxfrm() but with two important
1440 * differences. First, it handles embedded NULs. Second, it allocates a bit
1441 * more memory than needed for the transformed data itself. The real
55e5378d 1442 * transformed data begins at offset COLLXFRM_HDR_LEN. *xlen is set to
a4a439fb
KW
1443 * the length of that, and doesn't include the collation index size.
1444 * Please see sv_collxfrm() to see how this is used. */
1445
55e5378d
KW
1446#define COLLXFRM_HDR_LEN sizeof(PL_collation_ix)
1447
6696cfa7
KW
1448 char * s = (char *) input_string;
1449 STRLEN s_strlen = strlen(input_string);
79f120c8 1450 char *xbuf = NULL;
55e5378d 1451 STRLEN xAlloc; /* xalloc is a reserved word in VC */
17f41037 1452 STRLEN length_in_chars;
c664130f 1453 bool first_time = TRUE; /* Cleared after first loop iteration */
98994639 1454
a4a439fb
KW
1455 PERL_ARGS_ASSERT__MEM_COLLXFRM;
1456
1457 /* Must be NUL-terminated */
1458 assert(*(input_string + len) == '\0');
7918f24d 1459
79f120c8
KW
1460 /* If this locale has defective collation, skip */
1461 if (PL_collxfrm_base == 0 && PL_collxfrm_mult == 0) {
c7202dee
KW
1462 DEBUG_L(PerlIO_printf(Perl_debug_log,
1463 "_mem_collxfrm: locale's collation is defective\n"));
79f120c8
KW
1464 goto bad;
1465 }
1466
6696cfa7
KW
1467 /* Replace any embedded NULs with the control that sorts before any others.
1468 * This will give as good as possible results on strings that don't
1469 * otherwise contain that character, but otherwise there may be
1470 * less-than-perfect results with that character and NUL. This is
fdc080f3 1471 * unavoidable unless we replace strxfrm with our own implementation. */
1e4c9676 1472 if (s_strlen < len) { /* Only execute if there is an embedded NUL */
6696cfa7
KW
1473 char * e = s + len;
1474 char * sans_nuls;
fdc080f3
KW
1475 STRLEN sans_nuls_len;
1476 STRLEN sans_nuls_pos;
94762aa0 1477 int try_non_controls;
afc4976f
KW
1478 char this_replacement_char[] = "?\0"; /* Room for a two-byte string,
1479 making sure 2nd byte is NUL.
1480 */
1481 STRLEN this_replacement_len;
1482
1e4c9676
KW
1483 /* If we don't know what non-NUL control character sorts lowest for
1484 * this locale, find it */
f28f4d2a 1485 if (PL_strxfrm_NUL_replacement == '\0') {
6696cfa7 1486 int j;
afc4976f 1487 char * cur_min_x = NULL; /* The min_char's xfrm, (except it also
6696cfa7
KW
1488 includes the collation index
1489 prefixed. */
1490
91c0e2e0 1491 DEBUG_Lv(PerlIO_printf(Perl_debug_log, "Looking to replace NUL\n"));
94762aa0
KW
1492
1493 /* Unlikely, but it may be that no control will work to replace
1e4c9676
KW
1494 * NUL, in which case we instead look for any character. Controls
1495 * are preferred because collation order is, in general, context
1496 * sensitive, with adjoining characters affecting the order, and
1497 * controls are less likely to have such interactions, allowing the
1498 * NUL-replacement to stand on its own. (Another way to look at it
1499 * is to imagine what would happen if the NUL were replaced by a
1500 * combining character; it wouldn't work out all that well.) */
94762aa0
KW
1501 for (try_non_controls = 0;
1502 try_non_controls < 2;
1503 try_non_controls++)
1504 {
d4ff9586
KW
1505 /* Look through all legal code points (NUL isn't) */
1506 for (j = 1; j < 256; j++) {
1507 char * x; /* j's xfrm plus collation index */
1508 STRLEN x_len; /* length of 'x' */
1509 STRLEN trial_len = 1;
1510
afc4976f
KW
1511 /* Create a 1 byte string of the current code point */
1512 char cur_source[] = { (char) j, '\0' };
d4ff9586 1513
afc4976f
KW
1514 if (! try_non_controls && (PL_in_utf8_COLLATE_locale)
1515 ? ! isCNTRL_L1(j)
1516 : ! isCNTRL_LC(j))
1517 {
d4ff9586 1518 continue;
6696cfa7 1519 }
6696cfa7 1520
d4ff9586
KW
1521 /* Then transform it */
1522 x = _mem_collxfrm(cur_source, trial_len, &x_len,
afc4976f 1523 0 /* The string is not in UTF-8 */);
6696cfa7 1524
1e4c9676 1525 /* Ignore any character that didn't successfully transform.
d4ff9586
KW
1526 * */
1527 if (! x) {
1528 continue;
1529 }
6696cfa7 1530
d4ff9586
KW
1531 /* If this character's transformation is lower than
1532 * the current lowest, this one becomes the lowest */
1533 if ( cur_min_x == NULL
1534 || strLT(x + COLLXFRM_HDR_LEN,
1535 cur_min_x + COLLXFRM_HDR_LEN))
1536 {
f28f4d2a 1537 PL_strxfrm_NUL_replacement = j;
d4ff9586 1538 cur_min_x = x;
d4ff9586
KW
1539 }
1540 else {
1541 Safefree(x);
1542 }
1e4c9676 1543 } /* end of loop through all 255 characters */
6696cfa7 1544
1e4c9676 1545 /* Stop looking if found */
94762aa0
KW
1546 if (cur_min_x) {
1547 break;
1548 }
1549
1550 /* Unlikely, but possible, if there aren't any controls that
1551 * work in the locale, repeat the loop, looking for any
1552 * character that works */
1553 DEBUG_L(PerlIO_printf(Perl_debug_log,
1554 "_mem_collxfrm: No control worked. Trying non-controls\n"));
1e4c9676 1555 } /* End of loop to try first the controls, then any char */
6696cfa7 1556
94762aa0
KW
1557 if (! cur_min_x) {
1558 DEBUG_L(PerlIO_printf(Perl_debug_log,
1559 "_mem_collxfrm: Couldn't find any character to replace"
1560 " embedded NULs in locale %s with", PL_collation_name));
1561 goto bad;
58eebef2
KW
1562 }
1563
94762aa0
KW
1564 DEBUG_L(PerlIO_printf(Perl_debug_log,
1565 "_mem_collxfrm: Replacing embedded NULs in locale %s with "
f28f4d2a 1566 "0x%02X\n", PL_collation_name, PL_strxfrm_NUL_replacement));
94762aa0 1567
6696cfa7 1568 Safefree(cur_min_x);
1e4c9676 1569 } /* End of determining the character that is to replace NULs */
afc4976f
KW
1570
1571 /* If the replacement is variant under UTF-8, it must match the
1572 * UTF8-ness as the original */
f28f4d2a
KW
1573 if ( ! UVCHR_IS_INVARIANT(PL_strxfrm_NUL_replacement) && utf8) {
1574 this_replacement_char[0] =
1575 UTF8_EIGHT_BIT_HI(PL_strxfrm_NUL_replacement);
1576 this_replacement_char[1] =
1577 UTF8_EIGHT_BIT_LO(PL_strxfrm_NUL_replacement);
afc4976f
KW
1578 this_replacement_len = 2;
1579 }
1580 else {
f28f4d2a 1581 this_replacement_char[0] = PL_strxfrm_NUL_replacement;
afc4976f
KW
1582 /* this_replacement_char[1] = '\0' was done at initialization */
1583 this_replacement_len = 1;
6696cfa7
KW
1584 }
1585
1586 /* The worst case length for the replaced string would be if every
1587 * character in it is NUL. Multiply that by the length of each
1588 * replacement, and allow for a trailing NUL */
afc4976f 1589 sans_nuls_len = (len * this_replacement_len) + 1;
fdc080f3 1590 Newx(sans_nuls, sans_nuls_len, char);
6696cfa7 1591 *sans_nuls = '\0';
fdc080f3 1592 sans_nuls_pos = 0;
6696cfa7 1593
6696cfa7
KW
1594 /* Replace each NUL with the lowest collating control. Loop until have
1595 * exhausted all the NULs */
1596 while (s + s_strlen < e) {
fdc080f3
KW
1597 sans_nuls_pos = my_strlcat(sans_nuls + sans_nuls_pos,
1598 s,
1599 sans_nuls_len);
6696cfa7
KW
1600
1601 /* Do the actual replacement */
fdc080f3 1602 sans_nuls_pos = my_strlcat(sans_nuls + sans_nuls_pos,
afc4976f 1603 this_replacement_char,
fdc080f3 1604 sans_nuls_len);
6696cfa7
KW
1605
1606 /* Move past the input NUL */
1607 s += s_strlen + 1;
1608 s_strlen = strlen(s);
1609 }
1610
1611 /* And add anything that trails the final NUL */
fdc080f3 1612 my_strlcat(sans_nuls + sans_nuls_pos, s, sans_nuls_len);
6696cfa7
KW
1613
1614 /* Switch so below we transform this modified string */
1615 s = sans_nuls;
1616 len = strlen(s);
1e4c9676 1617 } /* End of replacing NULs */
6696cfa7 1618
a4a439fb
KW
1619 /* Make sure the UTF8ness of the string and locale match */
1620 if (utf8 != PL_in_utf8_COLLATE_locale) {
1621 const char * const t = s; /* Temporary so we can later find where the
1622 input was */
1623
1624 /* Here they don't match. Change the string's to be what the locale is
1625 * expecting */
1626
1627 if (! utf8) { /* locale is UTF-8, but input isn't; upgrade the input */
1628 s = (char *) bytes_to_utf8((const U8 *) s, &len);
1629 utf8 = TRUE;
1630 }
1631 else { /* locale is not UTF-8; but input is; downgrade the input */
1632
1633 s = (char *) bytes_from_utf8((const U8 *) s, &len, &utf8);
1634
1635 /* If the downgrade was successful we are done, but if the input
1636 * contains things that require UTF-8 to represent, have to do
1637 * damage control ... */
1638 if (UNLIKELY(utf8)) {
1639
1640 /* What we do is construct a non-UTF-8 string with
1641 * 1) the characters representable by a single byte converted
1642 * to be so (if necessary);
1643 * 2) and the rest converted to collate the same as the
1644 * highest collating representable character. That makes
1645 * them collate at the end. This is similar to how we
1646 * handle embedded NULs, but we use the highest collating
1647 * code point instead of the smallest. Like the NUL case,
1648 * this isn't perfect, but is the best we can reasonably
1649 * do. Every above-255 code point will sort the same as
1650 * the highest-sorting 0-255 code point. If that code
1651 * point can combine in a sequence with some other code
1652 * points for weight calculations, us changing something to
1653 * be it can adversely affect the results. But in most
1654 * cases, it should work reasonably. And note that this is
1655 * really an illegal situation: using code points above 255
1656 * on a locale where only 0-255 are valid. If two strings
1657 * sort entirely equal, then the sort order for the
1658 * above-255 code points will be in code point order. */
1659
1660 utf8 = FALSE;
1661
1662 /* If we haven't calculated the code point with the maximum
1663 * collating order for this locale, do so now */
1664 if (! PL_strxfrm_max_cp) {
1665 int j;
1666
1667 /* The current transformed string that collates the
1668 * highest (except it also includes the prefixed collation
1669 * index. */
1670 char * cur_max_x = NULL;
1671
1672 /* Look through all legal code points (NUL isn't) */
1673 for (j = 1; j < 256; j++) {
1674 char * x;
1675 STRLEN x_len;
1676
1677 /* Create a 1-char string of the current code point. */
1678 char cur_source[] = { (char) j, '\0' };
1679
1680 /* Then transform it */
1681 x = _mem_collxfrm(cur_source, 1, &x_len, FALSE);
1682
1683 /* If something went wrong (which it shouldn't), just
1684 * ignore this code point */
94762aa0 1685 if (! x) {
a4a439fb
KW
1686 continue;
1687 }
1688
1689 /* If this character's transformation is higher than
1690 * the current highest, this one becomes the highest */
1691 if ( cur_max_x == NULL
55e5378d
KW
1692 || strGT(x + COLLXFRM_HDR_LEN,
1693 cur_max_x + COLLXFRM_HDR_LEN))
a4a439fb
KW
1694 {
1695 PL_strxfrm_max_cp = j;
1696 cur_max_x = x;
1697 }
1698 else {
1699 Safefree(x);
1700 }
1701 }
1702
94762aa0
KW
1703 if (! cur_max_x) {
1704 DEBUG_L(PerlIO_printf(Perl_debug_log,
1705 "_mem_collxfrm: Couldn't find any character to"
1706 " replace above-Latin1 chars in locale %s with",
1707 PL_collation_name));
1708 goto bad;
1709 }
1710
58eebef2
KW
1711 DEBUG_L(PerlIO_printf(Perl_debug_log,
1712 "_mem_collxfrm: highest 1-byte collating character"
1713 " in locale %s is 0x%02X\n",
1714 PL_collation_name,
1715 PL_strxfrm_max_cp));
58eebef2 1716
a4a439fb
KW
1717 Safefree(cur_max_x);
1718 }
1719
1720 /* Here we know which legal code point collates the highest.
1721 * We are ready to construct the non-UTF-8 string. The length
1722 * will be at least 1 byte smaller than the input string
1723 * (because we changed at least one 2-byte character into a
1724 * single byte), but that is eaten up by the trailing NUL */
1725 Newx(s, len, char);
1726
1727 {
1728 STRLEN i;
1729 STRLEN d= 0;
042d9e50 1730 char * e = (char *) t + len;
a4a439fb
KW
1731
1732 for (i = 0; i < len; i+= UTF8SKIP(t + i)) {
1733 U8 cur_char = t[i];
1734 if (UTF8_IS_INVARIANT(cur_char)) {
1735 s[d++] = cur_char;
1736 }
042d9e50 1737 else if (UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(t + i, e)) {
a4a439fb
KW
1738 s[d++] = EIGHT_BIT_UTF8_TO_NATIVE(cur_char, t[i+1]);
1739 }
1740 else { /* Replace illegal cp with highest collating
1741 one */
1742 s[d++] = PL_strxfrm_max_cp;
1743 }
1744 }
1745 s[d++] = '\0';
1746 Renew(s, d, char); /* Free up unused space */
1747 }
1748 }
1749 }
1750
1751 /* Here, we have constructed a modified version of the input. It could
1752 * be that we already had a modified copy before we did this version.
1753 * If so, that copy is no longer needed */
1754 if (t != input_string) {
1755 Safefree(t);
1756 }
1757 }
1758
17f41037
KW
1759 length_in_chars = (utf8)
1760 ? utf8_length((U8 *) s, (U8 *) s + len)
1761 : len;
1762
59c018b9
KW
1763 /* The first element in the output is the collation id, used by
1764 * sv_collxfrm(); then comes the space for the transformed string. The
1765 * equation should give us a good estimate as to how much is needed */
55e5378d 1766 xAlloc = COLLXFRM_HDR_LEN
a4a439fb 1767 + PL_collxfrm_base
17f41037 1768 + (PL_collxfrm_mult * length_in_chars);
a02a5408 1769 Newx(xbuf, xAlloc, char);
c7202dee
KW
1770 if (UNLIKELY(! xbuf)) {
1771 DEBUG_L(PerlIO_printf(Perl_debug_log,
1772 "_mem_collxfrm: Couldn't malloc %zu bytes\n", xAlloc));
98994639 1773 goto bad;
c7202dee 1774 }
98994639 1775
d35fca5f 1776 /* Store the collation id */
98994639 1777 *(U32*)xbuf = PL_collation_ix;
d35fca5f
KW
1778
1779 /* Then the transformation of the input. We loop until successful, or we
1780 * give up */
4ebeff16 1781 for (;;) {
1adab0a7 1782
55e5378d 1783 *xlen = strxfrm(xbuf + COLLXFRM_HDR_LEN, s, xAlloc - COLLXFRM_HDR_LEN);
4ebeff16
KW
1784
1785 /* If the transformed string occupies less space than we told strxfrm()
1786 * was available, it means it successfully transformed the whole
1787 * string. */
55e5378d 1788 if (*xlen < xAlloc - COLLXFRM_HDR_LEN) {
17f41037 1789
1adab0a7
KW
1790 /* Some systems include a trailing NUL in the returned length.
1791 * Ignore it, using a loop in case multiple trailing NULs are
1792 * returned. */
1793 while ( (*xlen) > 0
1794 && *(xbuf + COLLXFRM_HDR_LEN + (*xlen) - 1) == '\0')
1795 {
1796 (*xlen)--;
1797 }
1798
17f41037
KW
1799 /* If the first try didn't get it, it means our prediction was low.
1800 * Modify the coefficients so that we predict a larger value in any
1801 * future transformations */
1802 if (! first_time) {
1803 STRLEN needed = *xlen + 1; /* +1 For trailing NUL */
1804 STRLEN computed_guess = PL_collxfrm_base
1805 + (PL_collxfrm_mult * length_in_chars);
e1c30f0c
KW
1806
1807 /* On zero-length input, just keep current slope instead of
1808 * dividing by 0 */
1809 const STRLEN new_m = (length_in_chars != 0)
1810 ? needed / length_in_chars
1811 : PL_collxfrm_mult;
17f41037
KW
1812
1813 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
b07929e4
KW
1814 "%s: %d: initial size of %zu bytes for a length "
1815 "%zu string was insufficient, %zu needed\n",
17f41037 1816 __FILE__, __LINE__,
b07929e4 1817 computed_guess, length_in_chars, needed));
17f41037
KW
1818
1819 /* If slope increased, use it, but discard this result for
1820 * length 1 strings, as we can't be sure that it's a real slope
1821 * change */
1822 if (length_in_chars > 1 && new_m > PL_collxfrm_mult) {
1823#ifdef DEBUGGING
1824 STRLEN old_m = PL_collxfrm_mult;
1825 STRLEN old_b = PL_collxfrm_base;
1826#endif
1827 PL_collxfrm_mult = new_m;
1828 PL_collxfrm_base = 1; /* +1 For trailing NUL */
1829 computed_guess = PL_collxfrm_base
1830 + (PL_collxfrm_mult * length_in_chars);
1831 if (computed_guess < needed) {
1832 PL_collxfrm_base += needed - computed_guess;
1833 }
1834
1835 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
b07929e4
KW
1836 "%s: %d: slope is now %zu; was %zu, base "
1837 "is now %zu; was %zu\n",
17f41037 1838 __FILE__, __LINE__,
b07929e4
KW
1839 PL_collxfrm_mult, old_m,
1840 PL_collxfrm_base, old_b));
17f41037
KW
1841 }
1842 else { /* Slope didn't change, but 'b' did */
1843 const STRLEN new_b = needed
1844 - computed_guess
1845 + PL_collxfrm_base;
1846 DEBUG_Lv(PerlIO_printf(Perl_debug_log,
b07929e4 1847 "%s: %d: base is now %zu; was %zu\n",
17f41037 1848 __FILE__, __LINE__,
b07929e4 1849 new_b, PL_collxfrm_base));
17f41037
KW
1850 PL_collxfrm_base = new_b;
1851 }
1852 }
1853
4ebeff16
KW
1854 break;
1855 }
bb0f664e 1856
c7202dee
KW
1857 if (UNLIKELY(*xlen >= PERL_INT_MAX)) {
1858 DEBUG_L(PerlIO_printf(Perl_debug_log,
1859 "_mem_collxfrm: Needed %zu bytes, max permissible is %u\n",
1860 *xlen, PERL_INT_MAX));
4ebeff16 1861 goto bad;
c7202dee 1862 }
d35fca5f 1863
c664130f 1864 /* A well-behaved strxfrm() returns exactly how much space it needs
1adab0a7
KW
1865 * (usually not including the trailing NUL) when it fails due to not
1866 * enough space being provided. Assume that this is the case unless
1867 * it's been proven otherwise */
c664130f 1868 if (LIKELY(PL_strxfrm_is_behaved) && first_time) {
55e5378d 1869 xAlloc = *xlen + COLLXFRM_HDR_LEN + 1;
c664130f
KW
1870 }
1871 else { /* Here, either:
1872 * 1) The strxfrm() has previously shown bad behavior; or
1873 * 2) It isn't the first time through the loop, which means
1874 * that the strxfrm() is now showing bad behavior, because
1875 * we gave it what it said was needed in the previous
1876 * iteration, and it came back saying it needed still more.
1877 * (Many versions of cygwin fit this. When the buffer size
1878 * isn't sufficient, they return the input size instead of
1879 * how much is needed.)
d4ff9586
KW
1880 * Increase the buffer size by a fixed percentage and try again.
1881 * */
6ddd902c 1882 xAlloc += (xAlloc / 4) + 1;
c664130f 1883 PL_strxfrm_is_behaved = FALSE;
c664130f 1884
58eebef2
KW
1885#ifdef DEBUGGING
1886 if (DEBUG_Lv_TEST || debug_initialization) {
1887 PerlIO_printf(Perl_debug_log,
1888 "_mem_collxfrm required more space than previously calculated"
b07929e4 1889 " for locale %s, trying again with new guess=%d+%zu\n",
58eebef2 1890 PL_collation_name, (int) COLLXFRM_HDR_LEN,
b07929e4 1891 xAlloc - COLLXFRM_HDR_LEN);
58eebef2
KW
1892 }
1893#endif
1894 }
c664130f 1895
4ebeff16 1896 Renew(xbuf, xAlloc, char);
c7202dee
KW
1897 if (UNLIKELY(! xbuf)) {
1898 DEBUG_L(PerlIO_printf(Perl_debug_log,
1899 "_mem_collxfrm: Couldn't realloc %zu bytes\n", xAlloc));
4ebeff16 1900 goto bad;
c7202dee 1901 }
c664130f
KW
1902
1903 first_time = FALSE;
4ebeff16 1904 }
98994639 1905
6696cfa7 1906
58eebef2
KW
1907#ifdef DEBUGGING
1908 if (DEBUG_Lv_TEST || debug_initialization) {
c7202dee
KW
1909 Size_t i;
1910
1911 print_collxfrm_input_and_return(s, s + len, xlen, utf8);
1912 PerlIO_printf(Perl_debug_log, "Its xfrm is:");
58eebef2
KW
1913 for (i = COLLXFRM_HDR_LEN; i < *xlen + COLLXFRM_HDR_LEN; i++) {
1914 PerlIO_printf(Perl_debug_log, " %02x", (U8) xbuf[i]);
1915 }
1916 PerlIO_printf(Perl_debug_log, "\n");
1917 }
1918#endif
1919
3c5f993e 1920 /* Free up unneeded space; retain ehough for trailing NUL */
55e5378d 1921 Renew(xbuf, COLLXFRM_HDR_LEN + *xlen + 1, char);
98994639 1922
6696cfa7
KW
1923 if (s != input_string) {
1924 Safefree(s);
98994639
HS
1925 }
1926
98994639
HS
1927 return xbuf;
1928
1929 bad:
1930 Safefree(xbuf);
6696cfa7
KW
1931 if (s != input_string) {
1932 Safefree(s);
1933 }
98994639 1934 *xlen = 0;
58eebef2
KW
1935#ifdef DEBUGGING
1936 if (DEBUG_Lv_TEST || debug_initialization) {
c7202dee 1937 print_collxfrm_input_and_return(s, s + len, NULL, utf8);
58eebef2
KW
1938 }
1939#endif
98994639
HS
1940 return NULL;
1941}
1942
c7202dee
KW
1943#ifdef DEBUGGING
1944
4cbaac56 1945STATIC void
c7202dee
KW
1946S_print_collxfrm_input_and_return(pTHX_
1947 const char * const s,
1948 const char * const e,
1949 const STRLEN * const xlen,
1950 const bool is_utf8)
1951{
1952 const char * t = s;
1953 bool prev_was_printable = TRUE;
1954 bool first_time = TRUE;
1955
1956 PERL_ARGS_ASSERT_PRINT_COLLXFRM_INPUT_AND_RETURN;
1957
e5d8cfc5 1958 PerlIO_printf(Perl_debug_log, "_mem_collxfrm[%u]: returning ",
c7202dee
KW
1959 PL_collation_ix);
1960 if (xlen) {
147e3846 1961 PerlIO_printf(Perl_debug_log, "%" UVuf, (UV) *xlen);
c7202dee
KW
1962 }
1963 else {
1964 PerlIO_printf(Perl_debug_log, "NULL");
1965 }
1966 PerlIO_printf(Perl_debug_log, " for locale '%s', string='",
1967 PL_collation_name);
1968
1969 while (t < e) {
1970 UV cp = (is_utf8)
1971 ? utf8_to_uvchr_buf((U8 *) t, e, NULL)
1972 : * (U8 *) t;
1973 if (isPRINT(cp)) {
1974 if (! prev_was_printable) {
1975 PerlIO_printf(Perl_debug_log, " ");
1976 }
1977 PerlIO_printf(Perl_debug_log, "%c", (U8) cp);
1978 prev_was_printable = TRUE;
1979 }
1980 else {
1981 if (! first_time) {
1982 PerlIO_printf(Perl_debug_log, " ");
1983 }
147e3846 1984 PerlIO_printf(Perl_debug_log, "%02" UVXf, cp);
c7202dee
KW
1985 prev_was_printable = FALSE;
1986 }
1987 t += (is_utf8) ? UTF8SKIP(t) : 1;
1988 first_time = FALSE;
1989 }
1990
1991 PerlIO_printf(Perl_debug_log, "'\n");
1992}
1993
1994#endif /* #ifdef DEBUGGING */
1995
98994639 1996#endif /* USE_LOCALE_COLLATE */
58eebef2 1997
8ef6e574
KW
1998#ifdef USE_LOCALE
1999
c1284011
KW
2000bool
2001Perl__is_cur_LC_category_utf8(pTHX_ int category)
7d74bb61
KW
2002{
2003 /* Returns TRUE if the current locale for 'category' is UTF-8; FALSE
2004 * otherwise. 'category' may not be LC_ALL. If the platform doesn't have
119ee68b 2005 * nl_langinfo(), nor MB_CUR_MAX, this employs a heuristic, which hence
609548d2
KW
2006 * could give the wrong result. The result will very likely be correct for
2007 * languages that have commonly used non-ASCII characters, but for notably
2008 * English, it comes down to if the locale's name ends in something like
2009 * "UTF-8". It errs on the side of not being a UTF-8 locale. */
7d74bb61
KW
2010
2011 char *save_input_locale = NULL;
7d74bb61
KW
2012 STRLEN final_pos;
2013
8ef6e574 2014#ifdef LC_ALL
7d74bb61 2015 assert(category != LC_ALL);
8ef6e574 2016#endif
7d74bb61
KW
2017
2018 /* First dispose of the trivial cases */
b07fffd1 2019 save_input_locale = setlocale(category, NULL);
7d74bb61 2020 if (! save_input_locale) {
69014004
KW
2021 DEBUG_L(PerlIO_printf(Perl_debug_log,
2022 "Could not find current locale for category %d\n",
2023 category));
7d74bb61
KW
2024 return FALSE; /* XXX maybe should croak */
2025 }
b07fffd1 2026 save_input_locale = stdize_locale(savepv(save_input_locale));
a39edc4c 2027 if (isNAME_C_OR_POSIX(save_input_locale)) {
69014004
KW
2028 DEBUG_L(PerlIO_printf(Perl_debug_log,
2029 "Current locale for category %d is %s\n",
2030 category, save_input_locale));
b07fffd1 2031 Safefree(save_input_locale);
7d74bb61
KW
2032 return FALSE;
2033 }
2034
1d958db2
KW
2035#if defined(USE_LOCALE_CTYPE) \
2036 && (defined(MB_CUR_MAX) || (defined(HAS_NL_LANGINFO) && defined(CODESET)))
7d74bb61 2037
1d958db2 2038 { /* Next try nl_langinfo or MB_CUR_MAX if available */
7d74bb61
KW
2039
2040 char *save_ctype_locale = NULL;
119ee68b 2041 bool is_utf8;
7d74bb61 2042
119ee68b 2043 if (category != LC_CTYPE) { /* These work only on LC_CTYPE */
7d74bb61
KW
2044
2045 /* Get the current LC_CTYPE locale */
4f72bb37 2046 save_ctype_locale = setlocale(LC_CTYPE, NULL);
7d74bb61 2047 if (! save_ctype_locale) {
69014004
KW
2048 DEBUG_L(PerlIO_printf(Perl_debug_log,
2049 "Could not find current locale for LC_CTYPE\n"));
7d74bb61
KW
2050 goto cant_use_nllanginfo;
2051 }
4f72bb37 2052 save_ctype_locale = stdize_locale(savepv(save_ctype_locale));
7d74bb61
KW
2053
2054 /* If LC_CTYPE and the desired category use the same locale, this
2055 * means that finding the value for LC_CTYPE is the same as finding
2056 * the value for the desired category. Otherwise, switch LC_CTYPE
2057 * to the desired category's locale */
2058 if (strEQ(save_ctype_locale, save_input_locale)) {
2059 Safefree(save_ctype_locale);
2060 save_ctype_locale = NULL;
2061 }
2062 else if (! setlocale(LC_CTYPE, save_input_locale)) {
69014004
KW
2063 DEBUG_L(PerlIO_printf(Perl_debug_log,
2064 "Could not change LC_CTYPE locale to %s\n",
2065 save_input_locale));
7d74bb61
KW
2066 Safefree(save_ctype_locale);
2067 goto cant_use_nllanginfo;
2068 }
2069 }
2070
69014004
KW
2071 DEBUG_L(PerlIO_printf(Perl_debug_log, "Current LC_CTYPE locale=%s\n",
2072 save_input_locale));
2073
7d74bb61 2074 /* Here the current LC_CTYPE is set to the locale of the category whose
1d958db2
KW
2075 * information is desired. This means that nl_langinfo() and MB_CUR_MAX
2076 * should give the correct results */
119ee68b 2077
1d958db2
KW
2078# if defined(HAS_NL_LANGINFO) && defined(CODESET)
2079 {
4f72bb37 2080 char *codeset = nl_langinfo(CODESET);
1d958db2 2081 if (codeset && strNE(codeset, "")) {
4f72bb37 2082 codeset = savepv(codeset);
119ee68b 2083
1d958db2
KW
2084 /* If we switched LC_CTYPE, switch back */
2085 if (save_ctype_locale) {
2086 setlocale(LC_CTYPE, save_ctype_locale);
2087 Safefree(save_ctype_locale);
2088 }
2089
2090 is_utf8 = foldEQ(codeset, STR_WITH_LEN("UTF-8"))
2091 || foldEQ(codeset, STR_WITH_LEN("UTF8"));
2092
69014004
KW
2093 DEBUG_L(PerlIO_printf(Perl_debug_log,
2094 "\tnllanginfo returned CODESET '%s'; ?UTF8 locale=%d\n",
2095 codeset, is_utf8));
1d958db2
KW
2096 Safefree(codeset);
2097 Safefree(save_input_locale);
2098 return is_utf8;
2099 }
119ee68b
KW
2100 }
2101
1d958db2
KW
2102# endif
2103# ifdef MB_CUR_MAX
2104
2105 /* Here, either we don't have nl_langinfo, or it didn't return a
2106 * codeset. Try MB_CUR_MAX */
2107
119ee68b
KW
2108 /* Standard UTF-8 needs at least 4 bytes to represent the maximum
2109 * Unicode code point. Since UTF-8 is the only non-single byte
2110 * encoding we handle, we just say any such encoding is UTF-8, and if
2111 * turns out to be wrong, other things will fail */
2112 is_utf8 = MB_CUR_MAX >= 4;
2113
69014004
KW
2114 DEBUG_L(PerlIO_printf(Perl_debug_log,
2115 "\tMB_CUR_MAX=%d; ?UTF8 locale=%d\n",
2116 (int) MB_CUR_MAX, is_utf8));
2117
119ee68b
KW
2118 Safefree(save_input_locale);
2119
2120# ifdef HAS_MBTOWC
2121
2122 /* ... But, most system that have MB_CUR_MAX will also have mbtowc(),
2123 * since they are both in the C99 standard. We can feed a known byte
2124 * string to the latter function, and check that it gives the expected
2125 * result */
2126 if (is_utf8) {
2127 wchar_t wc;
856b881c 2128 PERL_UNUSED_RESULT(mbtowc(&wc, NULL, 0));/* Reset any shift state */
69014004 2129 errno = 0;
f019f68f 2130 if ((size_t)mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8))
119ee68b
KW
2131 != strlen(HYPHEN_UTF8)
2132 || wc != (wchar_t) 0x2010)
2133 {
2134 is_utf8 = FALSE;
abdcbdb8 2135 DEBUG_L(PerlIO_printf(Perl_debug_log, "\thyphen=U+%x\n", (unsigned int)wc));
69014004
KW
2136 DEBUG_L(PerlIO_printf(Perl_debug_log,
2137 "\treturn from mbtowc=%d; errno=%d; ?UTF8 locale=0\n",
2138 mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8)), errno));
119ee68b
KW
2139 }
2140 }
119ee68b
KW
2141# endif
2142
1d958db2
KW
2143 /* If we switched LC_CTYPE, switch back */
2144 if (save_ctype_locale) {
2145 setlocale(LC_CTYPE, save_ctype_locale);
2146 Safefree(save_ctype_locale);
119ee68b 2147 }
7d74bb61 2148
1d958db2 2149 return is_utf8;
119ee68b 2150# endif
7d74bb61 2151 }
119ee68b 2152
7d74bb61
KW
2153 cant_use_nllanginfo:
2154
0080c90a
KW
2155#else /* nl_langinfo should work if available, so don't bother compiling this
2156 fallback code. The final fallback of looking at the name is
2157 compiled, and will be executed if nl_langinfo fails */
7d74bb61 2158
97f4de96
KW
2159 /* nl_langinfo not available or failed somehow. Next try looking at the
2160 * currency symbol to see if it disambiguates things. Often that will be
2161 * in the native script, and if the symbol isn't in UTF-8, we know that the
2162 * locale isn't. If it is non-ASCII UTF-8, we infer that the locale is
609548d2
KW
2163 * too, as the odds of a non-UTF8 string being valid UTF-8 are quite small
2164 * */
fa9b773e
KW
2165
2166#ifdef HAS_LOCALECONV
fa9b773e 2167# ifdef USE_LOCALE_MONETARY
fa9b773e
KW
2168 {
2169 char *save_monetary_locale = NULL;
fa9b773e 2170 bool only_ascii = FALSE;
13542a67
KW
2171 bool is_utf8 = FALSE;
2172 struct lconv* lc;
fa9b773e 2173
97f4de96
KW
2174 /* Like above for LC_CTYPE, we first set LC_MONETARY to the locale of
2175 * the desired category, if it isn't that locale already */
2176
fa9b773e
KW
2177 if (category != LC_MONETARY) {
2178
4f72bb37 2179 save_monetary_locale = setlocale(LC_MONETARY, NULL);
fa9b773e 2180 if (! save_monetary_locale) {
69014004
KW
2181 DEBUG_L(PerlIO_printf(Perl_debug_log,
2182 "Could not find current locale for LC_MONETARY\n"));
fa9b773e
KW
2183 goto cant_use_monetary;
2184 }
4f72bb37 2185 save_monetary_locale = stdize_locale(savepv(save_monetary_locale));
fa9b773e 2186
13542a67
KW
2187 if (strEQ(save_monetary_locale, save_input_locale)) {
2188 Safefree(save_monetary_locale);
2189 save_monetary_locale = NULL;
2190 }
2191 else if (! setlocale(LC_MONETARY, save_input_locale)) {
59c234b4
KW
2192 DEBUG_L(PerlIO_printf(Perl_debug_log,
2193 "Could not change LC_MONETARY locale to %s\n",
2194 save_input_locale));
2195 Safefree(save_monetary_locale);
2196 goto cant_use_monetary;
fa9b773e
KW
2197 }
2198 }
2199
2200 /* Here the current LC_MONETARY is set to the locale of the category
2201 * whose information is desired. */
2202
13542a67
KW
2203 lc = localeconv();
2204 if (! lc
2205 || ! lc->currency_symbol
c5f058df 2206 || is_utf8_invariant_string((U8 *) lc->currency_symbol, 0))
13542a67
KW
2207 {
2208 DEBUG_L(PerlIO_printf(Perl_debug_log, "Couldn't get currency symbol for %s, or contains only ASCII; can't use for determining if UTF-8 locale\n", save_input_locale));
2209 only_ascii = TRUE;
2210 }
2211 else {
2212 is_utf8 = is_utf8_string((U8 *) lc->currency_symbol, 0);
fa9b773e
KW
2213 }
2214
2215 /* If we changed it, restore LC_MONETARY to its original locale */
2216 if (save_monetary_locale) {
2217 setlocale(LC_MONETARY, save_monetary_locale);
2218 Safefree(save_monetary_locale);
2219 }
2220
13542a67 2221 if (! only_ascii) {
fa9b773e 2222
59c234b4
KW
2223 /* It isn't a UTF-8 locale if the symbol is not legal UTF-8;
2224 * otherwise assume the locale is UTF-8 if and only if the symbol
2225 * is non-ascii UTF-8. */
2226 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?Currency symbol for %s is UTF-8=%d\n",
2227 save_input_locale, is_utf8));
2228 Safefree(save_input_locale);
2229 return is_utf8;
13542a67 2230 }
fa9b773e
KW
2231 }
2232 cant_use_monetary:
2233
2234# endif /* USE_LOCALE_MONETARY */
2235#endif /* HAS_LOCALECONV */
2236
15f7e74e
KW
2237#if defined(HAS_STRFTIME) && defined(USE_LOCALE_TIME)
2238
2239/* Still haven't found a non-ASCII string to disambiguate UTF-8 or not. Try
2240 * the names of the months and weekdays, timezone, and am/pm indicator */
2241 {
2242 char *save_time_locale = NULL;
2243 int hour = 10;
2244 bool is_dst = FALSE;
2245 int dom = 1;
2246 int month = 0;
2247 int i;
2248 char * formatted_time;
2249
2250
2251 /* Like above for LC_MONETARY, we set LC_TIME to the locale of the
2252 * desired category, if it isn't that locale already */
2253
2254 if (category != LC_TIME) {
2255
2256 save_time_locale = setlocale(LC_TIME, NULL);
2257 if (! save_time_locale) {
2258 DEBUG_L(PerlIO_printf(Perl_debug_log,
2259 "Could not find current locale for LC_TIME\n"));
2260 goto cant_use_time;
2261 }
2262 save_time_locale = stdize_locale(savepv(save_time_locale));
2263
2264 if (strEQ(save_time_locale, save_input_locale)) {
2265 Safefree(save_time_locale);
2266 save_time_locale = NULL;
2267 }
2268 else if (! setlocale(LC_TIME, save_input_locale)) {
2269 DEBUG_L(PerlIO_printf(Perl_debug_log,
2270 "Could not change LC_TIME locale to %s\n",
2271 save_input_locale));
2272 Safefree(save_time_locale);
2273 goto cant_use_time;
2274 }
2275 }
2276
2277 /* Here the current LC_TIME is set to the locale of the category
2278 * whose information is desired. Look at all the days of the week and
9f10db87 2279 * month names, and the timezone and am/pm indicator for UTF-8 variant
15f7e74e
KW
2280 * characters. The first such a one found will tell us if the locale
2281 * is UTF-8 or not */
2282
2283 for (i = 0; i < 7 + 12; i++) { /* 7 days; 12 months */
2284 formatted_time = my_strftime("%A %B %Z %p",
2285 0, 0, hour, dom, month, 112, 0, 0, is_dst);
c5f058df
KW
2286 if ( ! formatted_time
2287 || is_utf8_invariant_string((U8 *) formatted_time, 0))
2288 {
15f7e74e
KW
2289
2290 /* Here, we didn't find a non-ASCII. Try the next time through
2291 * with the complemented dst and am/pm, and try with the next
2292 * weekday. After we have gotten all weekdays, try the next
2293 * month */
2294 is_dst = ! is_dst;
2295 hour = (hour + 12) % 24;
2296 dom++;
2297 if (i > 6) {
2298 month++;
2299 }
2300 continue;
2301 }
2302
2303 /* Here, we have a non-ASCII. Return TRUE is it is valid UTF8;
2304 * false otherwise. But first, restore LC_TIME to its original
2305 * locale if we changed it */
2306 if (save_time_locale) {
2307 setlocale(LC_TIME, save_time_locale);
2308 Safefree(save_time_locale);
2309 }
2310
2311 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?time-related strings for %s are UTF-8=%d\n",
2312 save_input_locale,
2313 is_utf8_string((U8 *) formatted_time, 0)));
2314 Safefree(save_input_locale);
2315 return is_utf8_string((U8 *) formatted_time, 0);
2316 }
2317
2318 /* Falling off the end of the loop indicates all the names were just
2319 * ASCII. Go on to the next test. If we changed it, restore LC_TIME
2320 * to its original locale */
2321 if (save_time_locale) {
2322 setlocale(LC_TIME, save_time_locale);
2323 Safefree(save_time_locale);
2324 }
2325 DEBUG_L(PerlIO_printf(Perl_debug_log, "All time-related words for %s contain only ASCII; can't use for determining if UTF-8 locale\n", save_input_locale));
2326 }
2327 cant_use_time:
2328
2329#endif
2330
2331#if 0 && defined(USE_LOCALE_MESSAGES) && defined(HAS_SYS_ERRLIST)
855aeb93
JH
2332
2333/* This code is ifdefd out because it was found to not be necessary in testing
5857e934
KW
2334 * on our dromedary test machine, which has over 700 locales. There, this
2335 * added no value to looking at the currency symbol and the time strings. I
2336 * left it in so as to avoid rewriting it if real-world experience indicates
2337 * that dromedary is an outlier. Essentially, instead of returning abpve if we
855aeb93
JH
2338 * haven't found illegal utf8, we continue on and examine all the strerror()
2339 * messages on the platform for utf8ness. If all are ASCII, we still don't
2340 * know the answer; but otherwise we have a pretty good indication of the
5857e934
KW
2341 * utf8ness. The reason this doesn't help much is that the messages may not
2342 * have been translated into the locale. The currency symbol and time strings
2343 * are much more likely to have been translated. */
2344 {
855aeb93 2345 int e;
5857e934
KW
2346 bool is_utf8 = FALSE;
2347 bool non_ascii = FALSE;
855aeb93 2348 char *save_messages_locale = NULL;
5857e934 2349 const char * errmsg = NULL;
855aeb93 2350
5857e934
KW
2351 /* Like above, we set LC_MESSAGES to the locale of the desired
2352 * category, if it isn't that locale already */
855aeb93
JH
2353
2354 if (category != LC_MESSAGES) {
2355
5857e934 2356 save_messages_locale = setlocale(LC_MESSAGES, NULL);
855aeb93 2357 if (! save_messages_locale) {
5857e934
KW
2358 DEBUG_L(PerlIO_printf(Perl_debug_log,
2359 "Could not find current locale for LC_MESSAGES\n"));
855aeb93
JH
2360 goto cant_use_messages;
2361 }
5857e934 2362 save_messages_locale = stdize_locale(savepv(save_messages_locale));
855aeb93
JH
2363
2364 if (strEQ(save_messages_locale, save_input_locale)) {
5857e934
KW
2365 Safefree(save_messages_locale);
2366 save_messages_locale = NULL;
855aeb93
JH
2367 }
2368 else if (! setlocale(LC_MESSAGES, save_input_locale)) {
5857e934
KW
2369 DEBUG_L(PerlIO_printf(Perl_debug_log,
2370 "Could not change LC_MESSAGES locale to %s\n",
2371 save_input_locale));
855aeb93
JH
2372 Safefree(save_messages_locale);
2373 goto cant_use_messages;
2374 }
2375 }
2376
2377 /* Here the current LC_MESSAGES is set to the locale of the category
5857e934
KW
2378 * whose information is desired. Look through all the messages. We
2379 * can't use Strerror() here because it may expand to code that
2380 * segfaults in miniperl */
855aeb93 2381
5857e934
KW
2382 for (e = 0; e <= sys_nerr; e++) {
2383 errno = 0;
2384 errmsg = sys_errlist[e];
2385 if (errno || !errmsg) {
855aeb93
JH
2386 break;
2387 }
5857e934 2388 errmsg = savepv(errmsg);
c5f058df 2389 if (! is_utf8_invariant_string((U8 *) errmsg, 0)) {
5857e934
KW
2390 non_ascii = TRUE;
2391 is_utf8 = is_utf8_string((U8 *) errmsg, 0);
2392 break;
855aeb93
JH
2393 }
2394 }
5857e934 2395 Safefree(errmsg);
855aeb93
JH
2396
2397 /* And, if we changed it, restore LC_MESSAGES to its original locale */
2398 if (save_messages_locale) {
2399 setlocale(LC_MESSAGES, save_messages_locale);
2400 Safefree(save_messages_locale);
2401 }
2402
5857e934
KW
2403 if (non_ascii) {
2404
2405 /* Any non-UTF-8 message means not a UTF-8 locale; if all are valid,
2406 * any non-ascii means it is one; otherwise we assume it isn't */
2407 DEBUG_L(PerlIO_printf(Perl_debug_log, "\t?error messages for %s are UTF-8=%d\n",
2408 save_input_locale,
2409 is_utf8));
2410 Safefree(save_input_locale);
2411 return is_utf8;
2412 }
855aeb93 2413
5857e934 2414 DEBUG_L(PerlIO_printf(Perl_debug_log, "All error messages for %s contain only ASCII; can't use for determining if UTF-8 locale\n", save_input_locale));
855aeb93
JH
2415 }
2416 cant_use_messages:
2417
2418#endif
fa9b773e 2419
0080c90a
KW
2420#endif /* the code that is compiled when no nl_langinfo */
2421
92c0a900
KW
2422#ifndef EBCDIC /* On os390, even if the name ends with "UTF-8', it isn't a
2423 UTF-8 locale */
97f4de96
KW
2424 /* As a last resort, look at the locale name to see if it matches
2425 * qr/UTF -? * 8 /ix, or some other common locale names. This "name", the
2426 * return of setlocale(), is actually defined to be opaque, so we can't
2427 * really rely on the absence of various substrings in the name to indicate
2428 * its UTF-8ness, but if it has UTF8 in the name, it is extremely likely to
2429 * be a UTF-8 locale. Similarly for the other common names */
2430
2431 final_pos = strlen(save_input_locale) - 1;
2432 if (final_pos >= 3) {
2433 char *name = save_input_locale;
2434
2435 /* Find next 'U' or 'u' and look from there */
2436 while ((name += strcspn(name, "Uu") + 1)
2437 <= save_input_locale + final_pos - 2)
2438 {
305b8651
KW
2439 if (!isALPHA_FOLD_NE(*name, 't')
2440 || isALPHA_FOLD_NE(*(name + 1), 'f'))
97f4de96
KW
2441 {
2442 continue;
2443 }
2444 name += 2;
2445 if (*(name) == '-') {
2446 if ((name > save_input_locale + final_pos - 1)) {
2447 break;
2448 }
2449 name++;
2450 }
2451 if (*(name) == '8') {
97f4de96
KW
2452 DEBUG_L(PerlIO_printf(Perl_debug_log,
2453 "Locale %s ends with UTF-8 in name\n",
2454 save_input_locale));
00c54b9c 2455 Safefree(save_input_locale);
97f4de96
KW
2456 return TRUE;
2457 }
2458 }
2459 DEBUG_L(PerlIO_printf(Perl_debug_log,
2460 "Locale %s doesn't end with UTF-8 in name\n",
2461 save_input_locale));
2462 }
92c0a900 2463#endif
97f4de96
KW
2464
2465#ifdef WIN32
2466 /* http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756.aspx */
2467 if (final_pos >= 4
2468 && *(save_input_locale + final_pos - 0) == '1'
2469 && *(save_input_locale + final_pos - 1) == '0'
2470 && *(save_input_locale + final_pos - 2) == '0'
2471 && *(save_input_locale + final_pos - 3) == '5'
2472 && *(save_input_locale + final_pos - 4) == '6')
2473 {
2474 DEBUG_L(PerlIO_printf(Perl_debug_log,
2475 "Locale %s ends with 10056 in name, is UTF-8 locale\n",
2476 save_input_locale));
2477 Safefree(save_input_locale);
2478 return TRUE;
2479 }
2480#endif
2481
2482 /* Other common encodings are the ISO 8859 series, which aren't UTF-8. But
2483 * since we are about to return FALSE anyway, there is no point in doing
2484 * this extra work */
2485#if 0
2486 if (instr(save_input_locale, "8859")) {
2487 DEBUG_L(PerlIO_printf(Perl_debug_log,
2488 "Locale %s has 8859 in name, not UTF-8 locale\n",
2489 save_input_locale));
2490 Safefree(save_input_locale);
2491 return FALSE;
2492 }
2493#endif
2494
69014004
KW
2495 DEBUG_L(PerlIO_printf(Perl_debug_log,
2496 "Assuming locale %s is not a UTF-8 locale\n",
2497 save_input_locale));
fa9b773e 2498 Safefree(save_input_locale);
7d74bb61
KW
2499 return FALSE;
2500}
2501
8ef6e574 2502#endif
7d74bb61 2503
d6ded950
KW
2504
2505bool
2506Perl__is_in_locale_category(pTHX_ const bool compiling, const int category)
2507{
1a4f13e1 2508 dVAR;
d6ded950
KW
2509 /* Internal function which returns if we are in the scope of a pragma that
2510 * enables the locale category 'category'. 'compiling' should indicate if
2511 * this is during the compilation phase (TRUE) or not (FALSE). */
2512
2513 const COP * const cop = (compiling) ? &PL_compiling : PL_curcop;
2514
2515 SV *categories = cop_hints_fetch_pvs(cop, "locale", 0);
2516 if (! categories || categories == &PL_sv_placeholder) {
2517 return FALSE;
2518 }
2519
2520 /* The pseudo-category 'not_characters' is -1, so just add 1 to each to get
2521 * a valid unsigned */
2522 assert(category >= -1);
2523 return cBOOL(SvUV(categories) & (1U << (category + 1)));
2524}
2525
2c6ee1a7 2526char *
6ebbc862
KW
2527Perl_my_strerror(pTHX_ const int errnum)
2528{
2529 /* Returns a mortalized copy of the text of the error message associated
2530 * with 'errnum'. It uses the current locale's text unless the platform
2531 * doesn't have the LC_MESSAGES category or we are not being called from
2532 * within the scope of 'use locale'. In the former case, it uses whatever
2533 * strerror returns; in the latter case it uses the text from the C locale.
2534 *
2535 * The function just calls strerror(), but temporarily switches, if needed,
2536 * to the C locale */
2537
2538 char *errstr;
2539
2540#ifdef USE_LOCALE_MESSAGES /* If platform doesn't have messages category, we
2541 don't do any switching to the C locale; we just
2542 use whatever strerror() returns */
2543 const bool within_locale_scope = IN_LC(LC_MESSAGES);
2544
a0b53297 2545 dVAR;
2c6ee1a7 2546
6ebbc862 2547# ifdef USE_THREAD_SAFE_LOCALE
fcd0e682 2548 locale_t save_locale = NULL;
6ebbc862 2549# else
fcd0e682 2550 char * save_locale = NULL;
c9dda6da 2551 bool locale_is_C = FALSE;
2c6ee1a7 2552
6ebbc862
KW
2553 /* We have a critical section to prevent another thread from changing the
2554 * locale out from under us (or zapping the buffer returned from
2555 * setlocale() ) */
2556 LOCALE_LOCK;
2557
2558# endif
2559
2560 if (! within_locale_scope) {
c9dda6da 2561 errno = 0;
a0b53297 2562
6ebbc862
KW
2563# ifdef USE_THREAD_SAFE_LOCALE /* Use the thread-safe locale functions */
2564
2565 save_locale = uselocale(PL_C_locale_obj);
c9dda6da
KW
2566 if (! save_locale) {
2567 DEBUG_L(PerlIO_printf(Perl_debug_log,
2568 "uselocale failed, errno=%d\n", errno));
2569 }
6ebbc862
KW
2570
2571# else /* Not thread-safe build */
a0b53297
KW
2572
2573 save_locale = setlocale(LC_MESSAGES, NULL);
c9dda6da
KW
2574 if (! save_locale) {
2575 DEBUG_L(PerlIO_printf(Perl_debug_log,
2576 "setlocale failed, errno=%d\n", errno));
2577 }
2578 else {
2579 locale_is_C = isNAME_C_OR_POSIX(save_locale);
2c6ee1a7 2580
c9dda6da
KW
2581 /* Switch to the C locale if not already in it */
2582 if (! locale_is_C) {
2c6ee1a7 2583
c9dda6da
KW
2584 /* The setlocale() just below likely will zap 'save_locale', so
2585 * create a copy. */
2586 save_locale = savepv(save_locale);
2587 setlocale(LC_MESSAGES, "C");
2588 }
6ebbc862 2589 }
2c6ee1a7 2590
6ebbc862 2591# endif
2c6ee1a7 2592
6ebbc862 2593 } /* end of ! within_locale_scope */
a0b53297 2594
6ebbc862 2595#endif
a0b53297 2596
6ebbc862
KW
2597 errstr = Strerror(errnum);
2598 if (errstr) {
2599 errstr = savepv(errstr);
2600 SAVEFREEPV(errstr);
2601 }
2602
2603#ifdef USE_LOCALE_MESSAGES
2604
2605 if (! within_locale_scope) {
c9dda6da 2606 errno = 0;
a0b53297 2607
6ebbc862
KW
2608# ifdef USE_THREAD_SAFE_LOCALE
2609
c9dda6da
KW
2610 if (save_locale && ! uselocale(save_locale)) {
2611 DEBUG_L(PerlIO_printf(Perl_debug_log,
2612 "uselocale restore failed, errno=%d\n", errno));
2613 }
2c6ee1a7 2614 }
6ebbc862
KW
2615
2616# else
2617
c9dda6da
KW
2618 if (save_locale && ! locale_is_C) {
2619 if (! setlocale(LC_MESSAGES, save_locale)) {
2620 DEBUG_L(PerlIO_printf(Perl_debug_log,
2621 "setlocale restore failed, errno=%d\n", errno));
2622 }
6ebbc862
KW
2623 Safefree(save_locale);
2624 }
2625 }
2626
2627 LOCALE_UNLOCK;
2628
2629# endif
2c6ee1a7
KW
2630#endif
2631
6ebbc862 2632 return errstr;
2c6ee1a7
KW
2633}
2634
66610fdd 2635/*
747c467a
KW
2636
2637=head1 Locale-related functions and macros
2638
2639=for apidoc sync_locale
2640
2641Changing the program's locale should be avoided by XS code. Nevertheless,
2642certain non-Perl libraries called from XS, such as C<Gtk> do so. When this
2643happens, Perl needs to be told that the locale has changed. Use this function
2644to do so, before returning to Perl.
2645
2646=cut
2647*/
2648
2649void
2650Perl_sync_locale(pTHX)
2651{
2652
2653#ifdef USE_LOCALE_CTYPE
2654 new_ctype(setlocale(LC_CTYPE, NULL));
2655#endif /* USE_LOCALE_CTYPE */
2656
2657#ifdef USE_LOCALE_COLLATE
2658 new_collate(setlocale(LC_COLLATE, NULL));
2659#endif
2660
2661#ifdef USE_LOCALE_NUMERIC
2662 set_numeric_local(); /* Switch from "C" to underlying LC_NUMERIC */
2663 new_numeric(setlocale(LC_NUMERIC, NULL));
2664#endif /* USE_LOCALE_NUMERIC */
2665
2666}
2667
5d1187d1
KW
2668#if defined(DEBUGGING) && defined(USE_LOCALE)
2669
2670char *
2671Perl__setlocale_debug_string(const int category, /* category number,
2672 like LC_ALL */
2673 const char* const locale, /* locale name */
2674
2675 /* return value from setlocale() when attempting to
2676 * set 'category' to 'locale' */
2677 const char* const retval)
2678{
2679 /* Returns a pointer to a NUL-terminated string in static storage with
2680 * added text about the info passed in. This is not thread safe and will
2681 * be overwritten by the next call, so this should be used just to
fa07b8e5 2682 * formulate a string to immediately print or savepv() on. */
5d1187d1 2683
398a990f
DM
2684 /* initialise to a non-null value to keep it out of BSS and so keep
2685 * -DPERL_GLOBAL_STRUCT_PRIVATE happy */
60b45a7d
KW
2686 static char ret[128] = "If you can read this, thank your buggy C"
2687 " library strlcpy(), and change your hints file"
2688 " to undef it";
fa07b8e5 2689 my_strlcpy(ret, "setlocale(", sizeof(ret));
5d1187d1
KW
2690
2691 switch (category) {
2692 default:
fa07b8e5 2693 my_snprintf(ret, sizeof(ret), "%s? %d", ret, category);
5d1187d1
KW
2694 break;
2695# ifdef LC_ALL
2696 case LC_ALL:
fa07b8e5 2697 my_strlcat(ret, "LC_ALL", sizeof(ret));
5d1187d1
KW
2698 break;
2699# endif
2700# ifdef LC_CTYPE
2701 case LC_CTYPE:
fa07b8e5 2702 my_strlcat(ret, "LC_CTYPE", sizeof(ret));
5d1187d1
KW
2703 break;
2704# endif
2705# ifdef LC_NUMERIC
2706 case LC_NUMERIC:
fa07b8e5 2707 my_strlcat(ret, "LC_NUMERIC", sizeof(ret));
5d1187d1
KW
2708 break;
2709# endif
2710# ifdef LC_COLLATE
2711 case LC_COLLATE:
fa07b8e5 2712 my_strlcat(ret, "LC_COLLATE", sizeof(ret));
5d1187d1
KW
2713 break;
2714# endif
2715# ifdef LC_TIME
2716 case LC_TIME:
fa07b8e5 2717 my_strlcat(ret, "LC_TIME", sizeof(ret));
5d1187d1
KW
2718 break;
2719# endif
2720# ifdef LC_MONETARY
2721 case LC_MONETARY:
fa07b8e5 2722 my_strlcat(ret, "LC_MONETARY", sizeof(ret));
5d1187d1
KW
2723 break;
2724# endif
2725# ifdef LC_MESSAGES
2726 case LC_MESSAGES:
fa07b8e5 2727 my_strlcat(ret, "LC_MESSAGES", sizeof(ret));
5d1187d1
KW
2728 break;
2729# endif
2730 }
2731
fa07b8e5 2732 my_strlcat(ret, ", ", sizeof(ret));
5d1187d1
KW
2733
2734 if (locale) {
fa07b8e5
KW
2735 my_strlcat(ret, "\"", sizeof(ret));
2736 my_strlcat(ret, locale, sizeof(ret));
2737 my_strlcat(ret, "\"", sizeof(ret));
5d1187d1
KW
2738 }
2739 else {
fa07b8e5 2740 my_strlcat(ret, "NULL", sizeof(ret));
5d1187d1
KW
2741 }
2742
fa07b8e5 2743 my_strlcat(ret, ") returned ", sizeof(ret));
5d1187d1
KW
2744
2745 if (retval) {
fa07b8e5
KW
2746 my_strlcat(ret, "\"", sizeof(ret));
2747 my_strlcat(ret, retval, sizeof(ret));
2748 my_strlcat(ret, "\"", sizeof(ret));
5d1187d1
KW
2749 }
2750 else {
fa07b8e5 2751 my_strlcat(ret, "NULL", sizeof(ret));
5d1187d1
KW
2752 }
2753
2754 assert(strlen(ret) < sizeof(ret));
2755
2756 return ret;
2757}
2758
2759#endif
747c467a
KW
2760
2761
2762/*
14d04a33 2763 * ex: set ts=8 sts=4 sw=4 et:
37442d52 2764 */