a79c1f52e2975130949323788ca269a5c1257640
[platform/upstream/glibc.git] / intl / dcgettext.c
1 /* Implementation of the dcgettext(3) function.
2    Copyright (C) 1995, 1996, 1997, 1998 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)) internal_function;
172 static const char *category_to_name PARAMS ((int category)) internal_function;
173 static const char *guess_category_value PARAMS ((int category,
174                                                  const char *categoryname))
175      internal_function;
176
177
178 /* For those loosing systems which don't have `alloca' we have to add
179    some additional code emulating it.  */
180 #ifdef HAVE_ALLOCA
181 /* Nothing has to be done.  */
182 # define ADD_BLOCK(list, address) /* nothing */
183 # define FREE_BLOCKS(list) /* nothing */
184 #else
185 struct block_list
186 {
187   void *address;
188   struct block_list *next;
189 };
190 # define ADD_BLOCK(list, addr)                                                \
191   do {                                                                        \
192     struct block_list *newp = (struct block_list *) malloc (sizeof (*newp));  \
193     /* If we cannot get a free block we cannot add the new element to         \
194        the list.  */                                                          \
195     if (newp != NULL) {                                                       \
196       newp->address = (addr);                                                 \
197       newp->next = (list);                                                    \
198       (list) = newp;                                                          \
199     }                                                                         \
200   } while (0)
201 # define FREE_BLOCKS(list)                                                    \
202   do {                                                                        \
203     while (list != NULL) {                                                    \
204       struct block_list *old = list;                                          \
205       list = list->next;                                                      \
206       free (old);                                                             \
207     }                                                                         \
208   } while (0)
209 # undef alloca
210 # define alloca(size) (malloc (size))
211 #endif  /* have alloca */
212
213
214 /* Names for the libintl functions are a problem.  They must not clash
215    with existing names and they should follow ANSI C.  But this source
216    code is also used in GNU C Library where the names have a __
217    prefix.  So we have to make a difference here.  */
218 #ifdef _LIBC
219 # define DCGETTEXT __dcgettext
220 #else
221 # define DCGETTEXT dcgettext__
222 #endif
223
224 /* Look up MSGID in the DOMAINNAME message catalog for the current CATEGORY
225    locale.  */
226 char *
227 DCGETTEXT (domainname, msgid, category)
228      const char *domainname;
229      const char *msgid;
230      int category;
231 {
232 #ifndef HAVE_ALLOCA
233   struct block_list *block_list = NULL;
234 #endif
235   struct loaded_l10nfile *domain;
236   struct binding *binding;
237   const char *categoryname;
238   const char *categoryvalue;
239   char *dirname, *xdomainname;
240   char *single_locale;
241   char *retval;
242   int saved_errno = errno;
243
244   /* If no real MSGID is given return NULL.  */
245   if (msgid == NULL)
246     return NULL;
247
248   /* If DOMAINNAME is NULL, we are interested in the default domain.  If
249      CATEGORY is not LC_MESSAGES this might not make much sense but the
250      defintion left this undefined.  */
251   if (domainname == NULL)
252     domainname = _nl_current_default_domain;
253
254   /* First find matching binding.  */
255   for (binding = _nl_domain_bindings; binding != NULL; binding = binding->next)
256     {
257       int compare = strcmp (domainname, binding->domainname);
258       if (compare == 0)
259         /* We found it!  */
260         break;
261       if (compare < 0)
262         {
263           /* It is not in the list.  */
264           binding = NULL;
265           break;
266         }
267     }
268
269   if (binding == NULL)
270     dirname = (char *) _nl_default_dirname;
271   else if (binding->dirname[0] == '/')
272     dirname = binding->dirname;
273   else
274     {
275       /* We have a relative path.  Make it absolute now.  */
276       size_t dirname_len = strlen (binding->dirname) + 1;
277       size_t path_max;
278       char *ret;
279
280       path_max = (unsigned) PATH_MAX;
281       path_max += 2;            /* The getcwd docs say to do this.  */
282
283       dirname = (char *) alloca (path_max + dirname_len);
284       ADD_BLOCK (block_list, dirname);
285
286       __set_errno (0);
287       while ((ret = getcwd (dirname, path_max)) == NULL && errno == ERANGE)
288         {
289           path_max += PATH_INCR;
290           dirname = (char *) alloca (path_max + dirname_len);
291           ADD_BLOCK (block_list, dirname);
292           __set_errno (0);
293         }
294
295       if (ret == NULL)
296         {
297           /* We cannot get the current working directory.  Don't signal an
298              error but simply return the default string.  */
299           FREE_BLOCKS (block_list);
300           __set_errno (saved_errno);
301           return (char *) msgid;
302         }
303
304       stpcpy (stpcpy (strchr (dirname, '\0'), "/"), binding->dirname);
305     }
306
307   /* Now determine the symbolic name of CATEGORY and its value.  */
308   categoryname = category_to_name (category);
309   categoryvalue = guess_category_value (category, categoryname);
310
311   xdomainname = (char *) alloca (strlen (categoryname)
312                                  + strlen (domainname) + 5);
313   ADD_BLOCK (block_list, xdomainname);
314
315   stpcpy (stpcpy (stpcpy (stpcpy (xdomainname, categoryname), "/"),
316                   domainname),
317           ".mo");
318
319   /* Creating working area.  */
320   single_locale = (char *) alloca (strlen (categoryvalue) + 1);
321   ADD_BLOCK (block_list, single_locale);
322
323
324   /* Search for the given string.  This is a loop because we perhaps
325      got an ordered list of languages to consider for th translation.  */
326   while (1)
327     {
328       /* Make CATEGORYVALUE point to the next element of the list.  */
329       while (categoryvalue[0] != '\0' && categoryvalue[0] == ':')
330         ++categoryvalue;
331       if (categoryvalue[0] == '\0')
332         {
333           /* The whole contents of CATEGORYVALUE has been searched but
334              no valid entry has been found.  We solve this situation
335              by implicitly appending a "C" entry, i.e. no translation
336              will take place.  */
337           single_locale[0] = 'C';
338           single_locale[1] = '\0';
339         }
340       else
341         {
342           char *cp = single_locale;
343           while (categoryvalue[0] != '\0' && categoryvalue[0] != ':')
344             *cp++ = *categoryvalue++;
345           *cp = '\0';
346         }
347
348       /* If the current locale value is C (or POSIX) we don't load a
349          domain.  Return the MSGID.  */
350       if (strcmp (single_locale, "C") == 0
351           || strcmp (single_locale, "POSIX") == 0)
352         {
353           FREE_BLOCKS (block_list);
354           __set_errno (saved_errno);
355           return (char *) msgid;
356         }
357
358
359       /* Find structure describing the message catalog matching the
360          DOMAINNAME and CATEGORY.  */
361       domain = _nl_find_domain (dirname, single_locale, xdomainname);
362
363       if (domain != NULL)
364         {
365           retval = find_msg (domain, msgid);
366
367           if (retval == NULL)
368             {
369               int cnt;
370
371               for (cnt = 0; domain->successor[cnt] != NULL; ++cnt)
372                 {
373                   retval = find_msg (domain->successor[cnt], msgid);
374
375                   if (retval != NULL)
376                     break;
377                 }
378             }
379
380           if (retval != NULL)
381             {
382               FREE_BLOCKS (block_list);
383               __set_errno (saved_errno);
384               return retval;
385             }
386         }
387     }
388   /* NOTREACHED */
389 }
390
391 #ifdef _LIBC
392 /* Alias for function name in GNU C Library.  */
393 weak_alias (__dcgettext, dcgettext);
394 #endif
395
396
397 static char *
398 internal_function
399 find_msg (domain_file, msgid)
400      struct loaded_l10nfile *domain_file;
401      const char *msgid;
402 {
403   size_t top, act, bottom;
404   struct loaded_domain *domain;
405
406   if (domain_file->decided == 0)
407     _nl_load_domain (domain_file);
408
409   if (domain_file->data == NULL)
410     return NULL;
411
412   domain = (struct loaded_domain *) domain_file->data;
413
414   /* Locate the MSGID and its translation.  */
415   if (domain->hash_size > 2 && domain->hash_tab != NULL)
416     {
417       /* Use the hashing table.  */
418       nls_uint32 len = strlen (msgid);
419       nls_uint32 hash_val = hash_string (msgid);
420       nls_uint32 idx = hash_val % domain->hash_size;
421       nls_uint32 incr = 1 + (hash_val % (domain->hash_size - 2));
422       nls_uint32 nstr = W (domain->must_swap, domain->hash_tab[idx]);
423
424       if (nstr == 0)
425         /* Hash table entry is empty.  */
426         return NULL;
427
428       if (W (domain->must_swap, domain->orig_tab[nstr - 1].length) == len
429           && strcmp (msgid,
430                      domain->data + W (domain->must_swap,
431                                        domain->orig_tab[nstr - 1].offset)) == 0)
432         return (char *) domain->data + W (domain->must_swap,
433                                           domain->trans_tab[nstr - 1].offset);
434
435       while (1)
436         {
437           if (idx >= domain->hash_size - incr)
438             idx -= domain->hash_size - incr;
439           else
440             idx += incr;
441
442           nstr = W (domain->must_swap, domain->hash_tab[idx]);
443           if (nstr == 0)
444             /* Hash table entry is empty.  */
445             return NULL;
446
447           if (W (domain->must_swap, domain->orig_tab[nstr - 1].length) == len
448               && strcmp (msgid,
449                          domain->data + W (domain->must_swap,
450                                            domain->orig_tab[nstr - 1].offset))
451                  == 0)
452             return (char *) domain->data
453               + W (domain->must_swap, domain->trans_tab[nstr - 1].offset);
454         }
455       /* NOTREACHED */
456     }
457
458   /* Now we try the default method:  binary search in the sorted
459      array of messages.  */
460   bottom = 0;
461   top = domain->nstrings;
462   while (bottom < top)
463     {
464       int cmp_val;
465
466       act = (bottom + top) / 2;
467       cmp_val = strcmp (msgid, domain->data
468                                + W (domain->must_swap,
469                                     domain->orig_tab[act].offset));
470       if (cmp_val < 0)
471         top = act;
472       else if (cmp_val > 0)
473         bottom = act + 1;
474       else
475         break;
476     }
477
478   /* If an translation is found return this.  */
479   return bottom >= top ? NULL : (char *) domain->data
480                                 + W (domain->must_swap,
481                                      domain->trans_tab[act].offset);
482 }
483
484
485 /* Return string representation of locale CATEGORY.  */
486 static const char *
487 internal_function
488 category_to_name (category)
489      int category;
490 {
491   const char *retval;
492
493   switch (category)
494   {
495 #ifdef LC_COLLATE
496   case LC_COLLATE:
497     retval = "LC_COLLATE";
498     break;
499 #endif
500 #ifdef LC_CTYPE
501   case LC_CTYPE:
502     retval = "LC_CTYPE";
503     break;
504 #endif
505 #ifdef LC_MONETARY
506   case LC_MONETARY:
507     retval = "LC_MONETARY";
508     break;
509 #endif
510 #ifdef LC_NUMERIC
511   case LC_NUMERIC:
512     retval = "LC_NUMERIC";
513     break;
514 #endif
515 #ifdef LC_TIME
516   case LC_TIME:
517     retval = "LC_TIME";
518     break;
519 #endif
520 #ifdef LC_MESSAGES
521   case LC_MESSAGES:
522     retval = "LC_MESSAGES";
523     break;
524 #endif
525 #ifdef LC_RESPONSE
526   case LC_RESPONSE:
527     retval = "LC_RESPONSE";
528     break;
529 #endif
530 #ifdef LC_ALL
531   case LC_ALL:
532     /* This might not make sense but is perhaps better than any other
533        value.  */
534     retval = "LC_ALL";
535     break;
536 #endif
537   default:
538     /* If you have a better idea for a default value let me know.  */
539     retval = "LC_XXX";
540   }
541
542   return retval;
543 }
544
545 /* Guess value of current locale from value of the environment variables.  */
546 static const char *
547 internal_function
548 guess_category_value (category, categoryname)
549      int category;
550      const char *categoryname;
551 {
552   const char *retval;
553
554   /* The highest priority value is the `LANGUAGE' environment
555      variable.  This is a GNU extension.  */
556   retval = getenv ("LANGUAGE");
557   if (retval != NULL && retval[0] != '\0')
558     return retval;
559
560   /* `LANGUAGE' is not set.  So we have to proceed with the POSIX
561      methods of looking to `LC_ALL', `LC_xxx', and `LANG'.  On some
562      systems this can be done by the `setlocale' function itself.  */
563 #if defined HAVE_SETLOCALE && defined HAVE_LC_MESSAGES && defined HAVE_LOCALE_NULL
564   return setlocale (category, NULL);
565 #else
566   /* Setting of LC_ALL overwrites all other.  */
567   retval = getenv ("LC_ALL");
568   if (retval != NULL && retval[0] != '\0')
569     return retval;
570
571   /* Next comes the name of the desired category.  */
572   retval = getenv (categoryname);
573   if (retval != NULL && retval[0] != '\0')
574     return retval;
575
576   /* Last possibility is the LANG environment variable.  */
577   retval = getenv ("LANG");
578   if (retval != NULL && retval[0] != '\0')
579     return retval;
580
581   /* We use C as the default domain.  POSIX says this is implementation
582      defined.  */
583   return "C";
584 #endif
585 }
586
587 /* @@ begin of epilog @@ */
588
589 /* We don't want libintl.a to depend on any other library.  So we
590    avoid the non-standard function stpcpy.  In GNU C Library this
591    function is available, though.  Also allow the symbol HAVE_STPCPY
592    to be defined.  */
593 #if !_LIBC && !HAVE_STPCPY
594 static char *
595 stpcpy (dest, src)
596      char *dest;
597      const char *src;
598 {
599   while ((*dest++ = *src++) != '\0')
600     /* Do nothing. */ ;
601   return dest - 1;
602 }
603 #endif
604
605
606 #ifdef _LIBC
607 /* If we want to free all resources we have to do some work at
608    program's end.  */
609 static void __attribute__ ((unused))
610 free_mem (void)
611 {
612   struct binding *runp;
613
614   for (runp = _nl_domain_bindings; runp != NULL; runp = runp->next)
615     {
616       free (runp->domainname);
617       if (runp->dirname != _nl_default_dirname)
618         /* Yes, this is a pointer comparison.  */
619         free (runp->dirname);
620     }
621
622   if (_nl_current_default_domain != _nl_default_default_domain)
623     /* Yes, again a pointer comparison.  */
624     free ((char *) _nl_current_default_domain);
625 }
626
627 text_set_element (__libc_subfreeres, free_mem);
628 #endif