xref: /openbsd/gnu/usr.bin/perl/t/loc_tools.pl (revision 73471bf0)
1# Common tools for test files to find the locales which exist on the
2# system.  Caller should have verified that this isn't miniperl before calling
3# the functions.
4
5# Note that it's okay that some languages have their native names
6# capitalized here even though that's not "right".  They are lowercased
7# anyway later during the scanning process (and besides, some clueless
8# vendor might have them capitalized erroneously anyway).
9
10# Functions whose names begin with underscore are internal helper functions
11# for this file, and are not to be used by outside callers.
12
13use Config;
14use strict;
15
16eval { require POSIX; import POSIX 'locale_h'; };
17my $has_locale_h = ! $@;
18
19my @known_categories = ( qw(LC_ALL LC_COLLATE LC_CTYPE LC_MESSAGES LC_MONETARY
20                            LC_NUMERIC LC_TIME LC_ADDRESS LC_IDENTIFICATION
21                            LC_MEASUREMENT LC_PAPER LC_TELEPHONE));
22my @platform_categories;
23
24# LC_ALL can be -1 on some platforms.  And, in fact the implementors could
25# legally use any integer to represent any category.  But it makes the most
26# sense for them to have used small integers.  Below, we create new locale
27# numbers for ones missing from this machine.  We make them very negative,
28# hopefully more negative than anything likely to be a valid category on the
29# platform, but also below is a check to be sure that our guess is valid.
30my $max_bad_category_number = -1000000;
31
32# Initialize this hash so that it looks like e.g.,
33#   6 => 'CTYPE',
34# where 6 is the value of &POSIX::LC_CTYPE
35my %category_name;
36my %category_number;
37if ($has_locale_h) {
38    my $number_for_missing_category = $max_bad_category_number;
39    foreach my $name (@known_categories) {
40        my $number = eval "&POSIX::$name";
41        if ($@) {
42            # Use a negative number (smaller than any legitimate category
43            # number) if the platform doesn't support this category, so we
44            # have an entry for all the ones that might be specified in calls
45            # to us.
46            $number = $number_for_missing_category-- if $@;
47        }
48        elsif (   $number !~ / ^ -? \d+ $ /x
49               || $number <=  $max_bad_category_number)
50        {
51            # We think this should be an int.  And it has to be larger than
52            # any of our synthetic numbers.
53            die "Unexpected locale category number '$number' for $name"
54        }
55        else {
56            push @platform_categories, $name;
57        }
58
59        $name =~ s/LC_//;
60        $category_name{$number} = "$name";
61        $category_number{$name} = $number;
62    }
63}
64
65sub _my_diag($) {
66    my $message = shift;
67    if (defined &main::diag) {
68        diag($message);
69    }
70    else {
71        local($\, $", $,) = (undef, ' ', '');
72        print STDERR $message, "\n";
73    }
74}
75
76sub _my_fail($) {
77    my $message = shift;
78    if (defined &main::fail) {
79        fail($message);
80    }
81    else {
82        local($\, $", $,) = (undef, ' ', '');
83        print "not ok 0 $message\n";
84    }
85}
86
87sub _trylocale ($$$$) { # For use only by other functions in this file!
88
89    # Adds the locale given by the first parameter to the list given by the
90    # 3rd iff the platform supports the locale in each of the category numbers
91    # given by the 2nd parameter, which is either a single category or a
92    # reference to a list of categories.  The list MUST be sorted so that
93    # CTYPE is first, COLLATE is last unless ALL is present, in which case
94    # that comes after COLLATE.  This is because locale.c detects bad locales
95    # only with CTYPE, and COLLATE on some platforms can core dump if it is a
96    # bad locale.
97    #
98    # The 4th parameter is true if to accept locales that aren't apparently
99    # fully compatible with Perl.
100
101    my $locale = shift;
102    my $categories = shift;
103    my $list = shift;
104    my $allow_incompatible = shift;
105
106    return if ! $locale || grep { $locale eq $_ } @$list;
107
108    # This is a toy (pig latin) locale that is not fully implemented on some
109    # systems
110    return if $locale =~ / ^ pig $ /ix;
111
112    # Certain platforms have a crippled locale system in which setlocale
113    # returns success for just about any possible locale name, but if anything
114    # actually happens as a result of the call, it is that the underlying
115    # locale is set to a system default, likely C or C.UTF-8.  We can't test
116    # such systems fully, but we shouldn't disable the user from using
117    # locales, as it may work out for them (or not).
118    return if    defined $Config{d_setlocale_accepts_any_locale_name}
119              && $locale !~ / ^ (?: C | POSIX | C\.UTF-8 ) $/ix;
120
121    $categories = [ $categories ] unless ref $categories;
122
123    my $badutf8 = 0;
124    my $plays_well = 1;
125
126    use warnings 'locale';
127
128    local $SIG{__WARN__} = sub {
129        $badutf8 = 1 if grep { /Malformed UTF-8/ } @_;
130        $plays_well = 0 if grep {
131                    /Locale .* may not work well(?#
132                   )|The Perl program will use the expected meanings/i
133            } @_;
134    };
135
136    # Incompatible locales aren't warned about unless using locales.
137    use locale;
138
139    foreach my $category (@$categories) {
140        die "category '$category' must instead be a number"
141                                            unless $category =~ / ^ -? \d+ $ /x;
142
143        return unless setlocale($category, $locale);
144        last if $badutf8 || ! $plays_well;
145    }
146
147    if ($badutf8) {
148        _my_fail("Verify locale name doesn't contain malformed utf8");
149        return;
150    }
151    push @$list, $locale if $plays_well || $allow_incompatible;
152}
153
154sub _decode_encodings { # For use only by other functions in this file!
155    my @enc;
156
157    foreach (split(/ /, shift)) {
158	if (/^(\d+)$/) {
159	    push @enc, "ISO8859-$1";
160	    push @enc, "iso8859$1";	# HP
161	    if ($1 eq '1') {
162		 push @enc, "roman8";	# HP
163	    }
164	    push @enc, $_;
165            push @enc, "$_.UTF-8";
166            push @enc, "$_.65001"; # Windows UTF-8
167            push @enc, "$_.ACP"; # Windows ANSI code page
168            push @enc, "$_.OCP"; # Windows OEM code page
169            push @enc, "$_.1252"; # Windows
170	}
171    }
172    if ($^O eq 'os390') {
173	push @enc, qw(IBM-037 IBM-819 IBM-1047);
174    }
175    push @enc, "UTF-8";
176    push @enc, "65001"; # Windows UTF-8
177
178    return @enc;
179}
180
181sub valid_locale_categories() {
182    # Returns a list of the locale categories (expressed as strings, like
183    # "LC_ALL) known to this program that are available on this platform.
184
185    return @platform_categories;
186}
187
188sub locales_enabled(;$) {
189    # Returns 0 if no locale handling is available on this platform; otherwise
190    # 1.
191    #
192    # The optional parameter is a reference to a list of individual POSIX
193    # locale categories.  If any of the individual categories specified by the
194    # optional parameter is all digits (and an optional leading minus), it is
195    # taken to be the C enum for the category (e.g., &POSIX::LC_CTYPE).
196    # Otherwise it should be a string name of the category, like 'LC_TIME'.
197    # The initial 'LC_' is optional.  It is a fatal error to call this with
198    # something that isn't a known category to this file.
199    #
200    # This optional parameter denotes which POSIX locale categories must be
201    # available on the platform.  If any aren't available, this function
202    # returns 0; otherwise it returns 1 and changes the list for the caller so
203    # that any category names are converted into their equivalent numbers, and
204    # sorts it to match the expectations of _trylocale.
205    #
206    # It is acceptable for the second parameter to be just a simple scalar
207    # denoting a single category (either name or number).  No conversion into
208    # a number is done in this case.
209
210    # khw cargo-culted the '?' in the pattern on the next line.
211    return 0 if $Config{ccflags} =~ /\bD?NO_LOCALE\b/;
212
213    # If we can't load the POSIX XS module, we can't have locales even if they
214    # normally would be available
215    return 0 if ! defined &DynaLoader::boot_DynaLoader;
216
217    if (! $Config{d_setlocale}) {
218        return 0 if $Config{ccflags} =~ /\bD?NO_POSIX_2008_LOCALE\b/;
219        return 0 unless $Config{d_newlocale};
220        return 0 unless $Config{d_uselocale};
221        return 0 unless $Config{d_duplocale};
222        return 0 unless $Config{d_freelocale};
223    }
224
225    # Done with the global possibilities.  Now check if any passed in category
226    # is disabled.
227
228    my $categories_ref = shift;
229    my $return_categories_numbers = 0;
230    my @categories_numbers;
231    my $has_LC_ALL = 0;
232    my $has_LC_COLLATE = 0;
233
234    if (defined $categories_ref) {
235        my @local_categories_copy;
236
237        if (ref $categories_ref) {
238            @local_categories_copy = @$$categories_ref;
239            $return_categories_numbers = 1;
240        }
241        else {  # Single category passed in
242            @local_categories_copy = $categories_ref;
243        }
244
245        for my $category_name_or_number (@local_categories_copy) {
246            my $name;
247            my $number;
248            if ($category_name_or_number =~ / ^ -? \d+ $ /x) {
249                $number = $category_name_or_number;
250                die "Invalid locale category number '$number'"
251                    unless grep { $number == $_ } keys %category_name;
252                $name = $category_name{$number};
253            }
254            else {
255                $name = $category_name_or_number;
256                $name =~ s/ ^ LC_ //x;
257                foreach my $trial (keys %category_name) {
258                    if ($category_name{$trial} eq $name) {
259                        $number = $trial;
260                        last;
261                    }
262                }
263                die "Invalid locale category name '$name'"
264                    unless defined $number;
265            }
266
267            return 0 if    $number <= $max_bad_category_number
268                        || $Config{ccflags} =~ /\bD?NO_LOCALE_$name\b/;
269
270            eval "defined &POSIX::LC_$name";
271            return 0 if $@;
272
273            if ($return_categories_numbers) {
274                if ($name eq 'CTYPE') {
275                    unshift @categories_numbers, $number;   # Always first
276                }
277                elsif ($name eq 'ALL') {
278                    $has_LC_ALL = 1;
279                }
280                elsif ($name eq 'COLLATE') {
281                    $has_LC_COLLATE = 1;
282                }
283                else {
284                    push @categories_numbers, $number;
285                }
286            }
287        }
288    }
289
290    if ($return_categories_numbers) {
291
292        # COLLATE comes after all other locales except ALL, which comes last
293        if ($has_LC_COLLATE) {
294            push @categories_numbers, $category_number{'COLLATE'};
295        }
296        if ($has_LC_ALL) {
297            push @categories_numbers, $category_number{'ALL'};
298        }
299        $$categories_ref = \@categories_numbers;
300    }
301
302    return 1;
303}
304
305
306sub find_locales ($;$) {
307
308    # Returns an array of all the locales we found on the system.  If the
309    # optional 2nd parameter is non-zero, the list includes all found locales;
310    # otherwise it is restricted to those locales that play well with Perl, as
311    # far as we can easily determine.
312    #
313    # The first parameter is either a single locale category or a reference to
314    # a list of categories to find valid locales for it (or in the case of
315    # multiple) for all of them.  Each category can be a name (like 'LC_ALL'
316    # or simply 'ALL') or the C enum value for the category.
317
318    my $categories = shift;
319    my $allow_incompatible = shift // 0;
320
321    $categories = [ $categories ] unless ref $categories;
322    return unless locales_enabled(\$categories);
323
324    # Note, the subroutine call above converts the $categories into a form
325    # suitable for _trylocale().
326
327    # Visual C's CRT goes silly on strings of the form "en_US.ISO8859-1"
328    # and mingw32 uses said silly CRT
329    # This doesn't seem to be an issue any more, at least on Windows XP,
330    # so re-enable the tests for Windows XP onwards.
331    my $winxp = ($^O eq 'MSWin32' && defined &Win32::GetOSVersion &&
332                    join('.', (Win32::GetOSVersion())[1..2]) >= 5.1);
333    return if ((($^O eq 'MSWin32' && !$winxp) || $^O eq 'NetWare')
334                && $Config{cc} =~ /^(cl|gcc|g\+\+|ici)/i);
335
336    # UWIN seems to loop after taint tests, just skip for now
337    return if ($^O =~ /^uwin/);
338
339    my @Locale;
340    _trylocale("C", $categories, \@Locale, $allow_incompatible);
341    _trylocale("POSIX", $categories, \@Locale, $allow_incompatible);
342
343    if ($Config{d_has_C_UTF8} && $Config{d_has_C_UTF8} eq 'true') {
344        _trylocale("C.UTF-8", $categories, \@Locale, $allow_incompatible);
345    }
346
347    # There's no point in looking at anything more if we know that setlocale
348    # will return success on any garbage or non-garbage name.
349    return sort @Locale if defined $Config{d_setlocale_accepts_any_locale_name};
350
351    foreach (1..16) {
352        _trylocale("ISO8859-$_", $categories, \@Locale, $allow_incompatible);
353        _trylocale("iso8859$_", $categories, \@Locale, $allow_incompatible);
354        _trylocale("iso8859-$_", $categories, \@Locale, $allow_incompatible);
355        _trylocale("iso_8859_$_", $categories, \@Locale, $allow_incompatible);
356        _trylocale("isolatin$_", $categories, \@Locale, $allow_incompatible);
357        _trylocale("isolatin-$_", $categories, \@Locale, $allow_incompatible);
358        _trylocale("iso_latin_$_", $categories, \@Locale, $allow_incompatible);
359    }
360
361    # Sanitize the environment so that we can run the external 'locale'
362    # program without the taint mode getting grumpy.
363
364    # $ENV{PATH} is special in VMS.
365    delete local $ENV{PATH} if $^O ne 'VMS' or $Config{d_setenv};
366
367    # Other subversive stuff.
368    delete local @ENV{qw(IFS CDPATH ENV BASH_ENV)};
369
370    if (-x "/usr/bin/locale"
371        && open(LOCALES, '-|', "/usr/bin/locale -a 2>/dev/null"))
372    {
373        while (<LOCALES>) {
374            # It seems that /usr/bin/locale steadfastly outputs 8 bit data, which
375            # ain't great when we're running this testPERL_UNICODE= so that utf8
376            # locales will cause all IO hadles to default to (assume) utf8
377            next unless utf8::valid($_);
378            chomp;
379            _trylocale($_, $categories, \@Locale, $allow_incompatible);
380        }
381        close(LOCALES);
382    } elsif ($^O eq 'VMS'
383             && defined($ENV{'SYS$I18N_LOCALE'})
384             && -d 'SYS$I18N_LOCALE')
385    {
386    # The SYS$I18N_LOCALE logical name search list was not present on
387    # VAX VMS V5.5-12, but was on AXP && VAX VMS V6.2 as well as later versions.
388        opendir(LOCALES, "SYS\$I18N_LOCALE:");
389        while ($_ = readdir(LOCALES)) {
390            chomp;
391            _trylocale($_, $categories, \@Locale, $allow_incompatible);
392        }
393        close(LOCALES);
394    } elsif (($^O eq 'openbsd' || $^O eq 'bitrig' ) && -e '/usr/share/locale') {
395
396        # OpenBSD doesn't have a locale executable, so reading
397        # /usr/share/locale is much easier and faster than the last resort
398        # method.
399
400        opendir(LOCALES, '/usr/share/locale');
401        while ($_ = readdir(LOCALES)) {
402            chomp;
403            _trylocale($_, $categories, \@Locale, $allow_incompatible);
404        }
405        close(LOCALES);
406    } else { # Final fallback.  Try our list of locales hard-coded here
407
408        # This is going to be slow.
409        my @Data;
410
411        # Locales whose name differs if the utf8 bit is on are stored in these
412        # two files with appropriate encodings.
413        my $data_file = ($^H & 0x08 || (${^OPEN} || "") =~ /:utf8/)
414                        ? _source_location() . "/lib/locale/utf8"
415                        : _source_location() . "/lib/locale/latin1";
416        if (-e $data_file) {
417            @Data = do $data_file;
418        }
419        else {
420            _my_diag(__FILE__ . ":" . __LINE__ . ": '$data_file' doesn't exist");
421        }
422
423        # The rest of the locales are in this file.
424        push @Data, <DATA>; close DATA;
425
426        foreach my $line (@Data) {
427            chomp $line;
428            my ($locale_name, $language_codes, $country_codes, $encodings) =
429                split /:/, $line;
430            _my_diag(__FILE__ . ":" . __LINE__ . ": Unexpected syntax in '$line'")
431                                                     unless defined $locale_name;
432            my @enc = _decode_encodings($encodings);
433            foreach my $loc (split(/ /, $locale_name)) {
434                _trylocale($loc, $categories, \@Locale, $allow_incompatible);
435                foreach my $enc (@enc) {
436                    _trylocale("$loc.$enc", $categories, \@Locale,
437                                                            $allow_incompatible);
438                }
439                $loc = lc $loc;
440                foreach my $enc (@enc) {
441                    _trylocale("$loc.$enc", $categories, \@Locale,
442                                                            $allow_incompatible);
443                }
444            }
445            foreach my $lang (split(/ /, $language_codes)) {
446                _trylocale($lang, $categories, \@Locale, $allow_incompatible);
447                foreach my $country (split(/ /, $country_codes)) {
448                    my $lc = "${lang}_${country}";
449                    _trylocale($lc, $categories, \@Locale, $allow_incompatible);
450                    foreach my $enc (@enc) {
451                        _trylocale("$lc.$enc", $categories, \@Locale,
452                                                            $allow_incompatible);
453                    }
454                    my $lC = "${lang}_\U${country}";
455                    _trylocale($lC, $categories, \@Locale, $allow_incompatible);
456                    foreach my $enc (@enc) {
457                        _trylocale("$lC.$enc", $categories, \@Locale,
458                                                            $allow_incompatible);
459                    }
460                }
461            }
462        }
463    }
464
465    @Locale = sort @Locale;
466
467    return @Locale;
468}
469
470sub is_locale_utf8 ($) { # Return a boolean as to if core Perl thinks the input
471                         # is a UTF-8 locale
472
473    # On z/OS, even locales marked as UTF-8 aren't.
474    return 0 if ord "A" != 65;
475
476    return 0 unless locales_enabled('LC_CTYPE');
477
478    my $locale = shift;
479
480    use locale;
481    no warnings 'locale'; # We may be trying out a weird locale
482
483    my $save_locale = setlocale(&POSIX::LC_CTYPE());
484    if (! $save_locale) {
485        ok(0, "Verify could save previous locale");
486        return 0;
487    }
488
489    if (! setlocale(&POSIX::LC_CTYPE(), $locale)) {
490        ok(0, "Verify could setlocale to $locale");
491        return 0;
492    }
493
494    my $ret = 0;
495
496    # Use an op that gives different results for UTF-8 than any other locale.
497    # If a platform has UTF-8 locales, there should be at least one locale on
498    # most platforms with UTF-8 in its name, so if there is a bug in the op
499    # giving a false negative, we should get a failure for those locales as we
500    # go through testing all the locales on the platform.
501    if (CORE::fc(chr utf8::unicode_to_native(0xdf)) ne "ss") {
502        if ($locale =~ /UTF-?8/i) {
503            ok (0, "Verify $locale with UTF-8 in name is a UTF-8 locale");
504        }
505    }
506    else {
507        $ret = 1;
508    }
509
510    die "Couldn't restore locale '$save_locale'"
511        unless setlocale(&POSIX::LC_CTYPE(), $save_locale);
512
513    return $ret;
514}
515
516sub find_utf8_ctype_locales (;$) { # Return the names of the locales that core
517                                  # Perl thinks are UTF-8 LC_CTYPE locales.
518                                  # Optional parameter is a reference to a
519                                  # list of locales to try; if omitted, this
520                                  # tries all locales it can find on the
521                                  # platform
522    return unless locales_enabled('LC_CTYPE');
523
524    my $locales_ref = shift;
525    my @return;
526
527    if (! defined $locales_ref) {
528
529        my @locales = find_locales(&POSIX::LC_CTYPE());
530        $locales_ref = \@locales;
531    }
532
533    foreach my $locale (@$locales_ref) {
534        push @return, $locale if is_locale_utf8($locale);
535    }
536
537    return @return;
538}
539
540
541sub find_utf8_ctype_locale (;$) { # Return the name of a locale that core Perl
542                                  # thinks is a UTF-8 LC_CTYPE non-turkic
543                                  # locale.
544                                  # Optional parameter is a reference to a
545                                  # list of locales to try; if omitted, this
546                                  # tries all locales it can find on the
547                                  # platform
548    my $try_locales_ref = shift;
549
550    my @utf8_locales = find_utf8_ctype_locales($try_locales_ref);
551    my @turkic_locales = find_utf8_turkic_locales($try_locales_ref);
552
553    my %seen_turkic;
554
555    # Create undef elements in the hash for turkic locales
556    @seen_turkic{@turkic_locales} = ();
557
558    foreach my $locale (@utf8_locales) {
559        return $locale unless exists $seen_turkic{$locale};
560    }
561
562    return;
563}
564
565sub find_utf8_turkic_locales (;$) {
566
567    # Return the name of all the locales that core Perl thinks are UTF-8
568    # Turkic LC_CTYPE.  Optional parameter is a reference to a list of locales
569    # to try; if omitted, this tries all locales it can find on the platform
570
571    my @return;
572
573    return unless locales_enabled('LC_CTYPE');
574
575    my $save_locale = setlocale(&POSIX::LC_CTYPE());
576    foreach my $locale (find_utf8_ctype_locales(shift)) {
577        use locale;
578        setlocale(&POSIX::LC_CTYPE(), $locale);
579        push @return, $locale if uc('i') eq "\x{130}";
580    }
581    setlocale(&POSIX::LC_CTYPE(), $save_locale);
582
583    return @return;
584}
585
586sub find_utf8_turkic_locale (;$) {
587    my @turkics = find_utf8_turkic_locales(shift);
588
589    return unless @turkics;
590    return $turkics[0]
591}
592
593
594# returns full path to the directory containing the current source
595# file, inspired by mauke's Dir::Self
596sub _source_location {
597    require File::Spec;
598
599    my $caller_filename = (caller)[1];
600
601    my $loc = File::Spec->rel2abs(
602        File::Spec->catpath(
603            (File::Spec->splitpath($caller_filename))[0, 1], ''
604        )
605    );
606
607    return ($loc =~ /^(.*)$/)[0]; # untaint
608}
609
6101
611
612# Format of data is: locale_name, language_codes, country_codes, encodings
613__DATA__
614Afrikaans:af:za:1 15
615Arabic:ar:dz eg sa:6 arabic8
616Brezhoneg Breton:br:fr:1 15
617Bulgarski Bulgarian:bg:bg:5
618Chinese:zh:cn tw:cn.EUC eucCN eucTW euc.CN euc.TW Big5 GB2312 tw.EUC
619Hrvatski Croatian:hr:hr:2
620Cymraeg Welsh:cy:cy:1 14 15
621Czech:cs:cz:2
622Dansk Danish:da:dk:1 15
623Nederlands Dutch:nl:be nl:1 15
624English American British:en:au ca gb ie nz us uk zw:1 15 cp850
625Esperanto:eo:eo:3
626Eesti Estonian:et:ee:4 6 13
627Suomi Finnish:fi:fi:1 15
628Flamish::fl:1 15
629Deutsch German:de:at be ch de lu:1 15
630Euskaraz Basque:eu:es fr:1 15
631Galego Galician:gl:es:1 15
632Ellada Greek:el:gr:7 g8
633Frysk:fy:nl:1 15
634Greenlandic:kl:gl:4 6
635Hebrew:iw:il:8 hebrew8
636Hungarian:hu:hu:2
637Indonesian:id:id:1 15
638Gaeilge Irish:ga:IE:1 14 15
639Italiano Italian:it:ch it:1 15
640Nihongo Japanese:ja:jp:euc eucJP jp.EUC sjis
641Korean:ko:kr:
642Latine Latin:la:va:1 15
643Latvian:lv:lv:4 6 13
644Lithuanian:lt:lt:4 6 13
645Macedonian:mk:mk:1 15
646Maltese:mt:mt:3
647Moldovan:mo:mo:2
648Norsk Norwegian:no no\@nynorsk nb nn:no:1 15
649Occitan:oc:es:1 15
650Polski Polish:pl:pl:2
651Rumanian:ro:ro:2
652Russki Russian:ru:ru su ua:5 koi8 koi8r KOI8-R koi8u cp1251 cp866
653Serbski Serbian:sr:yu:5
654Slovak:sk:sk:2
655Slovene Slovenian:sl:si:2
656Sqhip Albanian:sq:sq:1 15
657Svenska Swedish:sv:fi se:1 15
658Thai:th:th:11 tis620
659Turkish:tr:tr:9 turkish8
660Yiddish:yi::1 15
661