1 /* Implementation of the internal dcigettext function.
2    Copyright (C) 1995-1999, 2000-2010, 2012 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 Lesser General Public License as published by
6    the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
13 
14    You should have received a copy of the GNU Lesser General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16 
17 /* Tell glibc's <string.h> to provide a prototype for mempcpy().
18    This must come before <config.h> because <config.h> may include
19    <features.h>, and once <features.h> has been included, it's too late.  */
20 #ifndef _GNU_SOURCE
21 # define _GNU_SOURCE	1
22 #endif
23 
24 #ifdef HAVE_CONFIG_H
25 # include <config.h>
26 #endif
27 
28 #include <sys/types.h>
29 
30 #ifdef __GNUC__
31 # define alloca __builtin_alloca
32 # define HAVE_ALLOCA 1
33 #else
34 # ifdef _MSC_VER
35 #  include <malloc.h>
36 #  define alloca _alloca
37 # else
38 #  if defined HAVE_ALLOCA_H || defined _LIBC
39 #   include <alloca.h>
40 #  else
41 #   ifdef _AIX
42  #pragma alloca
43 #   else
44 #    ifndef alloca
45 char *alloca ();
46 #    endif
47 #   endif
48 #  endif
49 # endif
50 #endif
51 
52 #include <errno.h>
53 #ifndef errno
54 extern int errno;
55 #endif
56 #ifndef __set_errno
57 # define __set_errno(val) errno = (val)
58 #endif
59 
60 #include <stddef.h>
61 #include <stdlib.h>
62 #include <string.h>
63 
64 #if defined HAVE_UNISTD_H || defined _LIBC
65 # include <unistd.h>
66 #endif
67 
68 #include <locale.h>
69 
70 #ifdef _LIBC
71   /* Guess whether integer division by zero raises signal SIGFPE.
72      Set to 1 only if you know for sure.  In case of doubt, set to 0.  */
73 # if defined __alpha__ || defined __arm__ || defined __i386__ \
74      || defined __m68k__ || defined __s390__
75 #  define INTDIV0_RAISES_SIGFPE 1
76 # else
77 #  define INTDIV0_RAISES_SIGFPE 0
78 # endif
79 #endif
80 #if !INTDIV0_RAISES_SIGFPE
81 # include <signal.h>
82 #endif
83 
84 #if defined HAVE_SYS_PARAM_H || defined _LIBC
85 # include <sys/param.h>
86 #endif
87 
88 #if !defined _LIBC
89 # include "localcharset.h"
90 #endif
91 
92 #include "gettextP.h"
93 #include "plural-exp.h"
94 #ifdef _LIBC
95 # include <libintl.h>
96 #else
97 # ifdef IN_LIBGLOCALE
98 #  include <libintl.h>
99 # endif
100 # include "libgnuintl.h"
101 #endif
102 #include "hash-string.h"
103 
104 /* Handle multi-threaded applications.  */
105 #ifdef _LIBC
106 # include <bits/libc-lock.h>
107 # define gl_rwlock_define_initialized __libc_rwlock_define_initialized
108 # define gl_rwlock_rdlock __libc_rwlock_rdlock
109 # define gl_rwlock_wrlock __libc_rwlock_wrlock
110 # define gl_rwlock_unlock __libc_rwlock_unlock
111 #else
112 # include "lock.h"
113 #endif
114 
115 /* Alignment of types.  */
116 #if defined __GNUC__ && __GNUC__ >= 2
117 # define alignof(TYPE) __alignof__ (TYPE)
118 #else
119 # define alignof(TYPE) \
120     ((int) &((struct { char dummy1; TYPE dummy2; } *) 0)->dummy2)
121 #endif
122 
123 /* Some compilers, like SunOS4 cc, don't have offsetof in <stddef.h>.  */
124 #ifndef offsetof
125 # define offsetof(type,ident) ((size_t)&(((type*)0)->ident))
126 #endif
127 
128 /* @@ end of prolog @@ */
129 
130 #ifdef _LIBC
131 /* Rename the non ANSI C functions.  This is required by the standard
132    because some ANSI C functions will require linking with this object
133    file and the name space must not be polluted.  */
134 # define getcwd __getcwd
135 # ifndef stpcpy
136 #  define stpcpy __stpcpy
137 # endif
138 # define tfind __tfind
139 #else
140 # if !defined HAVE_GETCWD
141 char *getwd ();
142 #  define getcwd(buf, max) getwd (buf)
143 # else
144 #  if VMS
145 #   define getcwd(buf, max) (getcwd) (buf, max, 0)
146 #  else
147 char *getcwd ();
148 #  endif
149 # endif
150 # ifndef HAVE_STPCPY
151 static char *stpcpy (char *dest, const char *src);
152 # endif
153 # ifndef HAVE_MEMPCPY
154 static void *mempcpy (void *dest, const void *src, size_t n);
155 # endif
156 #endif
157 
158 /* Use a replacement if the system does not provide the `tsearch' function
159    family.  */
160 #if HAVE_TSEARCH || defined _LIBC
161 # include <search.h>
162 #else
163 # define tsearch libintl_tsearch
164 # define tfind libintl_tfind
165 # define tdelete libintl_tdelete
166 # define twalk libintl_twalk
167 # include "tsearch.h"
168 #endif
169 
170 #ifdef _LIBC
171 # define tsearch __tsearch
172 #endif
173 
174 /* Amount to increase buffer size by in each try.  */
175 #define PATH_INCR 32
176 
177 /* The following is from pathmax.h.  */
178 /* Non-POSIX BSD systems might have gcc's limits.h, which doesn't define
179    PATH_MAX but might cause redefinition warnings when sys/param.h is
180    later included (as on MORE/BSD 4.3).  */
181 #if defined _POSIX_VERSION || (defined HAVE_LIMITS_H && !defined __GNUC__)
182 # include <limits.h>
183 #endif
184 
185 #ifndef _POSIX_PATH_MAX
186 # define _POSIX_PATH_MAX 255
187 #endif
188 
189 #if !defined PATH_MAX && defined _PC_PATH_MAX
190 # define PATH_MAX (pathconf ("/", _PC_PATH_MAX) < 1 ? 1024 : pathconf ("/", _PC_PATH_MAX))
191 #endif
192 
193 /* Don't include sys/param.h if it already has been.  */
194 #if defined HAVE_SYS_PARAM_H && !defined PATH_MAX && !defined MAXPATHLEN
195 # include <sys/param.h>
196 #endif
197 
198 #if !defined PATH_MAX && defined MAXPATHLEN
199 # define PATH_MAX MAXPATHLEN
200 #endif
201 
202 #ifndef PATH_MAX
203 # define PATH_MAX _POSIX_PATH_MAX
204 #endif
205 
206 /* Pathname support.
207    ISSLASH(C)           tests whether C is a directory separator character.
208    IS_ABSOLUTE_PATH(P)  tests whether P is an absolute path.  If it is not,
209                         it may be concatenated to a directory pathname.
210    IS_PATH_WITH_DIR(P)  tests whether P contains a directory specification.
211  */
212 #if defined _WIN32 || defined __WIN32__ || defined __CYGWIN__ || defined __EMX__ || defined __DJGPP__
213   /* Win32, Cygwin, OS/2, DOS */
214 # define ISSLASH(C) ((C) == '/' || (C) == '\\')
215 # define HAS_DEVICE(P) \
216     ((((P)[0] >= 'A' && (P)[0] <= 'Z') || ((P)[0] >= 'a' && (P)[0] <= 'z')) \
217      && (P)[1] == ':')
218 # define IS_ABSOLUTE_PATH(P) (ISSLASH ((P)[0]) || HAS_DEVICE (P))
219 # define IS_PATH_WITH_DIR(P) \
220     (strchr (P, '/') != NULL || strchr (P, '\\') != NULL || HAS_DEVICE (P))
221 #else
222   /* Unix */
223 # define ISSLASH(C) ((C) == '/')
224 # define IS_ABSOLUTE_PATH(P) ISSLASH ((P)[0])
225 # define IS_PATH_WITH_DIR(P) (strchr (P, '/') != NULL)
226 #endif
227 
228 /* Whether to support different locales in different threads.  */
229 #if defined _LIBC || HAVE_USELOCALE || defined IN_LIBGLOCALE
230 # define HAVE_PER_THREAD_LOCALE
231 #endif
232 
233 /* This is the type used for the search tree where known translations
234    are stored.  */
235 struct known_translation_t
236 {
237   /* Domain in which to search.  */
238   const char *domainname;
239 
240   /* The category.  */
241   int category;
242 
243 #ifdef HAVE_PER_THREAD_LOCALE
244   /* Name of the relevant locale category, or "" for the global locale.  */
245   const char *localename;
246 #endif
247 
248 #ifdef IN_LIBGLOCALE
249   /* The character encoding.  */
250   const char *encoding;
251 #endif
252 
253   /* State of the catalog counter at the point the string was found.  */
254   int counter;
255 
256   /* Catalog where the string was found.  */
257   struct loaded_l10nfile *domain;
258 
259   /* And finally the translation.  */
260   const char *translation;
261   size_t translation_length;
262 
263   /* Pointer to the string in question.  */
264   union
265     {
266       char appended[ZERO];  /* used if domain != NULL */
267       const char *ptr;      /* used if domain == NULL */
268     }
269   msgid;
270 };
271 
272 gl_rwlock_define_initialized (static, tree_lock)
273 
274 /* Root of the search tree with known translations.  */
275 static void *root;
276 
277 /* Function to compare two entries in the table of known translations.  */
278 static int
transcmp(const void * p1,const void * p2)279 transcmp (const void *p1, const void *p2)
280 {
281   const struct known_translation_t *s1;
282   const struct known_translation_t *s2;
283   int result;
284 
285   s1 = (const struct known_translation_t *) p1;
286   s2 = (const struct known_translation_t *) p2;
287 
288   result = strcmp (s1->domain != NULL ? s1->msgid.appended : s1->msgid.ptr,
289 		   s2->domain != NULL ? s2->msgid.appended : s2->msgid.ptr);
290   if (result == 0)
291     {
292       result = strcmp (s1->domainname, s2->domainname);
293       if (result == 0)
294 	{
295 #ifdef HAVE_PER_THREAD_LOCALE
296 	  result = strcmp (s1->localename, s2->localename);
297 	  if (result == 0)
298 #endif
299 	    {
300 #ifdef IN_LIBGLOCALE
301 	      result = strcmp (s1->encoding, s2->encoding);
302 	      if (result == 0)
303 #endif
304 		/* We compare the category last (though this is the cheapest
305 		   operation) since it is hopefully always the same (namely
306 		   LC_MESSAGES).  */
307 		result = s1->category - s2->category;
308 	    }
309 	}
310     }
311 
312   return result;
313 }
314 
315 /* Name of the default domain used for gettext(3) prior any call to
316    textdomain(3).  The default value for this is "messages".  */
317 const char _nl_default_default_domain[] attribute_hidden = "messages";
318 
319 #ifndef IN_LIBGLOCALE
320 /* Value used as the default domain for gettext(3).  */
321 const char *_nl_current_default_domain attribute_hidden
322      = _nl_default_default_domain;
323 #endif
324 
325 /* Contains the default location of the message catalogs.  */
326 #if defined __EMX__
327 extern const char _nl_default_dirname[];
328 #else
329 # ifdef _LIBC
330 extern const char _nl_default_dirname[];
331 libc_hidden_proto (_nl_default_dirname)
332 # endif
333 const char _nl_default_dirname[] = LOCALEDIR;
334 # ifdef _LIBC
335 libc_hidden_data_def (_nl_default_dirname)
336 # endif
337 #endif
338 
339 #ifndef IN_LIBGLOCALE
340 /* List with bindings of specific domains created by bindtextdomain()
341    calls.  */
342 struct binding *_nl_domain_bindings;
343 #endif
344 
345 /* Prototypes for local functions.  */
346 static char *plural_lookup (struct loaded_l10nfile *domain,
347 			    unsigned long int n,
348 			    const char *translation, size_t translation_len)
349      internal_function;
350 
351 #ifdef IN_LIBGLOCALE
352 static const char *guess_category_value (int category,
353 					 const char *categoryname,
354 					 const char *localename)
355      internal_function;
356 #else
357 static const char *guess_category_value (int category,
358 					 const char *categoryname)
359      internal_function;
360 #endif
361 
362 #ifdef _LIBC
363 # include "../locale/localeinfo.h"
364 # define category_to_name(category) \
365   _nl_category_names.str + _nl_category_name_idxs[category]
366 #else
367 static const char *category_to_name (int category) internal_function;
368 #endif
369 #if (defined _LIBC || HAVE_ICONV) && !defined IN_LIBGLOCALE
370 static const char *get_output_charset (struct binding *domainbinding)
371      internal_function;
372 #endif
373 
374 
375 /* For those losing systems which don't have `alloca' we have to add
376    some additional code emulating it.  */
377 #ifdef HAVE_ALLOCA
378 /* Nothing has to be done.  */
379 # define freea(p) /* nothing */
380 # define ADD_BLOCK(list, address) /* nothing */
381 # define FREE_BLOCKS(list) /* nothing */
382 #else
383 struct block_list
384 {
385   void *address;
386   struct block_list *next;
387 };
388 # define ADD_BLOCK(list, addr)						      \
389   do {									      \
390     struct block_list *newp = (struct block_list *) malloc (sizeof (*newp));  \
391     /* If we cannot get a free block we cannot add the new element to	      \
392        the list.  */							      \
393     if (newp != NULL) {							      \
394       newp->address = (addr);						      \
395       newp->next = (list);						      \
396       (list) = newp;							      \
397     }									      \
398   } while (0)
399 # define FREE_BLOCKS(list)						      \
400   do {									      \
401     while (list != NULL) {						      \
402       struct block_list *old = list;					      \
403       list = list->next;						      \
404       free (old->address);						      \
405       free (old);							      \
406     }									      \
407   } while (0)
408 # undef alloca
409 # define alloca(size) (malloc (size))
410 # define freea(p) free (p)
411 #endif	/* have alloca */
412 
413 
414 #ifdef _LIBC
415 /* List of blocks allocated for translations.  */
416 typedef struct transmem_list
417 {
418   struct transmem_list *next;
419   char data[ZERO];
420 } transmem_block_t;
421 static struct transmem_list *transmem_list;
422 #else
423 typedef unsigned char transmem_block_t;
424 #endif
425 
426 
427 /* Names for the libintl functions are a problem.  They must not clash
428    with existing names and they should follow ANSI C.  But this source
429    code is also used in GNU C Library where the names have a __
430    prefix.  So we have to make a difference here.  */
431 #ifdef _LIBC
432 # define DCIGETTEXT __dcigettext
433 #else
434 # define DCIGETTEXT libintl_dcigettext
435 #endif
436 
437 /* Lock variable to protect the global data in the gettext implementation.  */
438 gl_rwlock_define_initialized (, _nl_state_lock attribute_hidden)
439 
440 /* Checking whether the binaries runs SUID must be done and glibc provides
441    easier methods therefore we make a difference here.  */
442 #ifdef _LIBC
443 # define ENABLE_SECURE __libc_enable_secure
444 # define DETERMINE_SECURE
445 #else
446 # ifndef HAVE_GETUID
447 #  define getuid() 0
448 # endif
449 # ifndef HAVE_GETGID
450 #  define getgid() 0
451 # endif
452 # ifndef HAVE_GETEUID
453 #  define geteuid() getuid()
454 # endif
455 # ifndef HAVE_GETEGID
456 #  define getegid() getgid()
457 # endif
458 static int enable_secure;
459 # define ENABLE_SECURE (enable_secure == 1)
460 # define DETERMINE_SECURE \
461   if (enable_secure == 0)						      \
462     {									      \
463       if (getuid () != geteuid () || getgid () != getegid ())		      \
464 	enable_secure = 1;						      \
465       else								      \
466 	enable_secure = -1;						      \
467     }
468 #endif
469 
470 /* Get the function to evaluate the plural expression.  */
471 #include "eval-plural.h"
472 
473 /* Look up MSGID in the DOMAINNAME message catalog for the current
474    CATEGORY locale and, if PLURAL is nonzero, search over string
475    depending on the plural form determined by N.  */
476 #ifdef IN_LIBGLOCALE
477 char *
gl_dcigettext(const char * domainname,const char * msgid1,const char * msgid2,int plural,unsigned long int n,int category,const char * localename,const char * encoding)478 gl_dcigettext (const char *domainname,
479 	       const char *msgid1, const char *msgid2,
480 	       int plural, unsigned long int n,
481 	       int category,
482 	       const char *localename, const char *encoding)
483 #else
484 char *
485 DCIGETTEXT (const char *domainname, const char *msgid1, const char *msgid2,
486 	    int plural, unsigned long int n, int category)
487 #endif
488 {
489 #ifndef HAVE_ALLOCA
490   struct block_list *block_list = NULL;
491 #endif
492   struct loaded_l10nfile *domain;
493   struct binding *binding;
494   const char *categoryname;
495   const char *categoryvalue;
496   const char *dirname;
497   char *xdomainname;
498   char *single_locale;
499   char *retval;
500   size_t retlen;
501   int saved_errno;
502   struct known_translation_t search;
503   struct known_translation_t **foundp = NULL;
504 #if defined HAVE_PER_THREAD_LOCALE && !defined IN_LIBGLOCALE
505   const char *localename;
506 #endif
507   size_t domainname_len;
508 
509   /* If no real MSGID is given return NULL.  */
510   if (msgid1 == NULL)
511     return NULL;
512 
513 #ifdef _LIBC
514   if (category < 0 || category >= __LC_LAST || category == LC_ALL)
515     /* Bogus.  */
516     return (plural == 0
517 	    ? (char *) msgid1
518 	    /* Use the Germanic plural rule.  */
519 	    : n == 1 ? (char *) msgid1 : (char *) msgid2);
520 #endif
521 
522   /* Preserve the `errno' value.  */
523   saved_errno = errno;
524 
525 #ifdef _LIBC
526   __libc_rwlock_define (extern, __libc_setlocale_lock attribute_hidden)
527   __libc_rwlock_rdlock (__libc_setlocale_lock);
528 #endif
529 
530   gl_rwlock_rdlock (_nl_state_lock);
531 
532   /* If DOMAINNAME is NULL, we are interested in the default domain.  If
533      CATEGORY is not LC_MESSAGES this might not make much sense but the
534      definition left this undefined.  */
535   if (domainname == NULL)
536     domainname = _nl_current_default_domain;
537 
538   /* OS/2 specific: backward compatibility with older libintl versions  */
539 #ifdef LC_MESSAGES_COMPAT
540   if (category == LC_MESSAGES_COMPAT)
541     category = LC_MESSAGES;
542 #endif
543 
544   /* Try to find the translation among those which we found at
545      some time.  */
546   search.domain = NULL;
547   search.msgid.ptr = msgid1;
548   search.domainname = domainname;
549   search.category = category;
550 #ifdef HAVE_PER_THREAD_LOCALE
551 # ifndef IN_LIBGLOCALE
552 #  ifdef _LIBC
553   localename = _strdupa (_current_locale_name (category));
554 #  else
555   categoryname = category_to_name (category);
556 #   define CATEGORYNAME_INITIALIZED
557   localename = _nl_locale_name_thread_unsafe (category, categoryname);
558   if (localename == NULL)
559     localename = "";
560 #  endif
561 # endif
562   search.localename = localename;
563 # ifdef IN_LIBGLOCALE
564   search.encoding = encoding;
565 # endif
566 
567   /* Since tfind/tsearch manage a balanced tree, concurrent tfind and
568      tsearch calls can be fatal.  */
569   gl_rwlock_rdlock (tree_lock);
570 
571   foundp = (struct known_translation_t **) tfind (&search, &root, transcmp);
572 
573   gl_rwlock_unlock (tree_lock);
574 
575   if (foundp != NULL && (*foundp)->counter == _nl_msg_cat_cntr)
576     {
577       /* Now deal with plural.  */
578       if (plural)
579 	retval = plural_lookup ((*foundp)->domain, n, (*foundp)->translation,
580 				(*foundp)->translation_length);
581       else
582 	retval = (char *) (*foundp)->translation;
583 
584       gl_rwlock_unlock (_nl_state_lock);
585 # ifdef _LIBC
586       __libc_rwlock_unlock (__libc_setlocale_lock);
587 # endif
588       __set_errno (saved_errno);
589       return retval;
590     }
591 #endif
592 
593   /* See whether this is a SUID binary or not.  */
594   DETERMINE_SECURE;
595 
596   /* First find matching binding.  */
597 #ifdef IN_LIBGLOCALE
598   /* We can use a trivial binding, since _nl_find_msg will ignore it anyway,
599      and _nl_load_domain and _nl_find_domain just pass it through.  */
600   binding = NULL;
601   dirname = bindtextdomain (domainname, NULL);
602 #else
603   for (binding = _nl_domain_bindings; binding != NULL; binding = binding->next)
604     {
605       int compare = strcmp (domainname, binding->domainname);
606       if (compare == 0)
607 	/* We found it!  */
608 	break;
609       if (compare < 0)
610 	{
611 	  /* It is not in the list.  */
612 	  binding = NULL;
613 	  break;
614 	}
615     }
616 
617   if (binding == NULL)
618     dirname = _nl_default_dirname;
619   else
620     {
621       dirname = binding->dirname;
622 #endif
623       if (!IS_ABSOLUTE_PATH (dirname))
624 	{
625 	  /* We have a relative path.  Make it absolute now.  */
626 	  size_t dirname_len = strlen (dirname) + 1;
627 	  size_t path_max;
628 	  char *resolved_dirname;
629 	  char *ret;
630 
631 	  path_max = (unsigned int) PATH_MAX;
632 	  path_max += 2;		/* The getcwd docs say to do this.  */
633 
634 	  for (;;)
635 	    {
636 	      resolved_dirname = (char *) alloca (path_max + dirname_len);
637 	      ADD_BLOCK (block_list, tmp_dirname);
638 
639 	      __set_errno (0);
640 	      ret = getcwd (resolved_dirname, path_max);
641 	      if (ret != NULL || errno != ERANGE)
642 		break;
643 
644 	      path_max += path_max / 2;
645 	      path_max += PATH_INCR;
646 	    }
647 
648 	  if (ret == NULL)
649 	    /* We cannot get the current working directory.  Don't signal an
650 	       error but simply return the default string.  */
651 	    goto return_untranslated;
652 
653 	  stpcpy (stpcpy (strchr (resolved_dirname, '\0'), "/"), dirname);
654 	  dirname = resolved_dirname;
655 	}
656 #ifndef IN_LIBGLOCALE
657     }
658 #endif
659 
660   /* Now determine the symbolic name of CATEGORY and its value.  */
661 #ifndef CATEGORYNAME_INITIALIZED
662   categoryname = category_to_name (category);
663 #endif
664 #ifdef IN_LIBGLOCALE
665   categoryvalue = guess_category_value (category, categoryname, localename);
666 #else
667   categoryvalue = guess_category_value (category, categoryname);
668 #endif
669 
670   domainname_len = strlen (domainname);
671   xdomainname = (char *) alloca (strlen (categoryname)
672 				 + domainname_len + 5);
673   ADD_BLOCK (block_list, xdomainname);
674 
675   stpcpy ((char *) mempcpy (stpcpy (stpcpy (xdomainname, categoryname), "/"),
676 			    domainname, domainname_len),
677 	  ".mo");
678 
679   /* Creating working area.  */
680   single_locale = (char *) alloca (strlen (categoryvalue) + 1);
681   ADD_BLOCK (block_list, single_locale);
682 
683 
684   /* Search for the given string.  This is a loop because we perhaps
685      got an ordered list of languages to consider for the translation.  */
686   while (1)
687     {
688       /* Make CATEGORYVALUE point to the next element of the list.  */
689       while (categoryvalue[0] != '\0' && categoryvalue[0] == ':')
690 	++categoryvalue;
691       if (categoryvalue[0] == '\0')
692 	{
693 	  /* The whole contents of CATEGORYVALUE has been searched but
694 	     no valid entry has been found.  We solve this situation
695 	     by implicitly appending a "C" entry, i.e. no translation
696 	     will take place.  */
697 	  single_locale[0] = 'C';
698 	  single_locale[1] = '\0';
699 	}
700       else
701 	{
702 	  char *cp = single_locale;
703 	  while (categoryvalue[0] != '\0' && categoryvalue[0] != ':')
704 	    *cp++ = *categoryvalue++;
705 	  *cp = '\0';
706 
707 	  /* When this is a SUID binary we must not allow accessing files
708 	     outside the dedicated directories.  */
709 	  if (ENABLE_SECURE && IS_PATH_WITH_DIR (single_locale))
710 	    /* Ingore this entry.  */
711 	    continue;
712 	}
713 
714       /* If the current locale value is C (or POSIX) we don't load a
715 	 domain.  Return the MSGID.  */
716       if (strcmp (single_locale, "C") == 0
717 	  || strcmp (single_locale, "POSIX") == 0)
718 	break;
719 
720       /* Find structure describing the message catalog matching the
721 	 DOMAINNAME and CATEGORY.  */
722       domain = _nl_find_domain (dirname, single_locale, xdomainname, binding);
723 
724       if (domain != NULL)
725 	{
726 #if defined IN_LIBGLOCALE
727 	  retval = _nl_find_msg (domain, binding, encoding, msgid1, &retlen);
728 #else
729 	  retval = _nl_find_msg (domain, binding, msgid1, 1, &retlen);
730 #endif
731 
732 	  if (retval == NULL)
733 	    {
734 	      int cnt;
735 
736 	      for (cnt = 0; domain->successor[cnt] != NULL; ++cnt)
737 		{
738 #if defined IN_LIBGLOCALE
739 		  retval = _nl_find_msg (domain->successor[cnt], binding,
740 					 encoding, msgid1, &retlen);
741 #else
742 		  retval = _nl_find_msg (domain->successor[cnt], binding,
743 					 msgid1, 1, &retlen);
744 #endif
745 
746 		  /* Resource problems are not fatal, instead we return no
747 		     translation.  */
748 		  if (__builtin_expect (retval == (char *) -1, 0))
749 		    goto return_untranslated;
750 
751 		  if (retval != NULL)
752 		    {
753 		      domain = domain->successor[cnt];
754 		      break;
755 		    }
756 		}
757 	    }
758 
759 	  /* Returning -1 means that some resource problem exists
760 	     (likely memory) and that the strings could not be
761 	     converted.  Return the original strings.  */
762 	  if (__builtin_expect (retval == (char *) -1, 0))
763 	    break;
764 
765 	  if (retval != NULL)
766 	    {
767 	      /* Found the translation of MSGID1 in domain DOMAIN:
768 		 starting at RETVAL, RETLEN bytes.  */
769 	      FREE_BLOCKS (block_list);
770 	      if (foundp == NULL)
771 		{
772 		  /* Create a new entry and add it to the search tree.  */
773 		  size_t msgid_len;
774 		  size_t size;
775 		  struct known_translation_t *newp;
776 
777 		  msgid_len = strlen (msgid1) + 1;
778 		  size = offsetof (struct known_translation_t, msgid)
779 			 + msgid_len + domainname_len + 1;
780 #ifdef HAVE_PER_THREAD_LOCALE
781 		  size += strlen (localename) + 1;
782 #endif
783 		  newp = (struct known_translation_t *) malloc (size);
784 		  if (newp != NULL)
785 		    {
786 		      char *new_domainname;
787 #ifdef HAVE_PER_THREAD_LOCALE
788 		      char *new_localename;
789 #endif
790 
791 		      new_domainname =
792 			(char *) mempcpy (newp->msgid.appended, msgid1,
793 					  msgid_len);
794 		      memcpy (new_domainname, domainname, domainname_len + 1);
795 #ifdef HAVE_PER_THREAD_LOCALE
796 		      new_localename = new_domainname + domainname_len + 1;
797 		      strcpy (new_localename, localename);
798 #endif
799 		      newp->domainname = new_domainname;
800 		      newp->category = category;
801 #ifdef HAVE_PER_THREAD_LOCALE
802 		      newp->localename = new_localename;
803 #endif
804 #ifdef IN_LIBGLOCALE
805 		      newp->encoding = encoding;
806 #endif
807 		      newp->counter = _nl_msg_cat_cntr;
808 		      newp->domain = domain;
809 		      newp->translation = retval;
810 		      newp->translation_length = retlen;
811 
812 		      gl_rwlock_wrlock (tree_lock);
813 
814 		      /* Insert the entry in the search tree.  */
815 		      foundp = (struct known_translation_t **)
816 			tsearch (newp, &root, transcmp);
817 
818 		      gl_rwlock_unlock (tree_lock);
819 
820 		      if (foundp == NULL
821 			  || __builtin_expect (*foundp != newp, 0))
822 			/* The insert failed.  */
823 			free (newp);
824 		    }
825 		}
826 	      else
827 		{
828 		  /* We can update the existing entry.  */
829 		  (*foundp)->counter = _nl_msg_cat_cntr;
830 		  (*foundp)->domain = domain;
831 		  (*foundp)->translation = retval;
832 		  (*foundp)->translation_length = retlen;
833 		}
834 
835 	      __set_errno (saved_errno);
836 
837 	      /* Now deal with plural.  */
838 	      if (plural)
839 		retval = plural_lookup (domain, n, retval, retlen);
840 
841 	      gl_rwlock_unlock (_nl_state_lock);
842 #ifdef _LIBC
843 	      __libc_rwlock_unlock (__libc_setlocale_lock);
844 #endif
845 	      return retval;
846 	    }
847 	}
848     }
849 
850  return_untranslated:
851   /* Return the untranslated MSGID.  */
852   FREE_BLOCKS (block_list);
853   gl_rwlock_unlock (_nl_state_lock);
854 #ifdef _LIBC
855   __libc_rwlock_unlock (__libc_setlocale_lock);
856 #endif
857 #ifndef _LIBC
858   if (!ENABLE_SECURE)
859     {
860       extern void _nl_log_untranslated (const char *logfilename,
861 					const char *domainname,
862 					const char *msgid1, const char *msgid2,
863 					int plural);
864       const char *logfilename = getenv ("GETTEXT_LOG_UNTRANSLATED");
865 
866       if (logfilename != NULL && logfilename[0] != '\0')
867 	_nl_log_untranslated (logfilename, domainname, msgid1, msgid2, plural);
868     }
869 #endif
870   __set_errno (saved_errno);
871   return (plural == 0
872 	  ? (char *) msgid1
873 	  /* Use the Germanic plural rule.  */
874 	  : n == 1 ? (char *) msgid1 : (char *) msgid2);
875 }
876 
877 
878 /* Look up the translation of msgid within DOMAIN_FILE and DOMAINBINDING.
879    Return it if found.  Return NULL if not found or in case of a conversion
880    failure (problem in the particular message catalog).  Return (char *) -1
881    in case of a memory allocation failure during conversion (only if
882    ENCODING != NULL resp. CONVERT == true).  */
883 char *
884 internal_function
885 #ifdef IN_LIBGLOCALE
_nl_find_msg(struct loaded_l10nfile * domain_file,struct binding * domainbinding,const char * encoding,const char * msgid,size_t * lengthp)886 _nl_find_msg (struct loaded_l10nfile *domain_file,
887 	      struct binding *domainbinding, const char *encoding,
888 	      const char *msgid,
889 	      size_t *lengthp)
890 #else
891 _nl_find_msg (struct loaded_l10nfile *domain_file,
892 	      struct binding *domainbinding,
893 	      const char *msgid, int convert,
894 	      size_t *lengthp)
895 #endif
896 {
897   struct loaded_domain *domain;
898   nls_uint32 nstrings;
899   size_t act;
900   char *result;
901   size_t resultlen;
902 
903   if (domain_file->decided <= 0)
904     _nl_load_domain (domain_file, domainbinding);
905 
906   if (domain_file->data == NULL)
907     return NULL;
908 
909   domain = (struct loaded_domain *) domain_file->data;
910 
911   nstrings = domain->nstrings;
912 
913   /* Locate the MSGID and its translation.  */
914   if (domain->hash_tab != NULL)
915     {
916       /* Use the hashing table.  */
917       nls_uint32 len = strlen (msgid);
918       nls_uint32 hash_val = __hash_string (msgid);
919       nls_uint32 idx = hash_val % domain->hash_size;
920       nls_uint32 incr = 1 + (hash_val % (domain->hash_size - 2));
921 
922       while (1)
923 	{
924 	  nls_uint32 nstr =
925 	    W (domain->must_swap_hash_tab, domain->hash_tab[idx]);
926 
927 	  if (nstr == 0)
928 	    /* Hash table entry is empty.  */
929 	    return NULL;
930 
931 	  nstr--;
932 
933 	  /* Compare msgid with the original string at index nstr.
934 	     We compare the lengths with >=, not ==, because plural entries
935 	     are represented by strings with an embedded NUL.  */
936 	  if (nstr < nstrings
937 	      ? W (domain->must_swap, domain->orig_tab[nstr].length) >= len
938 		&& (strcmp (msgid,
939 			    domain->data + W (domain->must_swap,
940 					      domain->orig_tab[nstr].offset))
941 		    == 0)
942 	      : domain->orig_sysdep_tab[nstr - nstrings].length > len
943 		&& (strcmp (msgid,
944 			    domain->orig_sysdep_tab[nstr - nstrings].pointer)
945 		    == 0))
946 	    {
947 	      act = nstr;
948 	      goto found;
949 	    }
950 
951 	  if (idx >= domain->hash_size - incr)
952 	    idx -= domain->hash_size - incr;
953 	  else
954 	    idx += incr;
955 	}
956       /* NOTREACHED */
957     }
958   else
959     {
960       /* Try the default method:  binary search in the sorted array of
961 	 messages.  */
962       size_t top, bottom;
963 
964       bottom = 0;
965       top = nstrings;
966       while (bottom < top)
967 	{
968 	  int cmp_val;
969 
970 	  act = (bottom + top) / 2;
971 	  cmp_val = strcmp (msgid, (domain->data
972 				    + W (domain->must_swap,
973 					 domain->orig_tab[act].offset)));
974 	  if (cmp_val < 0)
975 	    top = act;
976 	  else if (cmp_val > 0)
977 	    bottom = act + 1;
978 	  else
979 	    goto found;
980 	}
981       /* No translation was found.  */
982       return NULL;
983     }
984 
985  found:
986   /* The translation was found at index ACT.  If we have to convert the
987      string to use a different character set, this is the time.  */
988   if (act < nstrings)
989     {
990       result = (char *)
991 	(domain->data + W (domain->must_swap, domain->trans_tab[act].offset));
992       resultlen = W (domain->must_swap, domain->trans_tab[act].length) + 1;
993     }
994   else
995     {
996       result = (char *) domain->trans_sysdep_tab[act - nstrings].pointer;
997       resultlen = domain->trans_sysdep_tab[act - nstrings].length;
998     }
999 
1000 #if defined _LIBC || HAVE_ICONV
1001 # ifdef IN_LIBGLOCALE
1002   if (encoding != NULL)
1003 # else
1004   if (convert)
1005 # endif
1006     {
1007       /* We are supposed to do a conversion.  */
1008 # ifndef IN_LIBGLOCALE
1009       const char *encoding = get_output_charset (domainbinding);
1010 # endif
1011       size_t nconversions;
1012       struct converted_domain *convd;
1013       size_t i;
1014 
1015       /* Protect against reallocation of the table.  */
1016       gl_rwlock_rdlock (domain->conversions_lock);
1017 
1018       /* Search whether a table with converted translations for this
1019 	 encoding has already been allocated.  */
1020       nconversions = domain->nconversions;
1021       convd = NULL;
1022 
1023       for (i = nconversions; i > 0; )
1024 	{
1025 	  i--;
1026 	  if (strcmp (domain->conversions[i].encoding, encoding) == 0)
1027 	    {
1028 	      convd = &domain->conversions[i];
1029 	      break;
1030 	    }
1031 	}
1032 
1033       gl_rwlock_unlock (domain->conversions_lock);
1034 
1035       if (convd == NULL)
1036 	{
1037 	  /* We have to allocate a new conversions table.  */
1038 	  gl_rwlock_wrlock (domain->conversions_lock);
1039 	  nconversions = domain->nconversions;
1040 
1041 	  /* Maybe in the meantime somebody added the translation.
1042 	     Recheck.  */
1043 	  for (i = nconversions; i > 0; )
1044 	    {
1045 	      i--;
1046 	      if (strcmp (domain->conversions[i].encoding, encoding) == 0)
1047 		{
1048 		  convd = &domain->conversions[i];
1049 		  goto found_convd;
1050 		}
1051 	    }
1052 
1053 	  {
1054 	    /* Allocate a table for the converted translations for this
1055 	       encoding.  */
1056 	    struct converted_domain *new_conversions =
1057 	      (struct converted_domain *)
1058 	      (domain->conversions != NULL
1059 	       ? realloc (domain->conversions,
1060 			  (nconversions + 1) * sizeof (struct converted_domain))
1061 	       : malloc ((nconversions + 1) * sizeof (struct converted_domain)));
1062 
1063 	    if (__builtin_expect (new_conversions == NULL, 0))
1064 	      {
1065 		/* Nothing we can do, no more memory.  We cannot use the
1066 		   translation because it might be encoded incorrectly.  */
1067 	      unlock_fail:
1068 		gl_rwlock_unlock (domain->conversions_lock);
1069 		return (char *) -1;
1070 	      }
1071 
1072 	    domain->conversions = new_conversions;
1073 
1074 	    /* Copy the 'encoding' string to permanent storage.  */
1075 	    encoding = strdup (encoding);
1076 	    if (__builtin_expect (encoding == NULL, 0))
1077 	      /* Nothing we can do, no more memory.  We cannot use the
1078 		 translation because it might be encoded incorrectly.  */
1079 	      goto unlock_fail;
1080 
1081 	    convd = &new_conversions[nconversions];
1082 	    convd->encoding = encoding;
1083 
1084 	    /* Find out about the character set the file is encoded with.
1085 	       This can be found (in textual form) in the entry "".  If this
1086 	       entry does not exist or if this does not contain the 'charset='
1087 	       information, we will assume the charset matches the one the
1088 	       current locale and we don't have to perform any conversion.  */
1089 # ifdef _LIBC
1090 	    convd->conv = (__gconv_t) -1;
1091 # else
1092 #  if HAVE_ICONV
1093 	    convd->conv = (iconv_t) -1;
1094 #  endif
1095 # endif
1096 	    {
1097 	      char *nullentry;
1098 	      size_t nullentrylen;
1099 
1100 	      /* Get the header entry.  This is a recursion, but it doesn't
1101 		 reallocate domain->conversions because we pass
1102 		 encoding = NULL or convert = 0, respectively.  */
1103 	      nullentry =
1104 # ifdef IN_LIBGLOCALE
1105 		_nl_find_msg (domain_file, domainbinding, NULL, "",
1106 			      &nullentrylen);
1107 # else
1108 		_nl_find_msg (domain_file, domainbinding, "", 0, &nullentrylen);
1109 # endif
1110 
1111 	      /* Resource problems are fatal.  If we continue onwards we will
1112 	         only attempt to calloc a new conv_tab and fail later.  */
1113 	      if (__builtin_expect (nullentry == (char *) -1, 0))
1114 	        return (char *) -1;
1115 
1116 	      if (nullentry != NULL)
1117 		{
1118 		  const char *charsetstr;
1119 
1120 		  charsetstr = strstr (nullentry, "charset=");
1121 		  if (charsetstr != NULL)
1122 		    {
1123 		      size_t len;
1124 		      char *charset;
1125 		      const char *outcharset;
1126 
1127 		      charsetstr += strlen ("charset=");
1128 		      len = strcspn (charsetstr, " \t\n");
1129 
1130 		      charset = (char *) alloca (len + 1);
1131 # if defined _LIBC || HAVE_MEMPCPY
1132 		      *((char *) mempcpy (charset, charsetstr, len)) = '\0';
1133 # else
1134 		      memcpy (charset, charsetstr, len);
1135 		      charset[len] = '\0';
1136 # endif
1137 
1138 		      outcharset = encoding;
1139 
1140 # ifdef _LIBC
1141 		      /* We always want to use transliteration.  */
1142 		      outcharset = norm_add_slashes (outcharset, "TRANSLIT");
1143 		      charset = norm_add_slashes (charset, "");
1144 		      int r = __gconv_open (outcharset, charset, &convd->conv,
1145 					    GCONV_AVOID_NOCONV);
1146 		      if (__builtin_expect (r != __GCONV_OK, 0))
1147 			{
1148 			  /* If the output encoding is the same there is
1149 			     nothing to do.  Otherwise do not use the
1150 			     translation at all.  */
1151 			  if (__builtin_expect (r != __GCONV_NULCONV, 1))
1152 			    {
1153 			      gl_rwlock_unlock (domain->conversions_lock);
1154 			      free ((char *) encoding);
1155 			      return NULL;
1156 			    }
1157 
1158 			  convd->conv = (__gconv_t) -1;
1159 			}
1160 # else
1161 #  if HAVE_ICONV
1162 		      /* When using GNU libc >= 2.2 or GNU libiconv >= 1.5,
1163 			 we want to use transliteration.  */
1164 #   if (((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2) || __GLIBC__ > 2) \
1165 	&& !defined __UCLIBC__) \
1166        || _LIBICONV_VERSION >= 0x0105
1167 		      if (strchr (outcharset, '/') == NULL)
1168 			{
1169 			  char *tmp;
1170 
1171 			  len = strlen (outcharset);
1172 			  tmp = (char *) alloca (len + 10 + 1);
1173 			  memcpy (tmp, outcharset, len);
1174 			  memcpy (tmp + len, "//TRANSLIT", 10 + 1);
1175 			  outcharset = tmp;
1176 
1177 			  convd->conv = iconv_open (outcharset, charset);
1178 
1179 			  freea (outcharset);
1180 			}
1181 		      else
1182 #   endif
1183 			convd->conv = iconv_open (outcharset, charset);
1184 #  endif
1185 # endif
1186 
1187 		      freea (charset);
1188 		    }
1189 		}
1190 	    }
1191 	    convd->conv_tab = NULL;
1192 	    /* Here domain->conversions is still == new_conversions.  */
1193 	    domain->nconversions++;
1194 	  }
1195 
1196 	found_convd:
1197 	  gl_rwlock_unlock (domain->conversions_lock);
1198 	}
1199 
1200       if (
1201 # ifdef _LIBC
1202 	  convd->conv != (__gconv_t) -1
1203 # else
1204 #  if HAVE_ICONV
1205 	  convd->conv != (iconv_t) -1
1206 #  endif
1207 # endif
1208 	  )
1209 	{
1210 	  /* We are supposed to do a conversion.  First allocate an
1211 	     appropriate table with the same structure as the table
1212 	     of translations in the file, where we can put the pointers
1213 	     to the converted strings in.
1214 	     There is a slight complication with plural entries.  They
1215 	     are represented by consecutive NUL terminated strings.  We
1216 	     handle this case by converting RESULTLEN bytes, including
1217 	     NULs.  */
1218 
1219 	  /* This lock primarily protects the memory management variables
1220 	     freemem, freemem_size.  It also protects write accesses to
1221 	     convd->conv_tab.  It's not worth using a separate lock (such
1222 	     as domain->conversions_lock) for this purpose, because when
1223 	     modifying convd->conv_tab, we also need to lock freemem,
1224 	     freemem_size for most of the time.  */
1225 	  __libc_lock_define_initialized (static, lock)
1226 
1227 	  if (__builtin_expect (convd->conv_tab == NULL, 0))
1228 	    {
1229 	      __libc_lock_lock (lock);
1230 	      if (convd->conv_tab == NULL)
1231 		{
1232 		  convd->conv_tab =
1233 		    (char **) calloc (nstrings + domain->n_sysdep_strings,
1234 				      sizeof (char *));
1235 		  if (convd->conv_tab != NULL)
1236 		    goto not_translated_yet;
1237 		  /* Mark that we didn't succeed allocating a table.  */
1238 		  convd->conv_tab = (char **) -1;
1239 		}
1240 	      __libc_lock_unlock (lock);
1241 	    }
1242 
1243 	  if (__builtin_expect (convd->conv_tab == (char **) -1, 0))
1244 	    /* Nothing we can do, no more memory.  We cannot use the
1245 	       translation because it might be encoded incorrectly.  */
1246 	    return (char *) -1;
1247 
1248 	  if (convd->conv_tab[act] == NULL)
1249 	    {
1250 	      /* We haven't used this string so far, so it is not
1251 		 translated yet.  Do this now.  */
1252 	      /* We use a bit more efficient memory handling.
1253 		 We allocate always larger blocks which get used over
1254 		 time.  This is faster than many small allocations.   */
1255 # define INITIAL_BLOCK_SIZE	4080
1256 	      static unsigned char *freemem;
1257 	      static size_t freemem_size;
1258 
1259 	      const unsigned char *inbuf;
1260 	      unsigned char *outbuf;
1261 	      int malloc_count;
1262 # ifndef _LIBC
1263 	      transmem_block_t *transmem_list;
1264 # endif
1265 
1266 	      __libc_lock_lock (lock);
1267 	    not_translated_yet:
1268 
1269 	      inbuf = (const unsigned char *) result;
1270 	      outbuf = freemem + sizeof (size_t);
1271 # ifndef _LIBC
1272 	      transmem_list = NULL;
1273 # endif
1274 
1275 	      malloc_count = 0;
1276 	      while (1)
1277 		{
1278 		  transmem_block_t *newmem;
1279 # ifdef _LIBC
1280 		  size_t non_reversible;
1281 		  int res;
1282 
1283 		  if (freemem_size < sizeof (size_t))
1284 		    goto resize_freemem;
1285 
1286 		  res = __gconv (convd->conv,
1287 				 &inbuf, inbuf + resultlen,
1288 				 &outbuf,
1289 				 outbuf + freemem_size - sizeof (size_t),
1290 				 &non_reversible);
1291 
1292 		  if (res == __GCONV_OK || res == __GCONV_EMPTY_INPUT)
1293 		    break;
1294 
1295 		  if (res != __GCONV_FULL_OUTPUT)
1296 		    {
1297 		      /* We should not use the translation at all, it
1298 			 is incorrectly encoded.  */
1299 		      __libc_lock_unlock (lock);
1300 		      return NULL;
1301 		    }
1302 
1303 		  inbuf = (const unsigned char *) result;
1304 # else
1305 #  if HAVE_ICONV
1306 		  const char *inptr = (const char *) inbuf;
1307 		  size_t inleft = resultlen;
1308 		  char *outptr = (char *) outbuf;
1309 		  size_t outleft;
1310 
1311 		  if (freemem_size < sizeof (size_t))
1312 		    goto resize_freemem;
1313 
1314 		  outleft = freemem_size - sizeof (size_t);
1315 		  if (iconv (convd->conv,
1316 			     (ICONV_CONST char **) &inptr, &inleft,
1317 			     &outptr, &outleft)
1318 		      != (size_t) (-1))
1319 		    {
1320 		      outbuf = (unsigned char *) outptr;
1321 		      break;
1322 		    }
1323 		  if (errno != E2BIG)
1324 		    {
1325 		      __libc_lock_unlock (lock);
1326 		      return NULL;
1327 		    }
1328 #  endif
1329 # endif
1330 
1331 		resize_freemem:
1332 		  /* We must allocate a new buffer or resize the old one.  */
1333 		  if (malloc_count > 0)
1334 		    {
1335 		      ++malloc_count;
1336 		      freemem_size = malloc_count * INITIAL_BLOCK_SIZE;
1337 		      newmem = (transmem_block_t *) realloc (transmem_list,
1338 							     freemem_size);
1339 # ifdef _LIBC
1340 		      if (newmem != NULL)
1341 			transmem_list = newmem;
1342 		      else
1343 			{
1344 			  struct transmem_list *old = transmem_list;
1345 
1346 			  transmem_list = transmem_list->next;
1347 			  free (old);
1348 			}
1349 # endif
1350 		    }
1351 		  else
1352 		    {
1353 		      malloc_count = 1;
1354 		      freemem_size = INITIAL_BLOCK_SIZE;
1355 		      newmem = (transmem_block_t *) malloc (freemem_size);
1356 # ifdef _LIBC
1357 		      if (newmem != NULL)
1358 			{
1359 			  /* Add the block to the list of blocks we have to free
1360 			     at some point.  */
1361 			  newmem->next = transmem_list;
1362 			  transmem_list = newmem;
1363 			}
1364 		      /* Fall through and return -1.  */
1365 # endif
1366 		    }
1367 		  if (__builtin_expect (newmem == NULL, 0))
1368 		    {
1369 		      freemem = NULL;
1370 		      freemem_size = 0;
1371 		      __libc_lock_unlock (lock);
1372 		      return (char *) -1;
1373 		    }
1374 
1375 # ifdef _LIBC
1376 		  freemem = (unsigned char *) newmem->data;
1377 		  freemem_size -= offsetof (struct transmem_list, data);
1378 # else
1379 		  transmem_list = newmem;
1380 		  freemem = newmem;
1381 # endif
1382 
1383 		  outbuf = freemem + sizeof (size_t);
1384 		}
1385 
1386 	      /* We have now in our buffer a converted string.  Put this
1387 		 into the table of conversions.  */
1388 	      *(size_t *) freemem = outbuf - freemem - sizeof (size_t);
1389 	      convd->conv_tab[act] = (char *) freemem;
1390 	      /* Shrink freemem, but keep it aligned.  */
1391 	      freemem_size -= outbuf - freemem;
1392 	      freemem = outbuf;
1393 	      freemem += freemem_size & (alignof (size_t) - 1);
1394 	      freemem_size = freemem_size & ~ (alignof (size_t) - 1);
1395 
1396 	      __libc_lock_unlock (lock);
1397 	    }
1398 
1399 	  /* Now convd->conv_tab[act] contains the translation of all
1400 	     the plural variants.  */
1401 	  result = convd->conv_tab[act] + sizeof (size_t);
1402 	  resultlen = *(size_t *) convd->conv_tab[act];
1403 	}
1404     }
1405 
1406   /* The result string is converted.  */
1407 
1408 #endif /* _LIBC || HAVE_ICONV */
1409 
1410   *lengthp = resultlen;
1411   return result;
1412 }
1413 
1414 
1415 /* Look up a plural variant.  */
1416 static char *
1417 internal_function
plural_lookup(struct loaded_l10nfile * domain,unsigned long int n,const char * translation,size_t translation_len)1418 plural_lookup (struct loaded_l10nfile *domain, unsigned long int n,
1419 	       const char *translation, size_t translation_len)
1420 {
1421   struct loaded_domain *domaindata = (struct loaded_domain *) domain->data;
1422   unsigned long int index;
1423   const char *p;
1424 
1425   index = plural_eval (domaindata->plural, n);
1426   if (index >= domaindata->nplurals)
1427     /* This should never happen.  It means the plural expression and the
1428        given maximum value do not match.  */
1429     index = 0;
1430 
1431   /* Skip INDEX strings at TRANSLATION.  */
1432   p = translation;
1433   while (index-- > 0)
1434     {
1435 #ifdef _LIBC
1436       p = __rawmemchr (p, '\0');
1437 #else
1438       p = strchr (p, '\0');
1439 #endif
1440       /* And skip over the NUL byte.  */
1441       p++;
1442 
1443       if (p >= translation + translation_len)
1444 	/* This should never happen.  It means the plural expression
1445 	   evaluated to a value larger than the number of variants
1446 	   available for MSGID1.  */
1447 	return (char *) translation;
1448     }
1449   return (char *) p;
1450 }
1451 
1452 #ifndef _LIBC
1453 /* Return string representation of locale CATEGORY.  */
1454 static const char *
1455 internal_function
category_to_name(int category)1456 category_to_name (int category)
1457 {
1458   const char *retval;
1459 
1460   switch (category)
1461   {
1462 #ifdef LC_COLLATE
1463   case LC_COLLATE:
1464     retval = "LC_COLLATE";
1465     break;
1466 #endif
1467 #ifdef LC_CTYPE
1468   case LC_CTYPE:
1469     retval = "LC_CTYPE";
1470     break;
1471 #endif
1472 #ifdef LC_MONETARY
1473   case LC_MONETARY:
1474     retval = "LC_MONETARY";
1475     break;
1476 #endif
1477 #ifdef LC_NUMERIC
1478   case LC_NUMERIC:
1479     retval = "LC_NUMERIC";
1480     break;
1481 #endif
1482 #ifdef LC_TIME
1483   case LC_TIME:
1484     retval = "LC_TIME";
1485     break;
1486 #endif
1487 #ifdef LC_MESSAGES
1488   case LC_MESSAGES:
1489     retval = "LC_MESSAGES";
1490     break;
1491 #endif
1492 #ifdef LC_RESPONSE
1493   case LC_RESPONSE:
1494     retval = "LC_RESPONSE";
1495     break;
1496 #endif
1497 #ifdef LC_ALL
1498   case LC_ALL:
1499     /* This might not make sense but is perhaps better than any other
1500        value.  */
1501     retval = "LC_ALL";
1502     break;
1503 #endif
1504   default:
1505     /* If you have a better idea for a default value let me know.  */
1506     retval = "LC_XXX";
1507   }
1508 
1509   return retval;
1510 }
1511 #endif
1512 
1513 /* Guess value of current locale from value of the environment variables
1514    or system-dependent defaults.  */
1515 static const char *
1516 internal_function
1517 #ifdef IN_LIBGLOCALE
guess_category_value(int category,const char * categoryname,const char * locale)1518 guess_category_value (int category, const char *categoryname,
1519 		      const char *locale)
1520 
1521 #else
1522 guess_category_value (int category, const char *categoryname)
1523 #endif
1524 {
1525   const char *language;
1526 #ifndef IN_LIBGLOCALE
1527   const char *locale;
1528 # ifndef _LIBC
1529   const char *language_default;
1530   int locale_defaulted;
1531 # endif
1532 #endif
1533 
1534   /* We use the settings in the following order:
1535      1. The value of the environment variable 'LANGUAGE'.  This is a GNU
1536         extension.  Its value can be a colon-separated list of locale names.
1537      2. The value of the environment variable 'LC_ALL', 'LC_xxx', or 'LANG'.
1538         More precisely, the first among these that is set to a non-empty value.
1539         This is how POSIX specifies it.  The value is a single locale name.
1540      3. A system-dependent preference list of languages.  Its value can be a
1541         colon-separated list of locale names.
1542      4. A system-dependent default locale name.
1543      This way:
1544        - System-dependent settings can be overridden by environment variables.
1545        - If the system provides both a list of languages and a default locale,
1546          the former is used.  */
1547 
1548 #ifndef IN_LIBGLOCALE
1549   /* Fetch the locale name, through the POSIX method of looking to `LC_ALL',
1550      `LC_xxx', and `LANG'.  On some systems this can be done by the
1551      `setlocale' function itself.  */
1552 # ifdef _LIBC
1553   locale = __current_locale_name (category);
1554 # else
1555   locale_defaulted = 0;
1556 #  if HAVE_USELOCALE
1557   locale = _nl_locale_name_thread_unsafe (category, categoryname);
1558   if (locale == NULL)
1559 #  endif
1560     {
1561       locale = _nl_locale_name_posix (category, categoryname);
1562       if (locale == NULL)
1563 	{
1564 	  locale = _nl_locale_name_default ();
1565 	  locale_defaulted = 1;
1566 	}
1567     }
1568 # endif
1569 #endif
1570 
1571   /* Ignore LANGUAGE and its system-dependent analogon if the locale is set
1572      to "C" because
1573      1. "C" locale usually uses the ASCII encoding, and most international
1574 	messages use non-ASCII characters. These characters get displayed
1575 	as question marks (if using glibc's iconv()) or as invalid 8-bit
1576 	characters (because other iconv()s refuse to convert most non-ASCII
1577 	characters to ASCII). In any case, the output is ugly.
1578      2. The precise output of some programs in the "C" locale is specified
1579 	by POSIX and should not depend on environment variables like
1580 	"LANGUAGE" or system-dependent information.  We allow such programs
1581         to use gettext().  */
1582   if (strcmp (locale, "C") == 0)
1583     return locale;
1584 
1585   /* The highest priority value is the value of the 'LANGUAGE' environment
1586      variable.  */
1587   language = getenv ("LANGUAGE");
1588   if (language != NULL && language[0] != '\0')
1589     return language;
1590 #if !defined IN_LIBGLOCALE && !defined _LIBC
1591   /* The next priority value is the locale name, if not defaulted.  */
1592   if (locale_defaulted)
1593     {
1594       /* The next priority value is the default language preferences list. */
1595       language_default = _nl_language_preferences_default ();
1596       if (language_default != NULL)
1597         return language_default;
1598     }
1599   /* The least priority value is the locale name, if defaulted.  */
1600 #endif
1601   return locale;
1602 }
1603 
1604 #if (defined _LIBC || HAVE_ICONV) && !defined IN_LIBGLOCALE
1605 /* Returns the output charset.  */
1606 static const char *
1607 internal_function
get_output_charset(struct binding * domainbinding)1608 get_output_charset (struct binding *domainbinding)
1609 {
1610   /* The output charset should normally be determined by the locale.  But
1611      sometimes the locale is not used or not correctly set up, so we provide
1612      a possibility for the user to override this: the OUTPUT_CHARSET
1613      environment variable.  Moreover, the value specified through
1614      bind_textdomain_codeset overrides both.  */
1615   if (domainbinding != NULL && domainbinding->codeset != NULL)
1616     return domainbinding->codeset;
1617   else
1618     {
1619       /* For speed reasons, we look at the value of OUTPUT_CHARSET only
1620 	 once.  This is a user variable that is not supposed to change
1621 	 during a program run.  */
1622       static char *output_charset_cache;
1623       static int output_charset_cached;
1624 
1625       if (!output_charset_cached)
1626 	{
1627 	  const char *value = getenv ("OUTPUT_CHARSET");
1628 
1629 	  if (value != NULL && value[0] != '\0')
1630 	    {
1631 	      size_t len = strlen (value) + 1;
1632 	      char *value_copy = (char *) malloc (len);
1633 
1634 	      if (value_copy != NULL)
1635 		memcpy (value_copy, value, len);
1636 	      output_charset_cache = value_copy;
1637 	    }
1638 	  output_charset_cached = 1;
1639 	}
1640 
1641       if (output_charset_cache != NULL)
1642 	return output_charset_cache;
1643       else
1644 	{
1645 # ifdef _LIBC
1646 	  return _NL_CURRENT (LC_CTYPE, CODESET);
1647 # else
1648 #  if HAVE_ICONV
1649 	  return locale_charset ();
1650 #  endif
1651 # endif
1652 	}
1653     }
1654 }
1655 #endif
1656 
1657 /* @@ begin of epilog @@ */
1658 
1659 /* We don't want libintl.a to depend on any other library.  So we
1660    avoid the non-standard function stpcpy.  In GNU C Library this
1661    function is available, though.  Also allow the symbol HAVE_STPCPY
1662    to be defined.  */
1663 #if !_LIBC && !HAVE_STPCPY
1664 static char *
stpcpy(char * dest,const char * src)1665 stpcpy (char *dest, const char *src)
1666 {
1667   while ((*dest++ = *src++) != '\0')
1668     /* Do nothing. */ ;
1669   return dest - 1;
1670 }
1671 #endif
1672 
1673 #if !_LIBC && !HAVE_MEMPCPY
1674 static void *
mempcpy(void * dest,const void * src,size_t n)1675 mempcpy (void *dest, const void *src, size_t n)
1676 {
1677   return (void *) ((char *) memcpy (dest, src, n) + n);
1678 }
1679 #endif
1680 
1681 #if !_LIBC && !HAVE_TSEARCH
1682 # include "tsearch.c"
1683 #endif
1684 
1685 
1686 #ifdef _LIBC
1687 /* If we want to free all resources we have to do some work at
1688    program's end.  */
libc_freeres_fn(free_mem)1689 libc_freeres_fn (free_mem)
1690 {
1691   void *old;
1692 
1693   while (_nl_domain_bindings != NULL)
1694     {
1695       struct binding *oldp = _nl_domain_bindings;
1696       _nl_domain_bindings = _nl_domain_bindings->next;
1697       if (oldp->dirname != _nl_default_dirname)
1698 	/* Yes, this is a pointer comparison.  */
1699 	free (oldp->dirname);
1700       free (oldp->codeset);
1701       free (oldp);
1702     }
1703 
1704   if (_nl_current_default_domain != _nl_default_default_domain)
1705     /* Yes, again a pointer comparison.  */
1706     free ((char *) _nl_current_default_domain);
1707 
1708   /* Remove the search tree with the known translations.  */
1709   __tdestroy (root, free);
1710   root = NULL;
1711 
1712   while (transmem_list != NULL)
1713     {
1714       old = transmem_list;
1715       transmem_list = transmem_list->next;
1716       free (old);
1717     }
1718 }
1719 #endif
1720