This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
gv.c:newGP: assert that PL_curcop is not NULL
[perl5.git] / locale.c
1 /*    locale.c
2  *
3  *    Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
4  *    2002, 2003, 2005, 2006, 2007, 2008 by Larry Wall and others
5  *
6  *    You may distribute under the terms of either the GNU General Public
7  *    License or the Artistic License, as specified in the README file.
8  *
9  */
10
11 /*
12  *      A Elbereth Gilthoniel,
13  *      silivren penna míriel
14  *      o menel aglar elenath!
15  *      Na-chaered palan-díriel
16  *      o galadhremmin ennorath,
17  *      Fanuilos, le linnathon
18  *      nef aear, si nef aearon!
19  *
20  *     [p.238 of _The Lord of the Rings_, II/i: "Many Meetings"]
21  */
22
23 /* utility functions for handling locale-specific stuff like what
24  * character represents the decimal point.
25  */
26
27 #include "EXTERN.h"
28 #define PERL_IN_LOCALE_C
29 #include "perl.h"
30
31 #ifdef I_LANGINFO
32 #   include <langinfo.h>
33 #endif
34
35 #include "reentr.h"
36
37 /*
38  * Standardize the locale name from a string returned by 'setlocale'.
39  *
40  * The typical return value of setlocale() is either
41  * (1) "xx_YY" if the first argument of setlocale() is not LC_ALL
42  * (2) "xa_YY xb_YY ..." if the first argument of setlocale() is LC_ALL
43  *     (the space-separated values represent the various sublocales,
44  *      in some unspecified order).  This is not handled by this function.
45  *
46  * In some platforms it has a form like "LC_SOMETHING=Lang_Country.866\n",
47  * which is harmful for further use of the string in setlocale().  This
48  * function removes the trailing new line and everything up through the '='
49  *
50  */
51 STATIC char *
52 S_stdize_locale(pTHX_ char *locs)
53 {
54     const char * const s = strchr(locs, '=');
55     bool okay = TRUE;
56
57     PERL_ARGS_ASSERT_STDIZE_LOCALE;
58
59     if (s) {
60         const char * const t = strchr(s, '.');
61         okay = FALSE;
62         if (t) {
63             const char * const u = strchr(t, '\n');
64             if (u && (u[1] == 0)) {
65                 const STRLEN len = u - s;
66                 Move(s + 1, locs, len, char);
67                 locs[len] = 0;
68                 okay = TRUE;
69             }
70         }
71     }
72
73     if (!okay)
74         Perl_croak(aTHX_ "Can't fix broken locale name \"%s\"", locs);
75
76     return locs;
77 }
78
79 void
80 Perl_set_numeric_radix(pTHX)
81 {
82 #ifdef USE_LOCALE_NUMERIC
83     dVAR;
84 # ifdef HAS_LOCALECONV
85     const struct lconv* const lc = localeconv();
86
87     if (lc && lc->decimal_point) {
88         if (lc->decimal_point[0] == '.' && lc->decimal_point[1] == 0) {
89             SvREFCNT_dec(PL_numeric_radix_sv);
90             PL_numeric_radix_sv = NULL;
91         }
92         else {
93             if (PL_numeric_radix_sv)
94                 sv_setpv(PL_numeric_radix_sv, lc->decimal_point);
95             else
96                 PL_numeric_radix_sv = newSVpv(lc->decimal_point, 0);
97             if (! is_ascii_string((U8 *) lc->decimal_point, 0)
98                 && is_utf8_string((U8 *) lc->decimal_point, 0)
99                 && is_cur_LC_category_utf8(LC_NUMERIC))
100             {
101                 SvUTF8_on(PL_numeric_radix_sv);
102             }
103         }
104     }
105     else
106         PL_numeric_radix_sv = NULL;
107 # endif /* HAS_LOCALECONV */
108 #endif /* USE_LOCALE_NUMERIC */
109 }
110
111 /*
112  * Set up for a new numeric locale.
113  */
114 void
115 Perl_new_numeric(pTHX_ const char *newnum)
116 {
117 #ifdef USE_LOCALE_NUMERIC
118     char *save_newnum;
119     dVAR;
120
121     if (! newnum) {
122         Safefree(PL_numeric_name);
123         PL_numeric_name = NULL;
124         PL_numeric_standard = TRUE;
125         PL_numeric_local = TRUE;
126         return;
127     }
128
129     save_newnum = stdize_locale(savepv(newnum));
130     if (! PL_numeric_name || strNE(PL_numeric_name, save_newnum)) {
131         Safefree(PL_numeric_name);
132         PL_numeric_name = save_newnum;
133         PL_numeric_standard = ((*save_newnum == 'C' && save_newnum[1] == '\0')
134                                || strEQ(save_newnum, "POSIX"));
135         PL_numeric_local = TRUE;
136         set_numeric_radix();
137     }
138     else {
139         Safefree(save_newnum);
140     }
141
142 #endif /* USE_LOCALE_NUMERIC */
143 }
144
145 void
146 Perl_set_numeric_standard(pTHX)
147 {
148 #ifdef USE_LOCALE_NUMERIC
149     dVAR;
150
151     if (! PL_numeric_standard) {
152         setlocale(LC_NUMERIC, "C");
153         PL_numeric_standard = TRUE;
154         PL_numeric_local = FALSE;
155         set_numeric_radix();
156     }
157
158 #endif /* USE_LOCALE_NUMERIC */
159 }
160
161 void
162 Perl_set_numeric_local(pTHX)
163 {
164 #ifdef USE_LOCALE_NUMERIC
165     dVAR;
166
167     if (! PL_numeric_local) {
168         setlocale(LC_NUMERIC, PL_numeric_name);
169         PL_numeric_standard = FALSE;
170         PL_numeric_local = TRUE;
171         set_numeric_radix();
172     }
173
174 #endif /* USE_LOCALE_NUMERIC */
175 }
176
177 /*
178  * Set up for a new ctype locale.
179  */
180 void
181 Perl_new_ctype(pTHX_ const char *newctype)
182 {
183 #ifdef USE_LOCALE_CTYPE
184     dVAR;
185     int i;
186
187     PERL_ARGS_ASSERT_NEW_CTYPE;
188
189     for (i = 0; i < 256; i++) {
190         if (isUPPER_LC(i))
191             PL_fold_locale[i] = toLOWER_LC(i);
192         else if (isLOWER_LC(i))
193             PL_fold_locale[i] = toUPPER_LC(i);
194         else
195             PL_fold_locale[i] = i;
196     }
197
198 #endif /* USE_LOCALE_CTYPE */
199     PERL_ARGS_ASSERT_NEW_CTYPE;
200     PERL_UNUSED_ARG(newctype);
201     PERL_UNUSED_CONTEXT;
202 }
203
204 /*
205  * Set up for a new collation locale.
206  */
207 void
208 Perl_new_collate(pTHX_ const char *newcoll)
209 {
210 #ifdef USE_LOCALE_COLLATE
211     dVAR;
212
213     if (! newcoll) {
214         if (PL_collation_name) {
215             ++PL_collation_ix;
216             Safefree(PL_collation_name);
217             PL_collation_name = NULL;
218         }
219         PL_collation_standard = TRUE;
220         PL_collxfrm_base = 0;
221         PL_collxfrm_mult = 2;
222         return;
223     }
224
225     if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
226         ++PL_collation_ix;
227         Safefree(PL_collation_name);
228         PL_collation_name = stdize_locale(savepv(newcoll));
229         PL_collation_standard = ((*newcoll == 'C' && newcoll[1] == '\0')
230                                  || strEQ(newcoll, "POSIX"));
231
232         {
233           /*  2: at most so many chars ('a', 'b'). */
234           /* 50: surely no system expands a char more. */
235 #define XFRMBUFSIZE  (2 * 50)
236           char xbuf[XFRMBUFSIZE];
237           const Size_t fa = strxfrm(xbuf, "a",  XFRMBUFSIZE);
238           const Size_t fb = strxfrm(xbuf, "ab", XFRMBUFSIZE);
239           const SSize_t mult = fb - fa;
240           if (mult < 1 && !(fa == 0 && fb == 0))
241               Perl_croak(aTHX_ "panic: strxfrm() gets absurd - a => %"UVuf", ab => %"UVuf,
242                          (UV) fa, (UV) fb);
243           PL_collxfrm_base = (fa > (Size_t)mult) ? (fa - mult) : 0;
244           PL_collxfrm_mult = mult;
245         }
246     }
247
248 #endif /* USE_LOCALE_COLLATE */
249 }
250
251 /*
252  * Initialize locale awareness.
253  */
254 int
255 Perl_init_i18nl10n(pTHX_ int printwarn)
256 {
257     int ok = 1;
258     /* returns
259      *    1 = set ok or not applicable,
260      *    0 = fallback to C locale,
261      *   -1 = fallback to C locale failed
262      */
263
264 #if defined(USE_LOCALE)
265     dVAR;
266
267 #ifdef USE_LOCALE_CTYPE
268     char *curctype   = NULL;
269 #endif /* USE_LOCALE_CTYPE */
270 #ifdef USE_LOCALE_COLLATE
271     char *curcoll    = NULL;
272 #endif /* USE_LOCALE_COLLATE */
273 #ifdef USE_LOCALE_NUMERIC
274     char *curnum     = NULL;
275 #endif /* USE_LOCALE_NUMERIC */
276 #ifdef __GLIBC__
277     char * const language   = PerlEnv_getenv("LANGUAGE");
278 #endif
279     /* NULL uses the existing already set up locale */
280     const char * const setlocale_init = (PerlEnv_getenv("PERL_SKIP_LOCALE_INIT"))
281                                         ? NULL
282                                         : "";
283     char * const lc_all     = PerlEnv_getenv("LC_ALL");
284     char * const lang       = PerlEnv_getenv("LANG");
285     bool setlocale_failure = FALSE;
286
287 #ifdef LOCALE_ENVIRON_REQUIRED
288
289     /*
290      * Ultrix setlocale(..., "") fails if there are no environment
291      * variables from which to get a locale name.
292      */
293
294     bool done = FALSE;
295
296 #   ifdef LC_ALL
297     if (lang) {
298         if (setlocale(LC_ALL, setlocale_init))
299             done = TRUE;
300         else
301             setlocale_failure = TRUE;
302     }
303     if (!setlocale_failure) {
304 #       ifdef USE_LOCALE_CTYPE
305         Safefree(curctype);
306         if (! (curctype =
307                setlocale(LC_CTYPE,
308                          (!done && (lang || PerlEnv_getenv("LC_CTYPE")))
309                                     ? setlocale_init : NULL)))
310             setlocale_failure = TRUE;
311         else
312             curctype = savepv(curctype);
313 #       endif /* USE_LOCALE_CTYPE */
314 #       ifdef USE_LOCALE_COLLATE
315         Safefree(curcoll);
316         if (! (curcoll =
317                setlocale(LC_COLLATE,
318                          (!done && (lang || PerlEnv_getenv("LC_COLLATE")))
319                                    ? setlocale_init : NULL)))
320             setlocale_failure = TRUE;
321         else
322             curcoll = savepv(curcoll);
323 #       endif /* USE_LOCALE_COLLATE */
324 #       ifdef USE_LOCALE_NUMERIC
325         Safefree(curnum);
326         if (! (curnum =
327                setlocale(LC_NUMERIC,
328                          (!done && (lang || PerlEnv_getenv("LC_NUMERIC")))
329                                   ? setlocale_init : NULL)))
330             setlocale_failure = TRUE;
331         else
332             curnum = savepv(curnum);
333 #       endif /* USE_LOCALE_NUMERIC */
334     }
335
336 #   endif /* LC_ALL */
337
338 #endif /* !LOCALE_ENVIRON_REQUIRED */
339
340 #ifdef LC_ALL
341     if (! setlocale(LC_ALL, setlocale_init))
342         setlocale_failure = TRUE;
343 #endif /* LC_ALL */
344
345     if (!setlocale_failure) {
346 #ifdef USE_LOCALE_CTYPE
347         Safefree(curctype);
348         if (! (curctype = setlocale(LC_CTYPE, setlocale_init)))
349             setlocale_failure = TRUE;
350         else
351             curctype = savepv(curctype);
352 #endif /* USE_LOCALE_CTYPE */
353 #ifdef USE_LOCALE_COLLATE
354         Safefree(curcoll);
355         if (! (curcoll = setlocale(LC_COLLATE, setlocale_init)))
356             setlocale_failure = TRUE;
357         else
358             curcoll = savepv(curcoll);
359 #endif /* USE_LOCALE_COLLATE */
360 #ifdef USE_LOCALE_NUMERIC
361         Safefree(curnum);
362         if (! (curnum = setlocale(LC_NUMERIC, setlocale_init)))
363             setlocale_failure = TRUE;
364         else
365             curnum = savepv(curnum);
366 #endif /* USE_LOCALE_NUMERIC */
367     }
368
369     if (setlocale_failure) {
370         char *p;
371         const bool locwarn = (printwarn > 1 ||
372                         (printwarn &&
373                          (!(p = PerlEnv_getenv("PERL_BADLANG")) || atoi(p))));
374
375         if (locwarn) {
376 #ifdef LC_ALL
377
378             PerlIO_printf(Perl_error_log,
379                "perl: warning: Setting locale failed.\n");
380
381 #else /* !LC_ALL */
382
383             PerlIO_printf(Perl_error_log,
384                "perl: warning: Setting locale failed for the categories:\n\t");
385 #ifdef USE_LOCALE_CTYPE
386             if (! curctype)
387                 PerlIO_printf(Perl_error_log, "LC_CTYPE ");
388 #endif /* USE_LOCALE_CTYPE */
389 #ifdef USE_LOCALE_COLLATE
390             if (! curcoll)
391                 PerlIO_printf(Perl_error_log, "LC_COLLATE ");
392 #endif /* USE_LOCALE_COLLATE */
393 #ifdef USE_LOCALE_NUMERIC
394             if (! curnum)
395                 PerlIO_printf(Perl_error_log, "LC_NUMERIC ");
396 #endif /* USE_LOCALE_NUMERIC */
397             PerlIO_printf(Perl_error_log, "\n");
398
399 #endif /* LC_ALL */
400
401             PerlIO_printf(Perl_error_log,
402                 "perl: warning: Please check that your locale settings:\n");
403
404 #ifdef __GLIBC__
405             PerlIO_printf(Perl_error_log,
406                           "\tLANGUAGE = %c%s%c,\n",
407                           language ? '"' : '(',
408                           language ? language : "unset",
409                           language ? '"' : ')');
410 #endif
411
412             PerlIO_printf(Perl_error_log,
413                           "\tLC_ALL = %c%s%c,\n",
414                           lc_all ? '"' : '(',
415                           lc_all ? lc_all : "unset",
416                           lc_all ? '"' : ')');
417
418 #if defined(USE_ENVIRON_ARRAY)
419             {
420               char **e;
421               for (e = environ; *e; e++) {
422                   if (strnEQ(*e, "LC_", 3)
423                         && strnNE(*e, "LC_ALL=", 7)
424                         && (p = strchr(*e, '=')))
425                       PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
426                                     (int)(p - *e), *e, p + 1);
427               }
428             }
429 #else
430             PerlIO_printf(Perl_error_log,
431                           "\t(possibly more locale environment variables)\n");
432 #endif
433
434             PerlIO_printf(Perl_error_log,
435                           "\tLANG = %c%s%c\n",
436                           lang ? '"' : '(',
437                           lang ? lang : "unset",
438                           lang ? '"' : ')');
439
440             PerlIO_printf(Perl_error_log,
441                           "    are supported and installed on your system.\n");
442         }
443
444 #ifdef LC_ALL
445
446         if (setlocale(LC_ALL, "C")) {
447             if (locwarn)
448                 PerlIO_printf(Perl_error_log,
449       "perl: warning: Falling back to the standard locale (\"C\").\n");
450             ok = 0;
451         }
452         else {
453             if (locwarn)
454                 PerlIO_printf(Perl_error_log,
455       "perl: warning: Failed to fall back to the standard locale (\"C\").\n");
456             ok = -1;
457         }
458
459 #else /* ! LC_ALL */
460
461         if (0
462 #ifdef USE_LOCALE_CTYPE
463             || !(curctype || setlocale(LC_CTYPE, "C"))
464 #endif /* USE_LOCALE_CTYPE */
465 #ifdef USE_LOCALE_COLLATE
466             || !(curcoll || setlocale(LC_COLLATE, "C"))
467 #endif /* USE_LOCALE_COLLATE */
468 #ifdef USE_LOCALE_NUMERIC
469             || !(curnum || setlocale(LC_NUMERIC, "C"))
470 #endif /* USE_LOCALE_NUMERIC */
471             )
472         {
473             if (locwarn)
474                 PerlIO_printf(Perl_error_log,
475       "perl: warning: Cannot fall back to the standard locale (\"C\").\n");
476             ok = -1;
477         }
478
479 #endif /* ! LC_ALL */
480
481 #ifdef USE_LOCALE_CTYPE
482         Safefree(curctype);
483         curctype = savepv(setlocale(LC_CTYPE, NULL));
484 #endif /* USE_LOCALE_CTYPE */
485 #ifdef USE_LOCALE_COLLATE
486         Safefree(curcoll);
487         curcoll = savepv(setlocale(LC_COLLATE, NULL));
488 #endif /* USE_LOCALE_COLLATE */
489 #ifdef USE_LOCALE_NUMERIC
490         Safefree(curnum);
491         curnum = savepv(setlocale(LC_NUMERIC, NULL));
492 #endif /* USE_LOCALE_NUMERIC */
493     }
494     else {
495
496 #ifdef USE_LOCALE_CTYPE
497     new_ctype(curctype);
498 #endif /* USE_LOCALE_CTYPE */
499
500 #ifdef USE_LOCALE_COLLATE
501     new_collate(curcoll);
502 #endif /* USE_LOCALE_COLLATE */
503
504 #ifdef USE_LOCALE_NUMERIC
505     new_numeric(curnum);
506 #endif /* USE_LOCALE_NUMERIC */
507
508     }
509
510 #endif /* USE_LOCALE */
511
512 #ifdef USE_PERLIO
513     {
514       /* Set PL_utf8locale to TRUE if using PerlIO _and_
515          the current LC_CTYPE locale is UTF-8.
516          If PL_utf8locale and PL_unicode (set by -C or by $ENV{PERL_UNICODE})
517          are true, perl.c:S_parse_body() will turn on the PerlIO :utf8 layer
518          on STDIN, STDOUT, STDERR, _and_ the default open discipline.
519       */
520         PL_utf8locale = is_cur_LC_category_utf8(LC_CTYPE);
521     }
522     /* Set PL_unicode to $ENV{PERL_UNICODE} if using PerlIO.
523        This is an alternative to using the -C command line switch
524        (the -C if present will override this). */
525     {
526          const char *p = PerlEnv_getenv("PERL_UNICODE");
527          PL_unicode = p ? parse_unicode_opts(&p) : 0;
528          if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
529              PL_utf8cache = -1;
530     }
531 #endif
532
533 #ifdef USE_LOCALE_CTYPE
534     Safefree(curctype);
535 #endif /* USE_LOCALE_CTYPE */
536 #ifdef USE_LOCALE_COLLATE
537     Safefree(curcoll);
538 #endif /* USE_LOCALE_COLLATE */
539 #ifdef USE_LOCALE_NUMERIC
540     Safefree(curnum);
541 #endif /* USE_LOCALE_NUMERIC */
542     return ok;
543 }
544
545 #ifdef USE_LOCALE_COLLATE
546
547 /*
548  * mem_collxfrm() is a bit like strxfrm() but with two important
549  * differences. First, it handles embedded NULs. Second, it allocates
550  * a bit more memory than needed for the transformed data itself.
551  * The real transformed data begins at offset sizeof(collationix).
552  * Please see sv_collxfrm() to see how this is used.
553  */
554
555 char *
556 Perl_mem_collxfrm(pTHX_ const char *s, STRLEN len, STRLEN *xlen)
557 {
558     dVAR;
559     char *xbuf;
560     STRLEN xAlloc, xin, xout; /* xalloc is a reserved word in VC */
561
562     PERL_ARGS_ASSERT_MEM_COLLXFRM;
563
564     /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
565     /* the +1 is for the terminating NUL. */
566
567     xAlloc = sizeof(PL_collation_ix) + PL_collxfrm_base + (PL_collxfrm_mult * len) + 1;
568     Newx(xbuf, xAlloc, char);
569     if (! xbuf)
570         goto bad;
571
572     *(U32*)xbuf = PL_collation_ix;
573     xout = sizeof(PL_collation_ix);
574     for (xin = 0; xin < len; ) {
575         Size_t xused;
576
577         for (;;) {
578             xused = strxfrm(xbuf + xout, s + xin, xAlloc - xout);
579             if (xused >= PERL_INT_MAX)
580                 goto bad;
581             if ((STRLEN)xused < xAlloc - xout)
582                 break;
583             xAlloc = (2 * xAlloc) + 1;
584             Renew(xbuf, xAlloc, char);
585             if (! xbuf)
586                 goto bad;
587         }
588
589         xin += strlen(s + xin) + 1;
590         xout += xused;
591
592         /* Embedded NULs are understood but silently skipped
593          * because they make no sense in locale collation. */
594     }
595
596     xbuf[xout] = '\0';
597     *xlen = xout - sizeof(PL_collation_ix);
598     return xbuf;
599
600   bad:
601     Safefree(xbuf);
602     *xlen = 0;
603     return NULL;
604 }
605
606 #endif /* USE_LOCALE_COLLATE */
607
608 STATIC bool
609 S_is_cur_LC_category_utf8(pTHX_ int category)
610 {
611     /* Returns TRUE if the current locale for 'category' is UTF-8; FALSE
612      * otherwise. 'category' may not be LC_ALL.  If the platform doesn't have
613      * nl_langinfo(), this employs a heuristic, which hence could give the
614      * wrong result.  It errs on the side of not being a UTF-8 locale. */
615
616     char *save_input_locale = NULL;
617     int has_hyphen;
618     STRLEN final_pos;
619
620     assert(category != LC_ALL);
621
622     /* First dispose of the trivial cases */
623     save_input_locale = stdize_locale(setlocale(category, NULL));
624     if (! save_input_locale) {
625         return FALSE;   /* XXX maybe should croak */
626     }
627     if ((*save_input_locale == 'C' && save_input_locale[1] == '\0')
628         || strEQ(save_input_locale, "POSIX"))
629     {
630         return FALSE;
631     }
632
633     save_input_locale = savepv(save_input_locale);
634
635 #if defined(HAS_NL_LANGINFO) && defined(CODESET) && defined(USE_LOCALE_CTYPE)
636
637     { /* Next try nl_langinfo if available */
638
639         char *save_ctype_locale = NULL;
640         char *codeset = NULL;
641
642         if (category != LC_CTYPE) { /* nl_langinfo works only on LC_CTYPE */
643
644             /* Get the current LC_CTYPE locale */
645             save_ctype_locale = stdize_locale(savepv(setlocale(LC_CTYPE, NULL)));
646             if (! save_ctype_locale) {
647                 goto cant_use_nllanginfo;
648             }
649
650             /* If LC_CTYPE and the desired category use the same locale, this
651              * means that finding the value for LC_CTYPE is the same as finding
652              * the value for the desired category.  Otherwise, switch LC_CTYPE
653              * to the desired category's locale */
654             if (strEQ(save_ctype_locale, save_input_locale)) {
655                 Safefree(save_ctype_locale);
656                 save_ctype_locale = NULL;
657             }
658             else if (! setlocale(LC_CTYPE, save_input_locale)) {
659                 Safefree(save_ctype_locale);
660                 goto cant_use_nllanginfo;
661             }
662         }
663
664         /* Here the current LC_CTYPE is set to the locale of the category whose
665          * information is desired.  This means that nl_langinfo() should give
666          * the correct results */
667         codeset = savepv(nl_langinfo(CODESET));
668         if (codeset) {
669             bool is_utf8;
670
671             /* If we switched LC_CTYPE, switch back */
672             if (save_ctype_locale) {
673                 setlocale(LC_CTYPE, save_ctype_locale);
674                 Safefree(save_ctype_locale);
675             }
676
677             is_utf8 = foldEQ(codeset, STR_WITH_LEN("UTF-8"))
678                       || foldEQ(codeset, STR_WITH_LEN("UTF8"));
679
680             Safefree(codeset);
681             Safefree(save_input_locale);
682             return is_utf8;
683         }
684
685     }
686   cant_use_nllanginfo:
687
688 #endif /* HAS_NL_LANGINFO etc */
689
690     /* nl_langinfo not available or failed somehow.  Look at the locale name to
691      * see if it matches qr/UTF -? 8 $ /ix  */
692
693     final_pos = strlen(save_input_locale) - 1;
694     if (final_pos >= 3
695         && *(save_input_locale + final_pos) == '8')
696     {
697         has_hyphen = *(save_input_locale + final_pos - 1 ) == '-';
698         if ((! has_hyphen || final_pos >= 4)
699             && toFOLD(*(save_input_locale + final_pos - has_hyphen - 1)) == 'f'
700             && toFOLD(*(save_input_locale + final_pos - has_hyphen - 2)) == 't'
701             && toFOLD(*(save_input_locale + final_pos - has_hyphen - 3)) == 'u')
702         {
703             Safefree(save_input_locale);
704             return TRUE;
705         }
706     }
707
708 #ifdef WIN32
709     /* http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756.aspx */
710     if (final_pos >= 4
711         && *(save_input_locale + final_pos - 0) == '1'
712         && *(save_input_locale + final_pos - 1) == '0'
713         && *(save_input_locale + final_pos - 2) == '0'
714         && *(save_input_locale + final_pos - 3) == '5'
715         && *(save_input_locale + final_pos - 4) == '6')
716     {
717         Safefree(save_input_locale);
718         return TRUE;
719     }
720 #endif
721
722     /* Other common encodings are the ISO 8859 series, which aren't UTF-8 */
723     if (instr(save_input_locale, "8859")) {
724         Safefree(save_input_locale);
725         return FALSE;
726     }
727
728 #ifdef HAS_LOCALECONV
729
730 #   ifdef USE_LOCALE_MONETARY
731
732     /* Here, there is nothing in the locale name to indicate whether the locale
733      * is UTF-8 or not.  This "name", the return of setlocale(), is actually
734      * defined to be opaque, so we can't really rely on the absence of various
735      * substrings in the name to indicate its UTF-8ness.  Look at the locale's
736      * currency symbol.  Often that will be in the native script, and if the
737      * symbol isn't in UTF-8, we know that the locale isn't.  If it is
738      * non-ASCII UTF-8, we infer that the locale is too.
739      * To do this, like above for LC_CTYPE, we first set LC_MONETARY to the
740      * locale of the desired category, if it isn't that locale already */
741
742     {
743         char *save_monetary_locale = NULL;
744         bool illegal_utf8 = FALSE;
745         bool only_ascii = FALSE;
746         const struct lconv* const lc = localeconv();
747
748         if (category != LC_MONETARY) {
749
750             save_monetary_locale = stdize_locale(savepv(setlocale(LC_MONETARY,
751                                                                   NULL)));
752             if (! save_monetary_locale) {
753                 goto cant_use_monetary;
754             }
755
756             if (strNE(save_monetary_locale, save_input_locale)) {
757                 if (! setlocale(LC_MONETARY, save_input_locale)) {
758                     Safefree(save_monetary_locale);
759                     goto cant_use_monetary;
760                 }
761             }
762         }
763
764         /* Here the current LC_MONETARY is set to the locale of the category
765          * whose information is desired. */
766
767         if (lc && lc->currency_symbol) {
768             if (! is_utf8_string((U8 *) lc->currency_symbol, 0)) {
769                 illegal_utf8 = TRUE;
770             }
771             else if (is_ascii_string((U8 *) lc->currency_symbol, 0)) {
772                 only_ascii = TRUE;
773             }
774         }
775
776         /* If we changed it, restore LC_MONETARY to its original locale */
777         if (save_monetary_locale) {
778             setlocale(LC_MONETARY, save_monetary_locale);
779             Safefree(save_monetary_locale);
780         }
781
782         Safefree(save_input_locale);
783
784         /* It isn't a UTF-8 locale if the symbol is not legal UTF-8; otherwise
785          * assume the locale is UTF-8 if and only if the symbol is non-ascii
786          * UTF-8.  (We can't really tell if the locale is UTF-8 or not if the
787          * symbol is just a '$', so we err on the side of it not being UTF-8)
788          * */
789         return (illegal_utf8)
790                 ? FALSE
791                 : ! only_ascii;
792
793     }
794   cant_use_monetary:
795
796 #   endif /* USE_LOCALE_MONETARY */
797 #endif /* HAS_LOCALECONV */
798
799 #if 0 && defined(HAS_STRERROR) && defined(USE_LOCALE_MESSAGES)
800
801 /* This code is ifdefd out because it was found to not be necessary in testing
802  * on our dromedary test machine, which has over 700 locales.  There, looking
803  * at just the currency symbol gave essentially the same results as doing this
804  * extra work.  Executing this also caused segfaults in miniperl.  I left it in
805  * so as to avoid rewriting it if real-world experience indicates that
806  * dromedary is an outlier.  Essentially, instead of returning abpve if we
807  * haven't found illegal utf8, we continue on and examine all the strerror()
808  * messages on the platform for utf8ness.  If all are ASCII, we still don't
809  * know the answer; but otherwise we have a pretty good indication of the
810  * utf8ness.  The reason this doesn't necessarily help much is that the
811  * messages may not have been translated into the locale.  The currency symbol
812  * is much more likely to have been translated.  The code below would need to
813  * be altered somewhat to just be a continuation of testing the currency
814  * symbol. */
815         int e;
816         unsigned int failures = 0, non_ascii = 0;
817         char *save_messages_locale = NULL;
818
819         /* Like above for LC_CTYPE, we set LC_MESSAGES to the locale of the
820          * desired category, if it isn't that locale already */
821
822         if (category != LC_MESSAGES) {
823
824             save_messages_locale = stdize_locale(savepv(setlocale(LC_MESSAGES,
825                                                                   NULL)));
826             if (! save_messages_locale) {
827                 goto cant_use_messages;
828             }
829
830             if (strEQ(save_messages_locale, save_input_locale)) {
831                 Safefree(save_input_locale);
832             }
833             else if (! setlocale(LC_MESSAGES, save_input_locale)) {
834                 Safefree(save_messages_locale);
835                 goto cant_use_messages;
836             }
837         }
838
839         /* Here the current LC_MESSAGES is set to the locale of the category
840          * whose information is desired.  Look through all the messages */
841
842         for (e = 0;
843 #ifdef HAS_SYS_ERRLIST
844              e <= sys_nerr
845 #endif
846              ; e++)
847         {
848             const U8* const errmsg = (U8 *) Strerror(e) ;
849             if (!errmsg)
850                 break;
851             if (! is_utf8_string(errmsg, 0)) {
852                 failures++;
853                 break;
854             }
855             else if (! is_ascii_string(errmsg, 0)) {
856                 non_ascii++;
857             }
858         }
859
860         /* And, if we changed it, restore LC_MESSAGES to its original locale */
861         if (save_messages_locale) {
862             setlocale(LC_MESSAGES, save_messages_locale);
863             Safefree(save_messages_locale);
864         }
865
866         /* Any non-UTF-8 message means not a UTF-8 locale; if all are valid,
867          * any non-ascii means it is one; otherwise we assume it isn't */
868         return (failures) ? FALSE : non_ascii;
869
870     }
871   cant_use_messages:
872
873 #endif
874
875     Safefree(save_input_locale);
876     return FALSE;
877 }
878
879
880
881 /*
882  * Local variables:
883  * c-indentation-style: bsd
884  * c-basic-offset: 4
885  * indent-tabs-mode: nil
886  * End:
887  *
888  * ex: set ts=8 sts=4 sw=4 et:
889  */