This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Integrate:
[perl5.git] / locale.c
1 /*    locale.c
2  *
3  *    Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4  *    2000, 2001, 2002, 2003, 2005, 2006, 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
21 /* utility functions for handling locale-specific stuff like what
22  * character represents the decimal point.
23  */
24
25 #include "EXTERN.h"
26 #define PERL_IN_LOCALE_C
27 #include "perl.h"
28
29 #ifdef I_LOCALE
30 #  include <locale.h>
31 #endif
32
33 #ifdef I_LANGINFO
34 #   include <langinfo.h>
35 #endif
36
37 #include "reentr.h"
38
39 #if defined(USE_LOCALE_NUMERIC) || defined(USE_LOCALE_COLLATE)
40 /*
41  * Standardize the locale name from a string returned by 'setlocale'.
42  *
43  * The standard return value of setlocale() is either
44  * (1) "xx_YY" if the first argument of setlocale() is not LC_ALL
45  * (2) "xa_YY xb_YY ..." if the first argument of setlocale() is LC_ALL
46  *     (the space-separated values represent the various sublocales,
47  *      in some unspecificed order)
48  *
49  * In some platforms it has a form like "LC_SOMETHING=Lang_Country.866\n",
50  * which is harmful for further use of the string in setlocale().
51  *
52  */
53 STATIC char *
54 S_stdize_locale(pTHX_ char *locs)
55 {
56     const char * const s = strchr(locs, '=');
57     bool okay = TRUE;
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 #endif
79
80 void
81 Perl_set_numeric_radix(pTHX)
82 {
83 #ifdef USE_LOCALE_NUMERIC
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         }
98     }
99     else
100         PL_numeric_radix_sv = NULL;
101 # endif /* HAS_LOCALECONV */
102 #endif /* USE_LOCALE_NUMERIC */
103 }
104
105 /*
106  * Set up for a new numeric locale.
107  */
108 void
109 Perl_new_numeric(pTHX_ char *newnum)
110 {
111 #ifdef USE_LOCALE_NUMERIC
112
113     if (! newnum) {
114         Safefree(PL_numeric_name);
115         PL_numeric_name = NULL;
116         PL_numeric_standard = TRUE;
117         PL_numeric_local = TRUE;
118         return;
119     }
120
121     if (! PL_numeric_name || strNE(PL_numeric_name, newnum)) {
122         Safefree(PL_numeric_name);
123         PL_numeric_name = stdize_locale(savepv(newnum));
124         PL_numeric_standard = ((*newnum == 'C' && newnum[1] == '\0')
125                                || strEQ(newnum, "POSIX"));
126         PL_numeric_local = TRUE;
127         set_numeric_radix();
128     }
129
130 #endif /* USE_LOCALE_NUMERIC */
131 }
132
133 void
134 Perl_set_numeric_standard(pTHX)
135 {
136 #ifdef USE_LOCALE_NUMERIC
137
138     if (! PL_numeric_standard) {
139         setlocale(LC_NUMERIC, "C");
140         PL_numeric_standard = TRUE;
141         PL_numeric_local = FALSE;
142         set_numeric_radix();
143     }
144
145 #endif /* USE_LOCALE_NUMERIC */
146 }
147
148 void
149 Perl_set_numeric_local(pTHX)
150 {
151 #ifdef USE_LOCALE_NUMERIC
152
153     if (! PL_numeric_local) {
154         setlocale(LC_NUMERIC, PL_numeric_name);
155         PL_numeric_standard = FALSE;
156         PL_numeric_local = TRUE;
157         set_numeric_radix();
158     }
159
160 #endif /* USE_LOCALE_NUMERIC */
161 }
162
163 /*
164  * Set up for a new ctype locale.
165  */
166 void
167 Perl_new_ctype(pTHX_ char *newctype)
168 {
169 #ifdef USE_LOCALE_CTYPE
170     int i;
171
172     for (i = 0; i < 256; i++) {
173         if (isUPPER_LC(i))
174             PL_fold_locale[i] = toLOWER_LC(i);
175         else if (isLOWER_LC(i))
176             PL_fold_locale[i] = toUPPER_LC(i);
177         else
178             PL_fold_locale[i] = i;
179     }
180
181 #endif /* USE_LOCALE_CTYPE */
182     PERL_UNUSED_ARG(newctype);
183     PERL_UNUSED_CONTEXT;
184 }
185
186 /*
187  * Set up for a new collation locale.
188  */
189 void
190 Perl_new_collate(pTHX_ char *newcoll)
191 {
192 #ifdef USE_LOCALE_COLLATE
193
194     if (! newcoll) {
195         if (PL_collation_name) {
196             ++PL_collation_ix;
197             Safefree(PL_collation_name);
198             PL_collation_name = NULL;
199         }
200         PL_collation_standard = TRUE;
201         PL_collxfrm_base = 0;
202         PL_collxfrm_mult = 2;
203         return;
204     }
205
206     if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
207         ++PL_collation_ix;
208         Safefree(PL_collation_name);
209         PL_collation_name = stdize_locale(savepv(newcoll));
210         PL_collation_standard = ((*newcoll == 'C' && newcoll[1] == '\0')
211                                  || strEQ(newcoll, "POSIX"));
212
213         {
214           /*  2: at most so many chars ('a', 'b'). */
215           /* 50: surely no system expands a char more. */
216 #define XFRMBUFSIZE  (2 * 50)
217           char xbuf[XFRMBUFSIZE];
218           const Size_t fa = strxfrm(xbuf, "a",  XFRMBUFSIZE);
219           const Size_t fb = strxfrm(xbuf, "ab", XFRMBUFSIZE);
220           const SSize_t mult = fb - fa;
221           if (mult < 1)
222               Perl_croak(aTHX_ "strxfrm() gets absurd");
223           PL_collxfrm_base = (fa > (Size_t)mult) ? (fa - mult) : 0;
224           PL_collxfrm_mult = mult;
225         }
226     }
227
228 #endif /* USE_LOCALE_COLLATE */
229 }
230
231 /*
232  * Initialize locale awareness.
233  */
234 int
235 Perl_init_i18nl10n(pTHX_ int printwarn)
236 {
237     int ok = 1;
238     /* returns
239      *    1 = set ok or not applicable,
240      *    0 = fallback to C locale,
241      *   -1 = fallback to C locale failed
242      */
243
244 #if defined(USE_LOCALE)
245
246 #ifdef USE_LOCALE_CTYPE
247     char *curctype   = NULL;
248 #endif /* USE_LOCALE_CTYPE */
249 #ifdef USE_LOCALE_COLLATE
250     char *curcoll    = NULL;
251 #endif /* USE_LOCALE_COLLATE */
252 #ifdef USE_LOCALE_NUMERIC
253     char *curnum     = NULL;
254 #endif /* USE_LOCALE_NUMERIC */
255 #ifdef __GLIBC__
256     char * const language   = PerlEnv_getenv("LANGUAGE");
257 #endif
258     char * const lc_all     = PerlEnv_getenv("LC_ALL");
259     char * const lang       = PerlEnv_getenv("LANG");
260     bool setlocale_failure = FALSE;
261
262 #ifdef LOCALE_ENVIRON_REQUIRED
263
264     /*
265      * Ultrix setlocale(..., "") fails if there are no environment
266      * variables from which to get a locale name.
267      */
268
269     bool done = FALSE;
270
271 #ifdef LC_ALL
272     if (lang) {
273         if (setlocale(LC_ALL, ""))
274             done = TRUE;
275         else
276             setlocale_failure = TRUE;
277     }
278     if (!setlocale_failure) {
279 #ifdef USE_LOCALE_CTYPE
280         Safefree(curctype);
281         if (! (curctype =
282                setlocale(LC_CTYPE,
283                          (!done && (lang || PerlEnv_getenv("LC_CTYPE")))
284                                     ? "" : NULL)))
285             setlocale_failure = TRUE;
286         else
287             curctype = savepv(curctype);
288 #endif /* USE_LOCALE_CTYPE */
289 #ifdef USE_LOCALE_COLLATE
290         Safefree(curcoll);
291         if (! (curcoll =
292                setlocale(LC_COLLATE,
293                          (!done && (lang || PerlEnv_getenv("LC_COLLATE")))
294                                    ? "" : NULL)))
295             setlocale_failure = TRUE;
296         else
297             curcoll = savepv(curcoll);
298 #endif /* USE_LOCALE_COLLATE */
299 #ifdef USE_LOCALE_NUMERIC
300         Safefree(curnum);
301         if (! (curnum =
302                setlocale(LC_NUMERIC,
303                          (!done && (lang || PerlEnv_getenv("LC_NUMERIC")))
304                                   ? "" : NULL)))
305             setlocale_failure = TRUE;
306         else
307             curnum = savepv(curnum);
308 #endif /* USE_LOCALE_NUMERIC */
309     }
310
311 #endif /* LC_ALL */
312
313 #endif /* !LOCALE_ENVIRON_REQUIRED */
314
315 #ifdef LC_ALL
316     if (! setlocale(LC_ALL, ""))
317         setlocale_failure = TRUE;
318 #endif /* LC_ALL */
319
320     if (!setlocale_failure) {
321 #ifdef USE_LOCALE_CTYPE
322         Safefree(curctype);
323         if (! (curctype = setlocale(LC_CTYPE, "")))
324             setlocale_failure = TRUE;
325         else
326             curctype = savepv(curctype);
327 #endif /* USE_LOCALE_CTYPE */
328 #ifdef USE_LOCALE_COLLATE
329         Safefree(curcoll);
330         if (! (curcoll = setlocale(LC_COLLATE, "")))
331             setlocale_failure = TRUE;
332         else
333             curcoll = savepv(curcoll);
334 #endif /* USE_LOCALE_COLLATE */
335 #ifdef USE_LOCALE_NUMERIC
336         Safefree(curnum);
337         if (! (curnum = setlocale(LC_NUMERIC, "")))
338             setlocale_failure = TRUE;
339         else
340             curnum = savepv(curnum);
341 #endif /* USE_LOCALE_NUMERIC */
342     }
343
344     if (setlocale_failure) {
345         char *p;
346         const bool locwarn = (printwarn > 1 ||
347                         (printwarn &&
348                          (!(p = PerlEnv_getenv("PERL_BADLANG")) || atoi(p))));
349
350         if (locwarn) {
351 #ifdef LC_ALL
352
353             PerlIO_printf(Perl_error_log,
354                "perl: warning: Setting locale failed.\n");
355
356 #else /* !LC_ALL */
357
358             PerlIO_printf(Perl_error_log,
359                "perl: warning: Setting locale failed for the categories:\n\t");
360 #ifdef USE_LOCALE_CTYPE
361             if (! curctype)
362                 PerlIO_printf(Perl_error_log, "LC_CTYPE ");
363 #endif /* USE_LOCALE_CTYPE */
364 #ifdef USE_LOCALE_COLLATE
365             if (! curcoll)
366                 PerlIO_printf(Perl_error_log, "LC_COLLATE ");
367 #endif /* USE_LOCALE_COLLATE */
368 #ifdef USE_LOCALE_NUMERIC
369             if (! curnum)
370                 PerlIO_printf(Perl_error_log, "LC_NUMERIC ");
371 #endif /* USE_LOCALE_NUMERIC */
372             PerlIO_printf(Perl_error_log, "\n");
373
374 #endif /* LC_ALL */
375
376             PerlIO_printf(Perl_error_log,
377                 "perl: warning: Please check that your locale settings:\n");
378
379 #ifdef __GLIBC__
380             PerlIO_printf(Perl_error_log,
381                           "\tLANGUAGE = %c%s%c,\n",
382                           language ? '"' : '(',
383                           language ? language : "unset",
384                           language ? '"' : ')');
385 #endif
386
387             PerlIO_printf(Perl_error_log,
388                           "\tLC_ALL = %c%s%c,\n",
389                           lc_all ? '"' : '(',
390                           lc_all ? lc_all : "unset",
391                           lc_all ? '"' : ')');
392
393 #if defined(USE_ENVIRON_ARRAY)
394             {
395               char **e;
396               for (e = environ; *e; e++) {
397                   if (strnEQ(*e, "LC_", 3)
398                         && strnNE(*e, "LC_ALL=", 7)
399                         && (p = strchr(*e, '=')))
400                       PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
401                                     (int)(p - *e), *e, p + 1);
402               }
403             }
404 #else
405             PerlIO_printf(Perl_error_log,
406                           "\t(possibly more locale environment variables)\n");
407 #endif
408
409             PerlIO_printf(Perl_error_log,
410                           "\tLANG = %c%s%c\n",
411                           lang ? '"' : '(',
412                           lang ? lang : "unset",
413                           lang ? '"' : ')');
414
415             PerlIO_printf(Perl_error_log,
416                           "    are supported and installed on your system.\n");
417         }
418
419 #ifdef LC_ALL
420
421         if (setlocale(LC_ALL, "C")) {
422             if (locwarn)
423                 PerlIO_printf(Perl_error_log,
424       "perl: warning: Falling back to the standard locale (\"C\").\n");
425             ok = 0;
426         }
427         else {
428             if (locwarn)
429                 PerlIO_printf(Perl_error_log,
430       "perl: warning: Failed to fall back to the standard locale (\"C\").\n");
431             ok = -1;
432         }
433
434 #else /* ! LC_ALL */
435
436         if (0
437 #ifdef USE_LOCALE_CTYPE
438             || !(curctype || setlocale(LC_CTYPE, "C"))
439 #endif /* USE_LOCALE_CTYPE */
440 #ifdef USE_LOCALE_COLLATE
441             || !(curcoll || setlocale(LC_COLLATE, "C"))
442 #endif /* USE_LOCALE_COLLATE */
443 #ifdef USE_LOCALE_NUMERIC
444             || !(curnum || setlocale(LC_NUMERIC, "C"))
445 #endif /* USE_LOCALE_NUMERIC */
446             )
447         {
448             if (locwarn)
449                 PerlIO_printf(Perl_error_log,
450       "perl: warning: Cannot fall back to the standard locale (\"C\").\n");
451             ok = -1;
452         }
453
454 #endif /* ! LC_ALL */
455
456 #ifdef USE_LOCALE_CTYPE
457         Safefree(curctype);
458         curctype = savepv(setlocale(LC_CTYPE, NULL));
459 #endif /* USE_LOCALE_CTYPE */
460 #ifdef USE_LOCALE_COLLATE
461         Safefree(curcoll);
462         curcoll = savepv(setlocale(LC_COLLATE, NULL));
463 #endif /* USE_LOCALE_COLLATE */
464 #ifdef USE_LOCALE_NUMERIC
465         Safefree(curnum);
466         curnum = savepv(setlocale(LC_NUMERIC, NULL));
467 #endif /* USE_LOCALE_NUMERIC */
468     }
469     else {
470
471 #ifdef USE_LOCALE_CTYPE
472     new_ctype(curctype);
473 #endif /* USE_LOCALE_CTYPE */
474
475 #ifdef USE_LOCALE_COLLATE
476     new_collate(curcoll);
477 #endif /* USE_LOCALE_COLLATE */
478
479 #ifdef USE_LOCALE_NUMERIC
480     new_numeric(curnum);
481 #endif /* USE_LOCALE_NUMERIC */
482
483     }
484
485 #endif /* USE_LOCALE */
486
487 #ifdef USE_PERLIO
488     {
489       /* Set PL_utf8locale to TRUE if using PerlIO _and_
490          any of the following are true:
491          - nl_langinfo(CODESET) contains /^utf-?8/i
492          - $ENV{LC_ALL}   contains /^utf-?8/i
493          - $ENV{LC_CTYPE} contains /^utf-?8/i
494          - $ENV{LANG}     contains /^utf-?8/i
495          The LC_ALL, LC_CTYPE, LANG obey the usual override
496          hierarchy of locale environment variables.  (LANGUAGE
497          affects only LC_MESSAGES only under glibc.) (If present,
498          it overrides LC_MESSAGES for GNU gettext, and it also
499          can have more than one locale, separated by spaces,
500          in case you need to know.)
501          If PL_utf8locale and PL_unicode (set by -C or by $ENV{PERL_UNICODE})
502          are true, perl.c:S_parse_body() will turn on the PerlIO :utf8 layer
503          on STDIN, STDOUT, STDERR, _and_ the default open discipline.
504       */
505          bool utf8locale = FALSE;
506          char *codeset = NULL;
507 #if defined(HAS_NL_LANGINFO) && defined(CODESET)
508          codeset = nl_langinfo(CODESET);
509 #endif
510          if (codeset)
511               utf8locale = (Perl_ibcmp(aTHX_ codeset, STR_WITH_LEN("UTF-8")) == 0 ||
512                             Perl_ibcmp(aTHX_ codeset, STR_WITH_LEN("UTF8") ) == 0);
513 #if defined(USE_LOCALE)
514          else { /* nl_langinfo(CODESET) is supposed to correctly
515                  * interpret the locale environment variables,
516                  * but just in case it fails, let's do this manually. */ 
517               if (lang)
518                    utf8locale = (Perl_ibcmp(aTHX_ lang, STR_WITH_LEN("UTF-8")) == 0 ||
519                                  Perl_ibcmp(aTHX_ lang, STR_WITH_LEN("UTF8") ) == 0);
520 #ifdef USE_LOCALE_CTYPE
521               if (curctype)
522                    utf8locale = (Perl_ibcmp(aTHX_ curctype, STR_WITH_LEN("UTF-8")) == 0 ||
523                                  Perl_ibcmp(aTHX_ curctype, STR_WITH_LEN("UTF8") ) == 0);
524 #endif
525               if (lc_all)
526                    utf8locale = (Perl_ibcmp(aTHX_ lc_all, STR_WITH_LEN("UTF-8")) == 0 ||
527                                  Perl_ibcmp(aTHX_ lc_all, STR_WITH_LEN("UTF8") ) == 0);
528          }
529 #endif /* USE_LOCALE */
530          if (utf8locale)
531               PL_utf8locale = TRUE;
532     }
533     /* Set PL_unicode to $ENV{PERL_UNICODE} if using PerlIO.
534        This is an alternative to using the -C command line switch
535        (the -C if present will override this). */
536     {
537          char *p = PerlEnv_getenv("PERL_UNICODE");
538          PL_unicode = p ? parse_unicode_opts(&p) : 0;
539          if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
540              PL_utf8cache = -1;
541     }
542 #endif
543
544 #ifdef USE_LOCALE_CTYPE
545     Safefree(curctype);
546 #endif /* USE_LOCALE_CTYPE */
547 #ifdef USE_LOCALE_COLLATE
548     Safefree(curcoll);
549 #endif /* USE_LOCALE_COLLATE */
550 #ifdef USE_LOCALE_NUMERIC
551     Safefree(curnum);
552 #endif /* USE_LOCALE_NUMERIC */
553     return ok;
554 }
555
556 #ifdef USE_LOCALE_COLLATE
557
558 /*
559  * mem_collxfrm() is a bit like strxfrm() but with two important
560  * differences. First, it handles embedded NULs. Second, it allocates
561  * a bit more memory than needed for the transformed data itself.
562  * The real transformed data begins at offset sizeof(collationix).
563  * Please see sv_collxfrm() to see how this is used.
564  */
565
566 char *
567 Perl_mem_collxfrm(pTHX_ const char *s, STRLEN len, STRLEN *xlen)
568 {
569     char *xbuf;
570     STRLEN xAlloc, xin, xout; /* xalloc is a reserved word in VC */
571
572     /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
573     /* the +1 is for the terminating NUL. */
574
575     xAlloc = sizeof(PL_collation_ix) + PL_collxfrm_base + (PL_collxfrm_mult * len) + 1;
576     Newx(xbuf, xAlloc, char);
577     if (! xbuf)
578         goto bad;
579
580     *(U32*)xbuf = PL_collation_ix;
581     xout = sizeof(PL_collation_ix);
582     for (xin = 0; xin < len; ) {
583         SSize_t xused;
584
585         for (;;) {
586             xused = strxfrm(xbuf + xout, s + xin, xAlloc - xout);
587             if (xused == -1)
588                 goto bad;
589             if ((STRLEN)xused < xAlloc - xout)
590                 break;
591             xAlloc = (2 * xAlloc) + 1;
592             Renew(xbuf, xAlloc, char);
593             if (! xbuf)
594                 goto bad;
595         }
596
597         xin += strlen(s + xin) + 1;
598         xout += xused;
599
600         /* Embedded NULs are understood but silently skipped
601          * because they make no sense in locale collation. */
602     }
603
604     xbuf[xout] = '\0';
605     *xlen = xout - sizeof(PL_collation_ix);
606     return xbuf;
607
608   bad:
609     Safefree(xbuf);
610     *xlen = 0;
611     return NULL;
612 }
613
614 #endif /* USE_LOCALE_COLLATE */
615
616 /*
617  * Local variables:
618  * c-indentation-style: bsd
619  * c-basic-offset: 4
620  * indent-tabs-mode: t
621  * End:
622  *
623  * ex: set ts=8 sts=4 sw=4 noet:
624  */