63f870f1df1398af4a947323671e0bb76d94b7d7
[platform/upstream/diffutils.git] / gnulib-tests / setlocale.c
1 /* Set the current locale.  -*- coding: utf-8 -*-
2    Copyright (C) 2009, 2011-2018 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
16
17 /* Written by Bruno Haible <bruno@clisp.org>, 2009.  */
18
19 #include <config.h>
20
21 /* Override setlocale() so that when the default locale is requested
22    (locale = ""), the environment variables LC_ALL, LC_*, and LANG are
23    considered.
24    Also include all the functionality from libintl's setlocale() override.  */
25
26 /* Please keep this file in sync with
27    gettext/gettext-runtime/intl/setlocale.c !  */
28
29 /* Specification.  */
30 #include <locale.h>
31
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35
36 #include "localename.h"
37
38 #if HAVE_CFLOCALECOPYPREFERREDLANGUAGES || HAVE_CFPREFERENCESCOPYAPPVALUE
39 # if HAVE_CFLOCALECOPYPREFERREDLANGUAGES
40 #  include <CoreFoundation/CFLocale.h>
41 # elif HAVE_CFPREFERENCESCOPYAPPVALUE
42 #  include <CoreFoundation/CFPreferences.h>
43 # endif
44 # include <CoreFoundation/CFPropertyList.h>
45 # include <CoreFoundation/CFArray.h>
46 # include <CoreFoundation/CFString.h>
47 extern void gl_locale_name_canonicalize (char *name);
48 #endif
49
50 #if 1
51
52 # undef setlocale
53
54 /* Return string representation of locale category CATEGORY.  */
55 static const char *
56 category_to_name (int category)
57 {
58   const char *retval;
59
60   switch (category)
61   {
62   case LC_COLLATE:
63     retval = "LC_COLLATE";
64     break;
65   case LC_CTYPE:
66     retval = "LC_CTYPE";
67     break;
68   case LC_MONETARY:
69     retval = "LC_MONETARY";
70     break;
71   case LC_NUMERIC:
72     retval = "LC_NUMERIC";
73     break;
74   case LC_TIME:
75     retval = "LC_TIME";
76     break;
77   case LC_MESSAGES:
78     retval = "LC_MESSAGES";
79     break;
80   default:
81     /* If you have a better idea for a default value let me know.  */
82     retval = "LC_XXX";
83   }
84
85   return retval;
86 }
87
88 # if defined _WIN32 && ! defined __CYGWIN__
89
90 /* The native Windows setlocale() function expects locale names of the form
91    "German" or "German_Germany" or "DEU", but not "de" or "de_DE".  We need
92    to convert the names from the form with ISO 639 language code and ISO 3166
93    country code to the form with English names or with three-letter identifier.
94    The three-letter identifiers known by a Windows XP SP2 or SP3 are:
95      AFK  Afrikaans_South Africa.1252
96      ARA  Arabic_Saudi Arabia.1256
97      ARB  Arabic_Lebanon.1256
98      ARE  Arabic_Egypt.1256
99      ARG  Arabic_Algeria.1256
100      ARH  Arabic_Bahrain.1256
101      ARI  Arabic_Iraq.1256
102      ARJ  Arabic_Jordan.1256
103      ARK  Arabic_Kuwait.1256
104      ARL  Arabic_Libya.1256
105      ARM  Arabic_Morocco.1256
106      ARO  Arabic_Oman.1256
107      ARQ  Arabic_Qatar.1256
108      ARS  Arabic_Syria.1256
109      ART  Arabic_Tunisia.1256
110      ARU  Arabic_U.A.E..1256
111      ARY  Arabic_Yemen.1256
112      AZE  Azeri (Latin)_Azerbaijan.1254
113      BEL  Belarusian_Belarus.1251
114      BGR  Bulgarian_Bulgaria.1251
115      BSB  Bosnian_Bosnia and Herzegovina.1250
116      BSC  Bosnian (Cyrillic)_Bosnia and Herzegovina.1250  (wrong encoding!)
117      CAT  Catalan_Spain.1252
118      CHH  Chinese_Hong Kong S.A.R..950
119      CHI  Chinese_Singapore.936
120      CHS  Chinese_People's Republic of China.936
121      CHT  Chinese_Taiwan.950
122      CSY  Czech_Czech Republic.1250
123      CYM  Welsh_United Kingdom.1252
124      DAN  Danish_Denmark.1252
125      DEA  German_Austria.1252
126      DEC  German_Liechtenstein.1252
127      DEL  German_Luxembourg.1252
128      DES  German_Switzerland.1252
129      DEU  German_Germany.1252
130      ELL  Greek_Greece.1253
131      ENA  English_Australia.1252
132      ENB  English_Caribbean.1252
133      ENC  English_Canada.1252
134      ENG  English_United Kingdom.1252
135      ENI  English_Ireland.1252
136      ENJ  English_Jamaica.1252
137      ENL  English_Belize.1252
138      ENP  English_Republic of the Philippines.1252
139      ENS  English_South Africa.1252
140      ENT  English_Trinidad and Tobago.1252
141      ENU  English_United States.1252
142      ENW  English_Zimbabwe.1252
143      ENZ  English_New Zealand.1252
144      ESA  Spanish_Panama.1252
145      ESB  Spanish_Bolivia.1252
146      ESC  Spanish_Costa Rica.1252
147      ESD  Spanish_Dominican Republic.1252
148      ESE  Spanish_El Salvador.1252
149      ESF  Spanish_Ecuador.1252
150      ESG  Spanish_Guatemala.1252
151      ESH  Spanish_Honduras.1252
152      ESI  Spanish_Nicaragua.1252
153      ESL  Spanish_Chile.1252
154      ESM  Spanish_Mexico.1252
155      ESN  Spanish_Spain.1252
156      ESO  Spanish_Colombia.1252
157      ESP  Spanish_Spain.1252
158      ESR  Spanish_Peru.1252
159      ESS  Spanish_Argentina.1252
160      ESU  Spanish_Puerto Rico.1252
161      ESV  Spanish_Venezuela.1252
162      ESY  Spanish_Uruguay.1252
163      ESZ  Spanish_Paraguay.1252
164      ETI  Estonian_Estonia.1257
165      EUQ  Basque_Spain.1252
166      FAR  Farsi_Iran.1256
167      FIN  Finnish_Finland.1252
168      FOS  Faroese_Faroe Islands.1252
169      FPO  Filipino_Philippines.1252
170      FRA  French_France.1252
171      FRB  French_Belgium.1252
172      FRC  French_Canada.1252
173      FRL  French_Luxembourg.1252
174      FRM  French_Principality of Monaco.1252
175      FRS  French_Switzerland.1252
176      FYN  Frisian_Netherlands.1252
177      GLC  Galician_Spain.1252
178      HEB  Hebrew_Israel.1255
179      HRB  Croatian_Bosnia and Herzegovina.1250
180      HRV  Croatian_Croatia.1250
181      HUN  Hungarian_Hungary.1250
182      IND  Indonesian_Indonesia.1252
183      IRE  Irish_Ireland.1252
184      ISL  Icelandic_Iceland.1252
185      ITA  Italian_Italy.1252
186      ITS  Italian_Switzerland.1252
187      IUK  Inuktitut (Latin)_Canada.1252
188      JPN  Japanese_Japan.932
189      KKZ  Kazakh_Kazakhstan.1251
190      KOR  Korean_Korea.949
191      KYR  Kyrgyz_Kyrgyzstan.1251
192      LBX  Luxembourgish_Luxembourg.1252
193      LTH  Lithuanian_Lithuania.1257
194      LVI  Latvian_Latvia.1257
195      MKI  FYRO Macedonian_Former Yugoslav Republic of Macedonia.1251
196      MON  Mongolian_Mongolia.1251
197      MPD  Mapudungun_Chile.1252
198      MSB  Malay_Brunei Darussalam.1252
199      MSL  Malay_Malaysia.1252
200      MWK  Mohawk_Canada.1252
201      NLB  Dutch_Belgium.1252
202      NLD  Dutch_Netherlands.1252
203      NON  Norwegian-Nynorsk_Norway.1252
204      NOR  Norwegian (BokmÃ¥l)_Norway.1252
205      NSO  Northern Sotho_South Africa.1252
206      PLK  Polish_Poland.1250
207      PTB  Portuguese_Brazil.1252
208      PTG  Portuguese_Portugal.1252
209      QUB  Quechua_Bolivia.1252
210      QUE  Quechua_Ecuador.1252
211      QUP  Quechua_Peru.1252
212      RMC  Romansh_Switzerland.1252
213      ROM  Romanian_Romania.1250
214      RUS  Russian_Russia.1251
215      SKY  Slovak_Slovakia.1250
216      SLV  Slovenian_Slovenia.1250
217      SMA  Sami (Southern)_Norway.1252
218      SMB  Sami (Southern)_Sweden.1252
219      SME  Sami (Northern)_Norway.1252
220      SMF  Sami (Northern)_Sweden.1252
221      SMG  Sami (Northern)_Finland.1252
222      SMJ  Sami (Lule)_Norway.1252
223      SMK  Sami (Lule)_Sweden.1252
224      SMN  Sami (Inari)_Finland.1252
225      SMS  Sami (Skolt)_Finland.1252
226      SQI  Albanian_Albania.1250
227      SRB  Serbian (Cyrillic)_Serbia and Montenegro.1251
228      SRL  Serbian (Latin)_Serbia and Montenegro.1250
229      SRN  Serbian (Cyrillic)_Bosnia and Herzegovina.1251
230      SRS  Serbian (Latin)_Bosnia and Herzegovina.1250
231      SVE  Swedish_Sweden.1252
232      SVF  Swedish_Finland.1252
233      SWK  Swahili_Kenya.1252
234      THA  Thai_Thailand.874
235      TRK  Turkish_Turkey.1254
236      TSN  Tswana_South Africa.1252
237      TTT  Tatar_Russia.1251
238      UKR  Ukrainian_Ukraine.1251
239      URD  Urdu_Islamic Republic of Pakistan.1256
240      USA  English_United States.1252
241      UZB  Uzbek (Latin)_Uzbekistan.1254
242      VIT  Vietnamese_Viet Nam.1258
243      XHO  Xhosa_South Africa.1252
244      ZHH  Chinese_Hong Kong S.A.R..950
245      ZHI  Chinese_Singapore.936
246      ZHM  Chinese_Macau S.A.R..950
247      ZUL  Zulu_South Africa.1252
248  */
249
250 /* Table from ISO 639 language code, optionally with country or script suffix,
251    to English name.
252    Keep in sync with the gl_locale_name_from_win32_LANGID function in
253    localename.c!  */
254 struct table_entry
255 {
256   const char *code;
257   const char *english;
258 };
259 static const struct table_entry language_table[] =
260   {
261     { "af", "Afrikaans" },
262     { "am", "Amharic" },
263     { "ar", "Arabic" },
264     { "arn", "Mapudungun" },
265     { "as", "Assamese" },
266     { "az@cyrillic", "Azeri (Cyrillic)" },
267     { "az@latin", "Azeri (Latin)" },
268     { "ba", "Bashkir" },
269     { "be", "Belarusian" },
270     { "ber", "Tamazight" },
271     { "ber@arabic", "Tamazight (Arabic)" },
272     { "ber@latin", "Tamazight (Latin)" },
273     { "bg", "Bulgarian" },
274     { "bin", "Edo" },
275     { "bn", "Bengali" },
276     { "bn_BD", "Bengali (Bangladesh)" },
277     { "bn_IN", "Bengali (India)" },
278     { "bnt", "Sutu" },
279     { "bo", "Tibetan" },
280     { "br", "Breton" },
281     { "bs", "BSB" }, /* "Bosnian (Latin)" */
282     { "bs@cyrillic", "BSC" }, /* Bosnian (Cyrillic) */
283     { "ca", "Catalan" },
284     { "chr", "Cherokee" },
285     { "co", "Corsican" },
286     { "cpe", "Hawaiian" },
287     { "cs", "Czech" },
288     { "cy", "Welsh" },
289     { "da", "Danish" },
290     { "de", "German" },
291     { "dsb", "Lower Sorbian" },
292     { "dv", "Divehi" },
293     { "el", "Greek" },
294     { "en", "English" },
295     { "es", "Spanish" },
296     { "et", "Estonian" },
297     { "eu", "Basque" },
298     { "fa", "Farsi" },
299     { "ff", "Fulfulde" },
300     { "fi", "Finnish" },
301     { "fo", "Faroese" }, /* "Faeroese" does not work */
302     { "fr", "French" },
303     { "fy", "Frisian" },
304     { "ga", "IRE" }, /* Gaelic (Ireland) */
305     { "gd", "Gaelic (Scotland)" },
306     { "gd", "Scottish Gaelic" },
307     { "gl", "Galician" },
308     { "gn", "Guarani" },
309     { "gsw", "Alsatian" },
310     { "gu", "Gujarati" },
311     { "ha", "Hausa" },
312     { "he", "Hebrew" },
313     { "hi", "Hindi" },
314     { "hr", "Croatian" },
315     { "hsb", "Upper Sorbian" },
316     { "hu", "Hungarian" },
317     { "hy", "Armenian" },
318     { "id", "Indonesian" },
319     { "ig", "Igbo" },
320     { "ii", "Yi" },
321     { "is", "Icelandic" },
322     { "it", "Italian" },
323     { "iu", "IUK" }, /* Inuktitut */
324     { "ja", "Japanese" },
325     { "ka", "Georgian" },
326     { "kk", "Kazakh" },
327     { "kl", "Greenlandic" },
328     { "km", "Cambodian" },
329     { "km", "Khmer" },
330     { "kn", "Kannada" },
331     { "ko", "Korean" },
332     { "kok", "Konkani" },
333     { "kr", "Kanuri" },
334     { "ks", "Kashmiri" },
335     { "ks_IN", "Kashmiri_India" },
336     { "ks_PK", "Kashmiri (Arabic)_Pakistan" },
337     { "ky", "Kyrgyz" },
338     { "la", "Latin" },
339     { "lb", "Luxembourgish" },
340     { "lo", "Lao" },
341     { "lt", "Lithuanian" },
342     { "lv", "Latvian" },
343     { "mi", "Maori" },
344     { "mk", "FYRO Macedonian" },
345     { "mk", "Macedonian" },
346     { "ml", "Malayalam" },
347     { "mn", "Mongolian" },
348     { "mni", "Manipuri" },
349     { "moh", "Mohawk" },
350     { "mr", "Marathi" },
351     { "ms", "Malay" },
352     { "mt", "Maltese" },
353     { "my", "Burmese" },
354     { "nb", "NOR" }, /* Norwegian BokmÃ¥l */
355     { "ne", "Nepali" },
356     { "nic", "Ibibio" },
357     { "nl", "Dutch" },
358     { "nn", "NON" }, /* Norwegian Nynorsk */
359     { "no", "Norwegian" },
360     { "nso", "Northern Sotho" },
361     { "nso", "Sepedi" },
362     { "oc", "Occitan" },
363     { "om", "Oromo" },
364     { "or", "Oriya" },
365     { "pa", "Punjabi" },
366     { "pap", "Papiamentu" },
367     { "pl", "Polish" },
368     { "prs", "Dari" },
369     { "ps", "Pashto" },
370     { "pt", "Portuguese" },
371     { "qu", "Quechua" },
372     { "qut", "K'iche'" },
373     { "rm", "Romansh" },
374     { "ro", "Romanian" },
375     { "ru", "Russian" },
376     { "rw", "Kinyarwanda" },
377     { "sa", "Sanskrit" },
378     { "sah", "Yakut" },
379     { "sd", "Sindhi" },
380     { "se", "Sami (Northern)" },
381     { "se", "Northern Sami" },
382     { "si", "Sinhalese" },
383     { "sk", "Slovak" },
384     { "sl", "Slovenian" },
385     { "sma", "Sami (Southern)" },
386     { "sma", "Southern Sami" },
387     { "smj", "Sami (Lule)" },
388     { "smj", "Lule Sami" },
389     { "smn", "Sami (Inari)" },
390     { "smn", "Inari Sami" },
391     { "sms", "Sami (Skolt)" },
392     { "sms", "Skolt Sami" },
393     { "so", "Somali" },
394     { "sq", "Albanian" },
395     { "sr", "Serbian (Latin)" },
396     { "sr@cyrillic", "SRB" }, /* Serbian (Cyrillic) */
397     { "sv", "Swedish" },
398     { "sw", "Swahili" },
399     { "syr", "Syriac" },
400     { "ta", "Tamil" },
401     { "te", "Telugu" },
402     { "tg", "Tajik" },
403     { "th", "Thai" },
404     { "ti", "Tigrinya" },
405     { "tk", "Turkmen" },
406     { "tl", "Filipino" },
407     { "tn", "Tswana" },
408     { "tr", "Turkish" },
409     { "ts", "Tsonga" },
410     { "tt", "Tatar" },
411     { "ug", "Uighur" },
412     { "uk", "Ukrainian" },
413     { "ur", "Urdu" },
414     { "uz", "Uzbek" },
415     { "uz", "Uzbek (Latin)" },
416     { "uz@cyrillic", "Uzbek (Cyrillic)" },
417     { "ve", "Venda" },
418     { "vi", "Vietnamese" },
419     { "wen", "Sorbian" },
420     { "wo", "Wolof" },
421     { "xh", "Xhosa" },
422     { "yi", "Yiddish" },
423     { "yo", "Yoruba" },
424     { "zh", "Chinese" },
425     { "zu", "Zulu" }
426   };
427
428 /* Table from ISO 3166 country code to English name.
429    Keep in sync with the gl_locale_name_from_win32_LANGID function in
430    localename.c!  */
431 static const struct table_entry country_table[] =
432   {
433     { "AE", "U.A.E." },
434     { "AF", "Afghanistan" },
435     { "AL", "Albania" },
436     { "AM", "Armenia" },
437     { "AN", "Netherlands Antilles" },
438     { "AR", "Argentina" },
439     { "AT", "Austria" },
440     { "AU", "Australia" },
441     { "AZ", "Azerbaijan" },
442     { "BA", "Bosnia and Herzegovina" },
443     { "BD", "Bangladesh" },
444     { "BE", "Belgium" },
445     { "BG", "Bulgaria" },
446     { "BH", "Bahrain" },
447     { "BN", "Brunei Darussalam" },
448     { "BO", "Bolivia" },
449     { "BR", "Brazil" },
450     { "BT", "Bhutan" },
451     { "BY", "Belarus" },
452     { "BZ", "Belize" },
453     { "CA", "Canada" },
454     { "CG", "Congo" },
455     { "CH", "Switzerland" },
456     { "CI", "Cote d'Ivoire" },
457     { "CL", "Chile" },
458     { "CM", "Cameroon" },
459     { "CN", "People's Republic of China" },
460     { "CO", "Colombia" },
461     { "CR", "Costa Rica" },
462     { "CS", "Serbia and Montenegro" },
463     { "CZ", "Czech Republic" },
464     { "DE", "Germany" },
465     { "DK", "Denmark" },
466     { "DO", "Dominican Republic" },
467     { "DZ", "Algeria" },
468     { "EC", "Ecuador" },
469     { "EE", "Estonia" },
470     { "EG", "Egypt" },
471     { "ER", "Eritrea" },
472     { "ES", "Spain" },
473     { "ET", "Ethiopia" },
474     { "FI", "Finland" },
475     { "FO", "Faroe Islands" },
476     { "FR", "France" },
477     { "GB", "United Kingdom" },
478     { "GD", "Caribbean" },
479     { "GE", "Georgia" },
480     { "GL", "Greenland" },
481     { "GR", "Greece" },
482     { "GT", "Guatemala" },
483     { "HK", "Hong Kong" },
484     { "HK", "Hong Kong S.A.R." },
485     { "HN", "Honduras" },
486     { "HR", "Croatia" },
487     { "HT", "Haiti" },
488     { "HU", "Hungary" },
489     { "ID", "Indonesia" },
490     { "IE", "Ireland" },
491     { "IL", "Israel" },
492     { "IN", "India" },
493     { "IQ", "Iraq" },
494     { "IR", "Iran" },
495     { "IS", "Iceland" },
496     { "IT", "Italy" },
497     { "JM", "Jamaica" },
498     { "JO", "Jordan" },
499     { "JP", "Japan" },
500     { "KE", "Kenya" },
501     { "KG", "Kyrgyzstan" },
502     { "KH", "Cambodia" },
503     { "KR", "South Korea" },
504     { "KW", "Kuwait" },
505     { "KZ", "Kazakhstan" },
506     { "LA", "Laos" },
507     { "LB", "Lebanon" },
508     { "LI", "Liechtenstein" },
509     { "LK", "Sri Lanka" },
510     { "LT", "Lithuania" },
511     { "LU", "Luxembourg" },
512     { "LV", "Latvia" },
513     { "LY", "Libya" },
514     { "MA", "Morocco" },
515     { "MC", "Principality of Monaco" },
516     { "MD", "Moldava" },
517     { "MD", "Moldova" },
518     { "ME", "Montenegro" },
519     { "MK", "Former Yugoslav Republic of Macedonia" },
520     { "ML", "Mali" },
521     { "MM", "Myanmar" },
522     { "MN", "Mongolia" },
523     { "MO", "Macau S.A.R." },
524     { "MT", "Malta" },
525     { "MV", "Maldives" },
526     { "MX", "Mexico" },
527     { "MY", "Malaysia" },
528     { "NG", "Nigeria" },
529     { "NI", "Nicaragua" },
530     { "NL", "Netherlands" },
531     { "NO", "Norway" },
532     { "NP", "Nepal" },
533     { "NZ", "New Zealand" },
534     { "OM", "Oman" },
535     { "PA", "Panama" },
536     { "PE", "Peru" },
537     { "PH", "Philippines" },
538     { "PK", "Islamic Republic of Pakistan" },
539     { "PL", "Poland" },
540     { "PR", "Puerto Rico" },
541     { "PT", "Portugal" },
542     { "PY", "Paraguay" },
543     { "QA", "Qatar" },
544     { "RE", "Reunion" },
545     { "RO", "Romania" },
546     { "RS", "Serbia" },
547     { "RU", "Russia" },
548     { "RW", "Rwanda" },
549     { "SA", "Saudi Arabia" },
550     { "SE", "Sweden" },
551     { "SG", "Singapore" },
552     { "SI", "Slovenia" },
553     { "SK", "Slovak" },
554     { "SN", "Senegal" },
555     { "SO", "Somalia" },
556     { "SR", "Suriname" },
557     { "SV", "El Salvador" },
558     { "SY", "Syria" },
559     { "TH", "Thailand" },
560     { "TJ", "Tajikistan" },
561     { "TM", "Turkmenistan" },
562     { "TN", "Tunisia" },
563     { "TR", "Turkey" },
564     { "TT", "Trinidad and Tobago" },
565     { "TW", "Taiwan" },
566     { "TZ", "Tanzania" },
567     { "UA", "Ukraine" },
568     { "US", "United States" },
569     { "UY", "Uruguay" },
570     { "VA", "Vatican" },
571     { "VE", "Venezuela" },
572     { "VN", "Viet Nam" },
573     { "YE", "Yemen" },
574     { "ZA", "South Africa" },
575     { "ZW", "Zimbabwe" }
576   };
577
578 /* Given a string STRING, find the set of indices i such that TABLE[i].code is
579    the given STRING.  It is a range [lo,hi-1].  */
580 typedef struct { size_t lo; size_t hi; } range_t;
581 static void
582 search (const struct table_entry *table, size_t table_size, const char *string,
583         range_t *result)
584 {
585   /* The table is sorted.  Perform a binary search.  */
586   size_t hi = table_size;
587   size_t lo = 0;
588   while (lo < hi)
589     {
590       /* Invariant:
591          for i < lo, strcmp (table[i].code, string) < 0,
592          for i >= hi, strcmp (table[i].code, string) > 0.  */
593       size_t mid = (hi + lo) >> 1; /* >= lo, < hi */
594       int cmp = strcmp (table[mid].code, string);
595       if (cmp < 0)
596         lo = mid + 1;
597       else if (cmp > 0)
598         hi = mid;
599       else
600         {
601           /* Found an i with
602                strcmp (language_table[i].code, string) == 0.
603              Find the entire interval of such i.  */
604           {
605             size_t i;
606
607             for (i = mid; i > lo; )
608               {
609                 i--;
610                 if (strcmp (table[i].code, string) < 0)
611                   {
612                     lo = i + 1;
613                     break;
614                   }
615               }
616           }
617           {
618             size_t i;
619
620             for (i = mid; i < hi; i++)
621               {
622                 if (strcmp (table[i].code, string) > 0)
623                   {
624                     hi = i;
625                     break;
626                   }
627               }
628           }
629           /* The set of i with
630                strcmp (language_table[i].code, string) == 0
631              is the interval [lo, hi-1].  */
632           break;
633         }
634     }
635   result->lo = lo;
636   result->hi = hi;
637 }
638
639 /* Like setlocale, but accept also locale names in the form ll or ll_CC,
640    where ll is an ISO 639 language code and CC is an ISO 3166 country code.  */
641 static char *
642 setlocale_unixlike (int category, const char *locale)
643 {
644   char *result;
645   char llCC_buf[64];
646   char ll_buf[64];
647   char CC_buf[64];
648
649   /* The native Windows implementation of setlocale understands the special
650      locale name "C", but not "POSIX".  Therefore map "POSIX" to "C".  */
651   if (locale != NULL && strcmp (locale, "POSIX") == 0)
652     locale = "C";
653
654   /* First, try setlocale with the original argument unchanged.  */
655   result = setlocale (category, locale);
656   if (result != NULL)
657     return result;
658
659   /* Otherwise, assume the argument is in the form
660        language[_territory][.codeset][@modifier]
661      and try to map it using the tables.  */
662   if (strlen (locale) < sizeof (llCC_buf))
663     {
664       /* Second try: Remove the codeset part.  */
665       {
666         const char *p = locale;
667         char *q = llCC_buf;
668
669         /* Copy the part before the dot.  */
670         for (; *p != '\0' && *p != '.'; p++, q++)
671           *q = *p;
672         if (*p == '.')
673           /* Skip the part up to the '@', if any.  */
674           for (; *p != '\0' && *p != '@'; p++)
675             ;
676         /* Copy the part starting with '@', if any.  */
677         for (; *p != '\0'; p++, q++)
678           *q = *p;
679         *q = '\0';
680       }
681       /* llCC_buf now contains
682            language[_territory][@modifier]
683        */
684       if (strcmp (llCC_buf, locale) != 0)
685         {
686           result = setlocale (category, llCC_buf);
687           if (result != NULL)
688             return result;
689         }
690       /* Look it up in language_table.  */
691       {
692         range_t range;
693         size_t i;
694
695         search (language_table,
696                 sizeof (language_table) / sizeof (language_table[0]),
697                 llCC_buf,
698                 &range);
699
700         for (i = range.lo; i < range.hi; i++)
701           {
702             /* Try the replacement in language_table[i].  */
703             result = setlocale (category, language_table[i].english);
704             if (result != NULL)
705               return result;
706           }
707       }
708       /* Split language[_territory][@modifier]
709          into  ll_buf = language[@modifier]
710          and   CC_buf = territory
711        */
712       {
713         const char *underscore = strchr (llCC_buf, '_');
714         if (underscore != NULL)
715           {
716             const char *territory_start = underscore + 1;
717             const char *territory_end = strchr (territory_start, '@');
718             if (territory_end == NULL)
719               territory_end = territory_start + strlen (territory_start);
720
721             memcpy (ll_buf, llCC_buf, underscore - llCC_buf);
722             strcpy (ll_buf + (underscore - llCC_buf), territory_end);
723
724             memcpy (CC_buf, territory_start, territory_end - territory_start);
725             CC_buf[territory_end - territory_start] = '\0';
726
727             {
728               /* Look up ll_buf in language_table
729                  and CC_buf in country_table.  */
730               range_t language_range;
731
732               search (language_table,
733                       sizeof (language_table) / sizeof (language_table[0]),
734                       ll_buf,
735                       &language_range);
736               if (language_range.lo < language_range.hi)
737                 {
738                   range_t country_range;
739
740                   search (country_table,
741                           sizeof (country_table) / sizeof (country_table[0]),
742                           CC_buf,
743                           &country_range);
744                   if (country_range.lo < country_range.hi)
745                     {
746                       size_t i;
747                       size_t j;
748
749                       for (i = language_range.lo; i < language_range.hi; i++)
750                         for (j = country_range.lo; j < country_range.hi; j++)
751                           {
752                             /* Concatenate the replacements.  */
753                             const char *part1 = language_table[i].english;
754                             size_t part1_len = strlen (part1);
755                             const char *part2 = country_table[j].english;
756                             size_t part2_len = strlen (part2) + 1;
757                             char buf[64+64];
758
759                             if (!(part1_len + 1 + part2_len <= sizeof (buf)))
760                               abort ();
761                             memcpy (buf, part1, part1_len);
762                             buf[part1_len] = '_';
763                             memcpy (buf + part1_len + 1, part2, part2_len);
764
765                             /* Try the concatenated replacements.  */
766                             result = setlocale (category, buf);
767                             if (result != NULL)
768                               return result;
769                           }
770                     }
771
772                   /* Try omitting the country entirely.  This may set a locale
773                      corresponding to the wrong country, but is better than
774                      failing entirely.  */
775                   {
776                     size_t i;
777
778                     for (i = language_range.lo; i < language_range.hi; i++)
779                       {
780                         /* Try only the language replacement.  */
781                         result =
782                           setlocale (category, language_table[i].english);
783                         if (result != NULL)
784                           return result;
785                       }
786                   }
787                 }
788             }
789           }
790       }
791     }
792
793   /* Failed.  */
794   return NULL;
795 }
796
797 # else
798 #  define setlocale_unixlike setlocale
799 # endif
800
801 # if LC_MESSAGES == 1729
802
803 /* The system does not store an LC_MESSAGES locale category.  Do it here.  */
804 static char lc_messages_name[64] = "C";
805
806 /* Like setlocale, but support also LC_MESSAGES.  */
807 static char *
808 setlocale_single (int category, const char *locale)
809 {
810   if (category == LC_MESSAGES)
811     {
812       if (locale != NULL)
813         {
814           lc_messages_name[sizeof (lc_messages_name) - 1] = '\0';
815           strncpy (lc_messages_name, locale, sizeof (lc_messages_name) - 1);
816         }
817       return lc_messages_name;
818     }
819   else
820     return setlocale_unixlike (category, locale);
821 }
822
823 # else
824 #  define setlocale_single setlocale_unixlike
825 # endif
826
827 char *
828 rpl_setlocale (int category, const char *locale)
829 {
830   if (locale != NULL && locale[0] == '\0')
831     {
832       /* A request to the set the current locale to the default locale.  */
833       if (category == LC_ALL)
834         {
835           /* Set LC_CTYPE first.  Then the other categories.  */
836           static int const categories[] =
837             {
838               LC_CTYPE,
839               LC_NUMERIC,
840               LC_TIME,
841               LC_COLLATE,
842               LC_MONETARY,
843               LC_MESSAGES
844             };
845           char *saved_locale;
846           const char *base_name;
847           unsigned int i;
848
849           /* Back up the old locale, in case one of the steps fails.  */
850           saved_locale = setlocale (LC_ALL, NULL);
851           if (saved_locale == NULL)
852             return NULL;
853           saved_locale = strdup (saved_locale);
854           if (saved_locale == NULL)
855             return NULL;
856
857           /* Set LC_CTYPE category.  Set all other categories (except possibly
858              LC_MESSAGES) to the same value in the same call; this is likely to
859              save calls.  */
860           base_name =
861             gl_locale_name_environ (LC_CTYPE, category_to_name (LC_CTYPE));
862           if (base_name == NULL)
863             base_name = gl_locale_name_default ();
864
865           if (setlocale_unixlike (LC_ALL, base_name) != NULL)
866             {
867               /* LC_CTYPE category already set.  */
868               i = 1;
869             }
870           else
871             {
872               /* On Mac OS X, "UTF-8" is a valid locale name for LC_CTYPE but
873                  not for LC_ALL.  Therefore this call may fail.  So, try
874                  another base_name.  */
875               base_name = "C";
876               if (setlocale_unixlike (LC_ALL, base_name) == NULL)
877                 goto fail;
878               i = 0;
879             }
880 # if defined _WIN32 && ! defined __CYGWIN__
881           /* On native Windows, setlocale(LC_ALL,...) may succeed but set the
882              LC_CTYPE category to an invalid value ("C") when it does not
883              support the specified encoding.  Report a failure instead.  */
884           if (strchr (base_name, '.') != NULL
885               && strcmp (setlocale (LC_CTYPE, NULL), "C") == 0)
886             goto fail;
887 # endif
888
889           for (; i < sizeof (categories) / sizeof (categories[0]); i++)
890             {
891               int cat = categories[i];
892               const char *name;
893
894               name = gl_locale_name_environ (cat, category_to_name (cat));
895               if (name == NULL)
896                 name = gl_locale_name_default ();
897
898               /* If name is the same as base_name, it has already been set
899                  through the setlocale call before the loop.  */
900               if (strcmp (name, base_name) != 0
901 # if LC_MESSAGES == 1729
902                   || cat == LC_MESSAGES
903 # endif
904                  )
905                 if (setlocale_single (cat, name) == NULL)
906 # if defined __APPLE__ && defined __MACH__
907                   {
908                     /* On Mac OS X 10.13, some locales can be set through
909                        System Preferences > Language & Region, that are not
910                        supported by libc.  The system's setlocale() falls
911                        back to "C" for these locale categories.  We can possibly
912                        do better.  If we can't, print a warning, to limit user
913                        expectations.  */
914                     int warn = 1;
915
916                     if (cat == LC_CTYPE)
917                       warn = (setlocale_single (cat, "UTF-8") == NULL);
918 #  if HAVE_CFLOCALECOPYPREFERREDLANGUAGES || HAVE_CFPREFERENCESCOPYAPPVALUE /* MacOS X 10.4 or newer */
919                     else if (cat == LC_MESSAGES)
920                       {
921                         /* Take the primary language preference.  */
922 #   if HAVE_CFLOCALECOPYPREFERREDLANGUAGES /* MacOS X 10.5 or newer */
923                         CFArrayRef prefArray = CFLocaleCopyPreferredLanguages ();
924 #   elif HAVE_CFPREFERENCESCOPYAPPVALUE /* MacOS X 10.4 or newer */
925                         CFTypeRef preferences =
926                           CFPreferencesCopyAppValue (CFSTR ("AppleLanguages"),
927                                                      kCFPreferencesCurrentApplication);
928                         if (preferences != NULL
929                             && CFGetTypeID (preferences) == CFArrayGetTypeID ())
930                           {
931                             CFArrayRef prefArray = (CFArrayRef)preferences;
932 #   endif
933                             int n = CFArrayGetCount (prefArray);
934                             if (n > 0)
935                               {
936                                 char buf[256];
937                                 CFTypeRef element = CFArrayGetValueAtIndex (prefArray, 0);
938                                 if (element != NULL
939                                     && CFGetTypeID (element) == CFStringGetTypeID ()
940                                     && CFStringGetCString ((CFStringRef)element,
941                                                            buf, sizeof (buf),
942                                                            kCFStringEncodingASCII))
943                                   {
944                                     /* Remove the country.
945                                        E.g. "zh-Hans-DE" -> "zh-Hans".  */
946                                     char *last_minus = strrchr (buf, '-');
947                                     if (last_minus != NULL)
948                                       *last_minus = '\0';
949
950                                     /* Convert to Unix locale name.
951                                        E.g. "zh-Hans" -> "zh_CN".  */
952                                     gl_locale_name_canonicalize (buf);
953
954                                     /* Try setlocale with this value.  */
955                                     warn = (setlocale_single (cat, buf) == NULL);
956                                   }
957                               }
958 #   if HAVE_CFLOCALECOPYPREFERREDLANGUAGES /* MacOS X 10.5 or newer */
959                         CFRelease (prefArray);
960 #   elif HAVE_CFPREFERENCESCOPYAPPVALUE /* MacOS X 10.4 or newer */
961                           }
962 #   endif
963                       }
964 #  endif
965                     /* No fallback possible for LC_NUMERIC.  The application
966                        should use the locale properties
967                        kCFLocaleDecimalSeparator, kCFLocaleGroupingSeparator.
968                        No fallback possible for LC_TIME.  The application should
969                        use the locale property kCFLocaleCalendarIdentifier.
970                        No fallback possible for LC_COLLATE.  The application
971                        should use the locale properties
972                        kCFLocaleCollationIdentifier, kCFLocaleCollatorIdentifier.
973                        No fallback possible for LC_MONETARY.  The application
974                        should use the locale properties
975                        kCFLocaleCurrencySymbol, kCFLocaleCurrencyCode.  */
976
977                     if (warn)
978                       fprintf (stderr,
979                                "Warning: Failed to set locale category %s to %s.\n",
980                                category_to_name (cat), name);
981                   }
982 # else
983                   goto fail;
984 # endif
985             }
986
987           /* All steps were successful.  */
988           free (saved_locale);
989           return setlocale (LC_ALL, NULL);
990
991         fail:
992           if (saved_locale[0] != '\0') /* don't risk an endless recursion */
993             setlocale (LC_ALL, saved_locale);
994           free (saved_locale);
995           return NULL;
996         }
997       else
998         {
999           const char *name =
1000             gl_locale_name_environ (category, category_to_name (category));
1001           if (name == NULL)
1002             name = gl_locale_name_default ();
1003
1004           return setlocale_single (category, name);
1005         }
1006     }
1007   else
1008     {
1009 # if defined _WIN32 && ! defined __CYGWIN__
1010       if (category == LC_ALL && locale != NULL && strchr (locale, '.') != NULL)
1011         {
1012           char *saved_locale;
1013
1014           /* Back up the old locale.  */
1015           saved_locale = setlocale (LC_ALL, NULL);
1016           if (saved_locale == NULL)
1017             return NULL;
1018           saved_locale = strdup (saved_locale);
1019           if (saved_locale == NULL)
1020             return NULL;
1021
1022           if (setlocale_unixlike (LC_ALL, locale) == NULL)
1023             {
1024               free (saved_locale);
1025               return NULL;
1026             }
1027
1028           /* On native Windows, setlocale(LC_ALL,...) may succeed but set the
1029              LC_CTYPE category to an invalid value ("C") when it does not
1030              support the specified encoding.  Report a failure instead.  */
1031           if (strcmp (setlocale (LC_CTYPE, NULL), "C") == 0)
1032             {
1033               if (saved_locale[0] != '\0') /* don't risk an endless recursion */
1034                 setlocale (LC_ALL, saved_locale);
1035               free (saved_locale);
1036               return NULL;
1037             }
1038
1039           /* It was really successful.  */
1040           free (saved_locale);
1041           return setlocale (LC_ALL, NULL);
1042         }
1043       else
1044 # endif
1045         return setlocale_single (category, locale);
1046     }
1047 }
1048
1049 #endif