Initial import of binutils 2.22 on the new vendor branch
[dragonfly.git] / contrib / texinfo / gnulib / lib / localcharset.c
1 /* Determine a canonical name for the current locale's character encoding.
2
3    Copyright (C) 2000-2006, 2008 Free Software Foundation, Inc.
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3, or (at your option)
8    any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License along
16    with this program; if not, write to the Free Software Foundation,
17    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
18
19 /* Written by Bruno Haible <bruno@clisp.org>.  */
20
21 #include <config.h>
22
23 /* Specification.  */
24 #include "localcharset.h"
25
26 #include <stddef.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <stdlib.h>
30
31 #if defined _WIN32 || defined __WIN32__
32 # define WIN32_NATIVE
33 #endif
34
35 #if defined __EMX__
36 /* Assume EMX program runs on OS/2, even if compiled under DOS.  */
37 # ifndef OS2
38 #  define OS2
39 # endif
40 #endif
41
42 #if !defined WIN32_NATIVE
43 # if HAVE_LANGINFO_CODESET
44 #  include <langinfo.h>
45 # else
46 #  if 0 /* see comment below */
47 #   include <locale.h>
48 #  endif
49 # endif
50 # ifdef __CYGWIN__
51 #  define WIN32_LEAN_AND_MEAN
52 #  include <windows.h>
53 # endif
54 #elif defined WIN32_NATIVE
55 # define WIN32_LEAN_AND_MEAN
56 # include <windows.h>
57 #endif
58 #if defined OS2
59 # define INCL_DOS
60 # include <os2.h>
61 #endif
62
63 #if ENABLE_RELOCATABLE
64 # include "relocatable.h"
65 #else
66 # define relocate(pathname) (pathname)
67 #endif
68
69 /* Get LIBDIR.  */
70 #ifndef LIBDIR
71 # include "configmake.h"
72 #endif
73
74 #if defined _WIN32 || defined __WIN32__ || defined __CYGWIN__ || defined __EMX__ || defined __DJGPP__
75   /* Win32, Cygwin, OS/2, DOS */
76 # define ISSLASH(C) ((C) == '/' || (C) == '\\')
77 #endif
78
79 #ifndef DIRECTORY_SEPARATOR
80 # define DIRECTORY_SEPARATOR '/'
81 #endif
82
83 #ifndef ISSLASH
84 # define ISSLASH(C) ((C) == DIRECTORY_SEPARATOR)
85 #endif
86
87 #if HAVE_DECL_GETC_UNLOCKED
88 # undef getc
89 # define getc getc_unlocked
90 #endif
91
92 /* The following static variable is declared 'volatile' to avoid a
93    possible multithread problem in the function get_charset_aliases. If we
94    are running in a threaded environment, and if two threads initialize
95    'charset_aliases' simultaneously, both will produce the same value,
96    and everything will be ok if the two assignments to 'charset_aliases'
97    are atomic. But I don't know what will happen if the two assignments mix.  */
98 #if __STDC__ != 1
99 # define volatile /* empty */
100 #endif
101 /* Pointer to the contents of the charset.alias file, if it has already been
102    read, else NULL.  Its format is:
103    ALIAS_1 '\0' CANONICAL_1 '\0' ... ALIAS_n '\0' CANONICAL_n '\0' '\0'  */
104 static const char * volatile charset_aliases;
105
106 /* Return a pointer to the contents of the charset.alias file.  */
107 static const char *
108 get_charset_aliases (void)
109 {
110   const char *cp;
111
112   cp = charset_aliases;
113   if (cp == NULL)
114     {
115 #if !(defined VMS || defined WIN32_NATIVE || defined __CYGWIN__)
116       FILE *fp;
117       const char *dir;
118       const char *base = "charset.alias";
119       char *file_name;
120
121       /* Make it possible to override the charset.alias location.  This is
122          necessary for running the testsuite before "make install".  */
123       dir = getenv ("CHARSETALIASDIR");
124       if (dir == NULL || dir[0] == '\0')
125         dir = relocate (LIBDIR);
126
127       /* Concatenate dir and base into freshly allocated file_name.  */
128       {
129         size_t dir_len = strlen (dir);
130         size_t base_len = strlen (base);
131         int add_slash = (dir_len > 0 && !ISSLASH (dir[dir_len - 1]));
132         file_name = (char *) malloc (dir_len + add_slash + base_len + 1);
133         if (file_name != NULL)
134           {
135             memcpy (file_name, dir, dir_len);
136             if (add_slash)
137               file_name[dir_len] = DIRECTORY_SEPARATOR;
138             memcpy (file_name + dir_len + add_slash, base, base_len + 1);
139           }
140       }
141
142       if (file_name == NULL || (fp = fopen (file_name, "r")) == NULL)
143         /* Out of memory or file not found, treat it as empty.  */
144         cp = "";
145       else
146         {
147           /* Parse the file's contents.  */
148           char *res_ptr = NULL;
149           size_t res_size = 0;
150
151           for (;;)
152             {
153               int c;
154               char buf1[50+1];
155               char buf2[50+1];
156               size_t l1, l2;
157               char *old_res_ptr;
158
159               c = getc (fp);
160               if (c == EOF)
161                 break;
162               if (c == '\n' || c == ' ' || c == '\t')
163                 continue;
164               if (c == '#')
165                 {
166                   /* Skip comment, to end of line.  */
167                   do
168                     c = getc (fp);
169                   while (!(c == EOF || c == '\n'));
170                   if (c == EOF)
171                     break;
172                   continue;
173                 }
174               ungetc (c, fp);
175               if (fscanf (fp, "%50s %50s", buf1, buf2) < 2)
176                 break;
177               l1 = strlen (buf1);
178               l2 = strlen (buf2);
179               old_res_ptr = res_ptr;
180               if (res_size == 0)
181                 {
182                   res_size = l1 + 1 + l2 + 1;
183                   res_ptr = (char *) malloc (res_size + 1);
184                 }
185               else
186                 {
187                   res_size += l1 + 1 + l2 + 1;
188                   res_ptr = (char *) realloc (res_ptr, res_size + 1);
189                 }
190               if (res_ptr == NULL)
191                 {
192                   /* Out of memory. */
193                   res_size = 0;
194                   if (old_res_ptr != NULL)
195                     free (old_res_ptr);
196                   break;
197                 }
198               strcpy (res_ptr + res_size - (l2 + 1) - (l1 + 1), buf1);
199               strcpy (res_ptr + res_size - (l2 + 1), buf2);
200             }
201           fclose (fp);
202           if (res_size == 0)
203             cp = "";
204           else
205             {
206               *(res_ptr + res_size) = '\0';
207               cp = res_ptr;
208             }
209         }
210
211       if (file_name != NULL)
212         free (file_name);
213
214 #else
215
216 # if defined VMS
217       /* To avoid the troubles of an extra file charset.alias_vms in the
218          sources of many GNU packages, simply inline the aliases here.  */
219       /* The list of encodings is taken from the OpenVMS 7.3-1 documentation
220          "Compaq C Run-Time Library Reference Manual for OpenVMS systems"
221          section 10.7 "Handling Different Character Sets".  */
222       cp = "ISO8859-1" "\0" "ISO-8859-1" "\0"
223            "ISO8859-2" "\0" "ISO-8859-2" "\0"
224            "ISO8859-5" "\0" "ISO-8859-5" "\0"
225            "ISO8859-7" "\0" "ISO-8859-7" "\0"
226            "ISO8859-8" "\0" "ISO-8859-8" "\0"
227            "ISO8859-9" "\0" "ISO-8859-9" "\0"
228            /* Japanese */
229            "eucJP" "\0" "EUC-JP" "\0"
230            "SJIS" "\0" "SHIFT_JIS" "\0"
231            "DECKANJI" "\0" "DEC-KANJI" "\0"
232            "SDECKANJI" "\0" "EUC-JP" "\0"
233            /* Chinese */
234            "eucTW" "\0" "EUC-TW" "\0"
235            "DECHANYU" "\0" "DEC-HANYU" "\0"
236            "DECHANZI" "\0" "GB2312" "\0"
237            /* Korean */
238            "DECKOREAN" "\0" "EUC-KR" "\0";
239 # endif
240
241 # if defined WIN32_NATIVE || defined __CYGWIN__
242       /* To avoid the troubles of installing a separate file in the same
243          directory as the DLL and of retrieving the DLL's directory at
244          runtime, simply inline the aliases here.  */
245
246       cp = "CP936" "\0" "GBK" "\0"
247            "CP1361" "\0" "JOHAB" "\0"
248            "CP20127" "\0" "ASCII" "\0"
249            "CP20866" "\0" "KOI8-R" "\0"
250            "CP20936" "\0" "GB2312" "\0"
251            "CP21866" "\0" "KOI8-RU" "\0"
252            "CP28591" "\0" "ISO-8859-1" "\0"
253            "CP28592" "\0" "ISO-8859-2" "\0"
254            "CP28593" "\0" "ISO-8859-3" "\0"
255            "CP28594" "\0" "ISO-8859-4" "\0"
256            "CP28595" "\0" "ISO-8859-5" "\0"
257            "CP28596" "\0" "ISO-8859-6" "\0"
258            "CP28597" "\0" "ISO-8859-7" "\0"
259            "CP28598" "\0" "ISO-8859-8" "\0"
260            "CP28599" "\0" "ISO-8859-9" "\0"
261            "CP28605" "\0" "ISO-8859-15" "\0"
262            "CP38598" "\0" "ISO-8859-8" "\0"
263            "CP51932" "\0" "EUC-JP" "\0"
264            "CP51936" "\0" "GB2312" "\0"
265            "CP51949" "\0" "EUC-KR" "\0"
266            "CP51950" "\0" "EUC-TW" "\0"
267            "CP54936" "\0" "GB18030" "\0"
268            "CP65001" "\0" "UTF-8" "\0";
269 # endif
270 #endif
271
272       charset_aliases = cp;
273     }
274
275   return cp;
276 }
277
278 /* Determine the current locale's character encoding, and canonicalize it
279    into one of the canonical names listed in config.charset.
280    The result must not be freed; it is statically allocated.
281    If the canonical name cannot be determined, the result is a non-canonical
282    name.  */
283
284 #ifdef STATIC
285 STATIC
286 #endif
287 const char *
288 locale_charset (void)
289 {
290   const char *codeset;
291   const char *aliases;
292
293 #if !(defined WIN32_NATIVE || defined OS2)
294
295 # if HAVE_LANGINFO_CODESET
296
297   /* Most systems support nl_langinfo (CODESET) nowadays.  */
298   codeset = nl_langinfo (CODESET);
299
300 #  ifdef __CYGWIN__
301   /* Cygwin 2006 does not have locales.  nl_langinfo (CODESET) always
302      returns "US-ASCII".  As long as this is not fixed, return the suffix
303      of the locale name from the environment variables (if present) or
304      the codepage as a number.  */
305   if (codeset != NULL && strcmp (codeset, "US-ASCII") == 0)
306     {
307       const char *locale;
308       static char buf[2 + 10 + 1];
309
310       locale = getenv ("LC_ALL");
311       if (locale == NULL || locale[0] == '\0')
312         {
313           locale = getenv ("LC_CTYPE");
314           if (locale == NULL || locale[0] == '\0')
315             locale = getenv ("LANG");
316         }
317       if (locale != NULL && locale[0] != '\0')
318         {
319           /* If the locale name contains an encoding after the dot, return
320              it.  */
321           const char *dot = strchr (locale, '.');
322
323           if (dot != NULL)
324             {
325               const char *modifier;
326
327               dot++;
328               /* Look for the possible @... trailer and remove it, if any.  */
329               modifier = strchr (dot, '@');
330               if (modifier == NULL)
331                 return dot;
332               if (modifier - dot < sizeof (buf))
333                 {
334                   memcpy (buf, dot, modifier - dot);
335                   buf [modifier - dot] = '\0';
336                   return buf;
337                 }
338             }
339         }
340
341       /* Woe32 has a function returning the locale's codepage as a number.  */
342       sprintf (buf, "CP%u", GetACP ());
343       codeset = buf;
344     }
345 #  endif
346
347 # else
348
349   /* On old systems which lack it, use setlocale or getenv.  */
350   const char *locale = NULL;
351
352   /* But most old systems don't have a complete set of locales.  Some
353      (like SunOS 4 or DJGPP) have only the C locale.  Therefore we don't
354      use setlocale here; it would return "C" when it doesn't support the
355      locale name the user has set.  */
356 #  if 0
357   locale = setlocale (LC_CTYPE, NULL);
358 #  endif
359   if (locale == NULL || locale[0] == '\0')
360     {
361       locale = getenv ("LC_ALL");
362       if (locale == NULL || locale[0] == '\0')
363         {
364           locale = getenv ("LC_CTYPE");
365           if (locale == NULL || locale[0] == '\0')
366             locale = getenv ("LANG");
367         }
368     }
369
370   /* On some old systems, one used to set locale = "iso8859_1". On others,
371      you set it to "language_COUNTRY.charset". In any case, we resolve it
372      through the charset.alias file.  */
373   codeset = locale;
374
375 # endif
376
377 #elif defined WIN32_NATIVE
378
379   static char buf[2 + 10 + 1];
380
381   /* Woe32 has a function returning the locale's codepage as a number.  */
382   sprintf (buf, "CP%u", GetACP ());
383   codeset = buf;
384
385 #elif defined OS2
386
387   const char *locale;
388   static char buf[2 + 10 + 1];
389   ULONG cp[3];
390   ULONG cplen;
391
392   /* Allow user to override the codeset, as set in the operating system,
393      with standard language environment variables.  */
394   locale = getenv ("LC_ALL");
395   if (locale == NULL || locale[0] == '\0')
396     {
397       locale = getenv ("LC_CTYPE");
398       if (locale == NULL || locale[0] == '\0')
399         locale = getenv ("LANG");
400     }
401   if (locale != NULL && locale[0] != '\0')
402     {
403       /* If the locale name contains an encoding after the dot, return it.  */
404       const char *dot = strchr (locale, '.');
405
406       if (dot != NULL)
407         {
408           const char *modifier;
409
410           dot++;
411           /* Look for the possible @... trailer and remove it, if any.  */
412           modifier = strchr (dot, '@');
413           if (modifier == NULL)
414             return dot;
415           if (modifier - dot < sizeof (buf))
416             {
417               memcpy (buf, dot, modifier - dot);
418               buf [modifier - dot] = '\0';
419               return buf;
420             }
421         }
422
423       /* Resolve through the charset.alias file.  */
424       codeset = locale;
425     }
426   else
427     {
428       /* OS/2 has a function returning the locale's codepage as a number.  */
429       if (DosQueryCp (sizeof (cp), cp, &cplen))
430         codeset = "";
431       else
432         {
433           sprintf (buf, "CP%u", cp[0]);
434           codeset = buf;
435         }
436     }
437
438 #endif
439
440   if (codeset == NULL)
441     /* The canonical name cannot be determined.  */
442     codeset = "";
443
444   /* Resolve alias. */
445   for (aliases = get_charset_aliases ();
446        *aliases != '\0';
447        aliases += strlen (aliases) + 1, aliases += strlen (aliases) + 1)
448     if (strcmp (codeset, aliases) == 0
449         || (aliases[0] == '*' && aliases[1] == '\0'))
450       {
451         codeset = aliases + strlen (aliases) + 1;
452         break;
453       }
454
455   /* Don't return an empty string.  GNU libc and GNU libiconv interpret
456      the empty string as denoting "the locale's character encoding",
457      thus GNU libiconv would call this function a second time.  */
458   if (codeset[0] == '\0')
459     codeset = "ASCII";
460
461   return codeset;
462 }