Update.
[platform/upstream/glibc.git] / intl / dcgettext.c
1 /* Implementation of the dcgettext(3) function.
2    Copyright (C) 1995, 1996, 1997 Free Software Foundation, Inc.
3
4    This file is part of the GNU C Library.  Its master source is NOT part of
5    the C library, however.
6
7    The GNU C Library is free software; you can redistribute it and/or
8    modify it under the terms of the GNU Library General Public License as
9    published by the Free Software Foundation; either version 2 of the
10    License, or (at your option) any later version.
11
12    The GNU C Library is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15    Library General Public License for more details.
16
17    You should have received a copy of the GNU Library General Public
18    License along with the GNU C Library; see the file COPYING.LIB.  If not,
19    write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20    Boston, MA 02111-1307, USA.  */
21
22 #ifdef HAVE_CONFIG_H
23 # include <config.h>
24 #endif
25
26 #include <sys/types.h>
27
28 #ifdef __GNUC__
29 # define alloca __builtin_alloca
30 # define HAVE_ALLOCA 1
31 #else
32 # if defined HAVE_ALLOCA_H || defined _LIBC
33 #  include <alloca.h>
34 # else
35 #  ifdef _AIX
36  #pragma alloca
37 #  else
38 #   ifndef alloca
39 char *alloca ();
40 #   endif
41 #  endif
42 # endif
43 #endif
44
45 #include <errno.h>
46 #ifndef errno
47 extern int errno;
48 #endif
49 #ifndef __set_errno
50 # define __set_errno(val) errno = (val)
51 #endif
52
53 #if defined STDC_HEADERS || defined _LIBC
54 # include <stdlib.h>
55 #else
56 char *getenv ();
57 # ifdef HAVE_MALLOC_H
58 #  include <malloc.h>
59 # else
60 void free ();
61 # endif
62 #endif
63
64 #if defined HAVE_STRING_H || defined _LIBC
65 # ifndef _GNU_SOURCE
66 #  define _GNU_SOURCE   1
67 # endif
68 # include <string.h>
69 #else
70 # include <strings.h>
71 #endif
72 #if !HAVE_STRCHR && !defined _LIBC
73 # ifndef strchr
74 #  define strchr index
75 # endif
76 #endif
77
78 #if defined HAVE_UNISTD_H || defined _LIBC
79 # include <unistd.h>
80 #endif
81
82 #include "gettext.h"
83 #include "gettextP.h"
84 #ifdef _LIBC
85 # include <libintl.h>
86 #else
87 # include "libgettext.h"
88 #endif
89 #include "hash-string.h"
90
91 /* @@ end of prolog @@ */
92
93 #ifdef _LIBC
94 /* Rename the non ANSI C functions.  This is required by the standard
95    because some ANSI C functions will require linking with this object
96    file and the name space must not be polluted.  */
97 # define getcwd __getcwd
98 # ifndef stpcpy
99 #  define stpcpy __stpcpy
100 # endif
101 #else
102 # if !defined HAVE_GETCWD
103 char *getwd ();
104 #  define getcwd(buf, max) getwd (buf)
105 # else
106 char *getcwd ();
107 # endif
108 # ifndef HAVE_STPCPY
109 static char *stpcpy PARAMS ((char *dest, const char *src));
110 # endif
111 #endif
112
113 /* Amount to increase buffer size by in each try.  */
114 #define PATH_INCR 32
115
116 /* The following is from pathmax.h.  */
117 /* Non-POSIX BSD systems might have gcc's limits.h, which doesn't define
118    PATH_MAX but might cause redefinition warnings when sys/param.h is
119    later included (as on MORE/BSD 4.3).  */
120 #if defined(_POSIX_VERSION) || (defined(HAVE_LIMITS_H) && !defined(__GNUC__))
121 # include <limits.h>
122 #endif
123
124 #ifndef _POSIX_PATH_MAX
125 # define _POSIX_PATH_MAX 255
126 #endif
127
128 #if !defined(PATH_MAX) && defined(_PC_PATH_MAX)
129 # define PATH_MAX (pathconf ("/", _PC_PATH_MAX) < 1 ? 1024 : pathconf ("/", _PC_PATH_MAX))
130 #endif
131
132 /* Don't include sys/param.h if it already has been.  */
133 #if defined(HAVE_SYS_PARAM_H) && !defined(PATH_MAX) && !defined(MAXPATHLEN)
134 # include <sys/param.h>
135 #endif
136
137 #if !defined(PATH_MAX) && defined(MAXPATHLEN)
138 # define PATH_MAX MAXPATHLEN
139 #endif
140
141 #ifndef PATH_MAX
142 # define PATH_MAX _POSIX_PATH_MAX
143 #endif
144
145 /* XPG3 defines the result of `setlocale (category, NULL)' as:
146    ``Directs `setlocale()' to query `category' and return the current
147      setting of `local'.''
148    However it does not specify the exact format.  And even worse: POSIX
149    defines this not at all.  So we can use this feature only on selected
150    system (e.g. those using GNU C Library).  */
151 #ifdef _LIBC
152 # define HAVE_LOCALE_NULL
153 #endif
154
155 /* Name of the default domain used for gettext(3) prior any call to
156    textdomain(3).  The default value for this is "messages".  */
157 const char _nl_default_default_domain[] = "messages";
158
159 /* Value used as the default domain for gettext(3).  */
160 const char *_nl_current_default_domain = _nl_default_default_domain;
161
162 /* Contains the default location of the message catalogs.  */
163 const char _nl_default_dirname[] = GNULOCALEDIR;
164
165 /* List with bindings of specific domains created by bindtextdomain()
166    calls.  */
167 struct binding *_nl_domain_bindings;
168
169 /* Prototypes for local functions.  */
170 static char *find_msg PARAMS ((struct loaded_l10nfile *domain_file,
171                                const char *msgid));
172 static const char *category_to_name PARAMS ((int category));
173 static const char *guess_category_value PARAMS ((int category,
174                                                  const char *categoryname));
175
176
177 /* For those loosing systems which don't have `alloca' we have to add
178    some additional code emulating it.  */
179 #ifdef HAVE_ALLOCA
180 /* Nothing has to be done.  */
181 # define ADD_BLOCK(list, address) /* nothing */
182 # define FREE_BLOCKS(list) /* nothing */
183 #else
184 struct block_list
185 {
186   void *address;
187   struct block_list *next;
188 };
189 # define ADD_BLOCK(list, addr)                                                \
190   do {                                                                        \
191     struct block_list *newp = (struct block_list *) malloc (sizeof (*newp));  \
192     /* If we cannot get a free block we cannot add the new element to         \
193        the list.  */                                                          \
194     if (newp != NULL) {                                                       \
195       newp->address = (addr);                                                 \
196       newp->next = (list);                                                    \
197       (list) = newp;                                                          \
198     }                                                                         \
199   } while (0)
200 # define FREE_BLOCKS(list)                                                    \
201   do {                                                                        \
202     while (list != NULL) {                                                    \
203       struct block_list *old = list;                                          \
204       list = list->next;                                                      \
205       free (old);                                                             \
206     }                                                                         \
207   } while (0)
208 # undef alloca
209 # define alloca(size) (malloc (size))
210 #endif  /* have alloca */
211
212
213 /* Names for the libintl functions are a problem.  They must not clash
214    with existing names and they should follow ANSI C.  But this source
215    code is also used in GNU C Library where the names have a __
216    prefix.  So we have to make a difference here.  */
217 #ifdef _LIBC
218 # define DCGETTEXT __dcgettext
219 #else
220 # define DCGETTEXT dcgettext__
221 #endif
222
223 /* Look up MSGID in the DOMAINNAME message catalog for the current CATEGORY
224    locale.  */
225 char *
226 DCGETTEXT (domainname, msgid, category)
227      const char *domainname;
228      const char *msgid;
229      int category;
230 {
231 #ifndef HAVE_ALLOCA
232   struct block_list *block_list = NULL;
233 #endif
234   struct loaded_l10nfile *domain;
235   struct binding *binding;
236   const char *categoryname;
237   const char *categoryvalue;
238   char *dirname, *xdomainname;
239   char *single_locale;
240   char *retval;
241   int saved_errno = errno;
242
243   /* If no real MSGID is given return NULL.  */
244   if (msgid == NULL)
245     return NULL;
246
247   /* If DOMAINNAME is NULL, we are interested in the default domain.  If
248      CATEGORY is not LC_MESSAGES this might not make much sense but the
249      defintion left this undefined.  */
250   if (domainname == NULL)
251     domainname = _nl_current_default_domain;
252
253   /* First find matching binding.  */
254   for (binding = _nl_domain_bindings; binding != NULL; binding = binding->next)
255     {
256       int compare = strcmp (domainname, binding->domainname);
257       if (compare == 0)
258         /* We found it!  */
259         break;
260       if (compare < 0)
261         {
262           /* It is not in the list.  */
263           binding = NULL;
264           break;
265         }
266     }
267
268   if (binding == NULL)
269     dirname = (char *) _nl_default_dirname;
270   else if (binding->dirname[0] == '/')
271     dirname = binding->dirname;
272   else
273     {
274       /* We have a relative path.  Make it absolute now.  */
275       size_t dirname_len = strlen (binding->dirname) + 1;
276       size_t path_max;
277       char *ret;
278
279       path_max = (unsigned) PATH_MAX;
280       path_max += 2;            /* The getcwd docs say to do this.  */
281
282       dirname = (char *) alloca (path_max + dirname_len);
283       ADD_BLOCK (block_list, dirname);
284
285       __set_errno (0);
286       while ((ret = getcwd (dirname, path_max)) == NULL && errno == ERANGE)
287         {
288           path_max += PATH_INCR;
289           dirname = (char *) alloca (path_max + dirname_len);
290           ADD_BLOCK (block_list, dirname);
291           __set_errno (0);
292         }
293
294       if (ret == NULL)
295         {
296           /* We cannot get the current working directory.  Don't signal an
297              error but simply return the default string.  */
298           FREE_BLOCKS (block_list);
299           __set_errno (saved_errno);
300           return (char *) msgid;
301         }
302
303       stpcpy (stpcpy (strchr (dirname, '\0'), "/"), binding->dirname);
304     }
305
306   /* Now determine the symbolic name of CATEGORY and its value.  */
307   categoryname = category_to_name (category);
308   categoryvalue = guess_category_value (category, categoryname);
309
310   xdomainname = (char *) alloca (strlen (categoryname)
311                                  + strlen (domainname) + 5);
312   ADD_BLOCK (block_list, xdomainname);
313
314   stpcpy (stpcpy (stpcpy (stpcpy (xdomainname, categoryname), "/"),
315                   domainname),
316           ".mo");
317
318   /* Creating working area.  */
319   single_locale = (char *) alloca (strlen (categoryvalue) + 1);
320   ADD_BLOCK (block_list, single_locale);
321
322
323   /* Search for the given string.  This is a loop because we perhaps
324      got an ordered list of languages to consider for th translation.  */
325   while (1)
326     {
327       /* Make CATEGORYVALUE point to the next element of the list.  */
328       while (categoryvalue[0] != '\0' && categoryvalue[0] == ':')
329         ++categoryvalue;
330       if (categoryvalue[0] == '\0')
331         {
332           /* The whole contents of CATEGORYVALUE has been searched but
333              no valid entry has been found.  We solve this situation
334              by implicitly appending a "C" entry, i.e. no translation
335              will take place.  */
336           single_locale[0] = 'C';
337           single_locale[1] = '\0';
338         }
339       else
340         {
341           char *cp = single_locale;
342           while (categoryvalue[0] != '\0' && categoryvalue[0] != ':')
343             *cp++ = *categoryvalue++;
344           *cp = '\0';
345         }
346
347       /* If the current locale value is C (or POSIX) we don't load a
348          domain.  Return the MSGID.  */
349       if (strcmp (single_locale, "C") == 0
350           || strcmp (single_locale, "POSIX") == 0)
351         {
352           FREE_BLOCKS (block_list);
353           __set_errno (saved_errno);
354           return (char *) msgid;
355         }
356
357
358       /* Find structure describing the message catalog matching the
359          DOMAINNAME and CATEGORY.  */
360       domain = _nl_find_domain (dirname, single_locale, xdomainname);
361
362       if (domain != NULL)
363         {
364           retval = find_msg (domain, msgid);
365
366           if (retval == NULL)
367             {
368               int cnt;
369
370               for (cnt = 0; domain->successor[cnt] != NULL; ++cnt)
371                 {
372                   retval = find_msg (domain->successor[cnt], msgid);
373
374                   if (retval != NULL)
375                     break;
376                 }
377             }
378
379           if (retval != NULL)
380             {
381               FREE_BLOCKS (block_list);
382               __set_errno (saved_errno);
383               return retval;
384             }
385         }
386     }
387   /* NOTREACHED */
388 }
389
390 #ifdef _LIBC
391 /* Alias for function name in GNU C Library.  */
392 weak_alias (__dcgettext, dcgettext);
393 #endif
394
395
396 static char *
397 find_msg (domain_file, msgid)
398      struct loaded_l10nfile *domain_file;
399      const char *msgid;
400 {
401   size_t top, act, bottom;
402   struct loaded_domain *domain;
403
404   if (domain_file->decided == 0)
405     _nl_load_domain (domain_file);
406
407   if (domain_file->data == NULL)
408     return NULL;
409
410   domain = (struct loaded_domain *) domain_file->data;
411
412   /* Locate the MSGID and its translation.  */
413   if (domain->hash_size > 2 && domain->hash_tab != NULL)
414     {
415       /* Use the hashing table.  */
416       nls_uint32 len = strlen (msgid);
417       nls_uint32 hash_val = hash_string (msgid);
418       nls_uint32 idx = hash_val % domain->hash_size;
419       nls_uint32 incr = 1 + (hash_val % (domain->hash_size - 2));
420       nls_uint32 nstr = W (domain->must_swap, domain->hash_tab[idx]);
421
422       if (nstr == 0)
423         /* Hash table entry is empty.  */
424         return NULL;
425
426       if (W (domain->must_swap, domain->orig_tab[nstr - 1].length) == len
427           && strcmp (msgid,
428                      domain->data + W (domain->must_swap,
429                                        domain->orig_tab[nstr - 1].offset)) == 0)
430         return (char *) domain->data + W (domain->must_swap,
431                                           domain->trans_tab[nstr - 1].offset);
432
433       while (1)
434         {
435           if (idx >= domain->hash_size - incr)
436             idx -= domain->hash_size - incr;
437           else
438             idx += incr;
439
440           nstr = W (domain->must_swap, domain->hash_tab[idx]);
441           if (nstr == 0)
442             /* Hash table entry is empty.  */
443             return NULL;
444
445           if (W (domain->must_swap, domain->orig_tab[nstr - 1].length) == len
446               && strcmp (msgid,
447                          domain->data + W (domain->must_swap,
448                                            domain->orig_tab[nstr - 1].offset))
449                  == 0)
450             return (char *) domain->data
451               + W (domain->must_swap, domain->trans_tab[nstr - 1].offset);
452         }
453       /* NOTREACHED */
454     }
455
456   /* Now we try the default method:  binary search in the sorted
457      array of messages.  */
458   bottom = 0;
459   top = domain->nstrings;
460   while (bottom < top)
461     {
462       int cmp_val;
463
464       act = (bottom + top) / 2;
465       cmp_val = strcmp (msgid, domain->data
466                                + W (domain->must_swap,
467                                     domain->orig_tab[act].offset));
468       if (cmp_val < 0)
469         top = act;
470       else if (cmp_val > 0)
471         bottom = act + 1;
472       else
473         break;
474     }
475
476   /* If an translation is found return this.  */
477   return bottom >= top ? NULL : (char *) domain->data
478                                 + W (domain->must_swap,
479                                      domain->trans_tab[act].offset);
480 }
481
482
483 /* Return string representation of locale CATEGORY.  */
484 static const char *
485 category_to_name (category)
486      int category;
487 {
488   const char *retval;
489
490   switch (category)
491   {
492 #ifdef LC_COLLATE
493   case LC_COLLATE:
494     retval = "LC_COLLATE";
495     break;
496 #endif
497 #ifdef LC_CTYPE
498   case LC_CTYPE:
499     retval = "LC_CTYPE";
500     break;
501 #endif
502 #ifdef LC_MONETARY
503   case LC_MONETARY:
504     retval = "LC_MONETARY";
505     break;
506 #endif
507 #ifdef LC_NUMERIC
508   case LC_NUMERIC:
509     retval = "LC_NUMERIC";
510     break;
511 #endif
512 #ifdef LC_TIME
513   case LC_TIME:
514     retval = "LC_TIME";
515     break;
516 #endif
517 #ifdef LC_MESSAGES
518   case LC_MESSAGES:
519     retval = "LC_MESSAGES";
520     break;
521 #endif
522 #ifdef LC_RESPONSE
523   case LC_RESPONSE:
524     retval = "LC_RESPONSE";
525     break;
526 #endif
527 #ifdef LC_ALL
528   case LC_ALL:
529     /* This might not make sense but is perhaps better than any other
530        value.  */
531     retval = "LC_ALL";
532     break;
533 #endif
534   default:
535     /* If you have a better idea for a default value let me know.  */
536     retval = "LC_XXX";
537   }
538
539   return retval;
540 }
541
542 /* Guess value of current locale from value of the environment variables.  */
543 static const char *
544 guess_category_value (category, categoryname)
545      int category;
546      const char *categoryname;
547 {
548   const char *retval;
549
550   /* The highest priority value is the `LANGUAGE' environment
551      variable.  This is a GNU extension.  */
552   retval = getenv ("LANGUAGE");
553   if (retval != NULL && retval[0] != '\0')
554     return retval;
555
556   /* `LANGUAGE' is not set.  So we have to proceed with the POSIX
557      methods of looking to `LC_ALL', `LC_xxx', and `LANG'.  On some
558      systems this can be done by the `setlocale' function itself.  */
559 #if defined HAVE_SETLOCALE && defined HAVE_LC_MESSAGES && defined HAVE_LOCALE_NULL
560   return setlocale (category, NULL);
561 #else
562   /* Setting of LC_ALL overwrites all other.  */
563   retval = getenv ("LC_ALL");
564   if (retval != NULL && retval[0] != '\0')
565     return retval;
566
567   /* Next comes the name of the desired category.  */
568   retval = getenv (categoryname);
569   if (retval != NULL && retval[0] != '\0')
570     return retval;
571
572   /* Last possibility is the LANG environment variable.  */
573   retval = getenv ("LANG");
574   if (retval != NULL && retval[0] != '\0')
575     return retval;
576
577   /* We use C as the default domain.  POSIX says this is implementation
578      defined.  */
579   return "C";
580 #endif
581 }
582
583 /* @@ begin of epilog @@ */
584
585 /* We don't want libintl.a to depend on any other library.  So we
586    avoid the non-standard function stpcpy.  In GNU C Library this
587    function is available, though.  Also allow the symbol HAVE_STPCPY
588    to be defined.  */
589 #if !_LIBC && !HAVE_STPCPY
590 static char *
591 stpcpy (dest, src)
592      char *dest;
593      const char *src;
594 {
595   while ((*dest++ = *src++) != '\0')
596     /* Do nothing. */ ;
597   return dest - 1;
598 }
599 #endif
600
601
602 #ifdef _LIBC
603 /* If we want to free all resources we have to do some work at
604    program's end.  */
605 static void __attribute__ ((unused))
606 free_mem (void)
607 {
608   struct binding *runp;
609
610   for (runp = _nl_domain_bindings; runp != NULL; runp = runp->next)
611     {
612       free (runp->domainname);
613       if (runp->dirname != _nl_default_dirname)
614         /* Yes, this is a pointer comparison.  */
615         free (runp->dirname);
616     }
617
618   if (_nl_current_default_domain != _nl_default_default_domain)
619     /* Yes, again a pointer comparison.  */
620     free ((char *) _nl_current_default_domain);
621 }
622
623 text_set_element (__libc_subfreeres, free_mem);
624 #endif