dfabaa9f8acabede4c6c85fab0f00a35bfdd3c19
[platform/upstream/glibc.git] / locale / programs / localedef.c
1 /* Copyright (C) 1995-2002, 2003, 2004, 2005 Free Software Foundation, Inc.
2    This file is part of the GNU C Library.
3    Contributed by Ulrich Drepper <drepper@cygnus.com>, 1995.
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License version 2 as
7    published by the Free Software Foundation.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
17
18 #ifdef HAVE_CONFIG_H
19 # include <config.h>
20 #endif
21
22 #include <argp.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <libintl.h>
26 #include <locale.h>
27 #include <mcheck.h>
28 #include <stdbool.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <unistd.h>
33 #include <error.h>
34 #include <sys/mman.h>
35 #include <sys/stat.h>
36
37 #include "localedef.h"
38 #include "charmap.h"
39 #include "locfile.h"
40
41 /* Undefine the following line in the production version.  */
42 /* #define NDEBUG 1 */
43 #include <assert.h>
44
45
46 /* List of copied locales.  */
47 struct copy_def_list_t *copy_list;
48
49 /* If this is defined be POSIX conform.  */
50 int posix_conformance;
51
52 /* If not zero give a lot more messages.  */
53 int verbose;
54
55 /* If not zero suppress warnings and information messages.  */
56 int be_quiet;
57
58 /* If not zero, produce old-style hash table instead of 3-level access
59    tables.  */
60 int oldstyle_tables;
61
62 /* If not zero force output even if warning were issued.  */
63 static int force_output;
64
65 /* Prefix for output files.  */
66 const char *output_prefix;
67
68 /* Name of the character map file.  */
69 static const char *charmap_file;
70
71 /* Name of the locale definition file.  */
72 static const char *input_file;
73
74 /* Name of the repertoire map file.  */
75 const char *repertoire_global;
76
77 /* Name of the locale.alias file.  */
78 const char *alias_file;
79
80 /* List of all locales.  */
81 static struct localedef_t *locales;
82
83 /* If true don't add locale data to archive.  */
84 bool no_archive;
85
86 /* If true add named locales to archive.  */
87 static bool add_to_archive;
88
89 /* If true delete named locales from archive.  */
90 static bool delete_from_archive;
91
92 /* If true replace archive content when adding.  */
93 static bool replace_archive;
94
95 /* If true list archive content.  */
96 static bool list_archive;
97
98 /* Maximum number of retries when opening the locale archive.  */
99 int max_locarchive_open_retry = 10;
100
101
102 /* Name and version of program.  */
103 static void print_version (FILE *stream, struct argp_state *state);
104 void (*argp_program_version_hook) (FILE *, struct argp_state *) = print_version;
105
106 #define OPT_POSIX 301
107 #define OPT_QUIET 302
108 #define OPT_OLDSTYLE 303
109 #define OPT_PREFIX 304
110 #define OPT_NO_ARCHIVE 305
111 #define OPT_ADD_TO_ARCHIVE 306
112 #define OPT_REPLACE 307
113 #define OPT_DELETE_FROM_ARCHIVE 308
114 #define OPT_LIST_ARCHIVE 309
115
116 /* Definitions of arguments for argp functions.  */
117 static const struct argp_option options[] =
118 {
119   { NULL, 0, NULL, 0, N_("Input Files:") },
120   { "charmap", 'f', "FILE", 0,
121     N_("Symbolic character names defined in FILE") },
122   { "inputfile", 'i', "FILE", 0, N_("Source definitions are found in FILE") },
123   { "repertoire-map", 'u', "FILE", 0,
124     N_("FILE contains mapping from symbolic names to UCS4 values") },
125
126   { NULL, 0, NULL, 0, N_("Output control:") },
127   { "force", 'c', NULL, 0,
128     N_("Create output even if warning messages were issued") },
129   { "old-style", OPT_OLDSTYLE, NULL, 0, N_("Create old-style tables") },
130   { "prefix", OPT_PREFIX, "PATH", 0, N_("Optional output file prefix") },
131   { "posix", OPT_POSIX, NULL, 0, N_("Be strictly POSIX conform") },
132   { "quiet", OPT_QUIET, NULL, 0,
133     N_("Suppress warnings and information messages") },
134   { "verbose", 'v', NULL, 0, N_("Print more messages") },
135   { NULL, 0, NULL, 0, N_("Archive control:") },
136   { "no-archive", OPT_NO_ARCHIVE, NULL, 0,
137     N_("Don't add new data to archive") },
138   { "add-to-archive", OPT_ADD_TO_ARCHIVE, NULL, 0,
139     N_("Add locales named by parameters to archive") },
140   { "replace", OPT_REPLACE, NULL, 0, N_("Replace existing archive content") },
141   { "delete-from-archive", OPT_DELETE_FROM_ARCHIVE, NULL, 0,
142     N_("Remove locales named by parameters from archive") },
143   { "list-archive", OPT_LIST_ARCHIVE, NULL, 0, N_("List content of archive") },
144   { "alias-file", 'A', "FILE", 0,
145     N_("locale.alias file to consult when making archive")},
146   { NULL, 0, NULL, 0, NULL }
147 };
148
149 /* Short description of program.  */
150 static const char doc[] = N_("Compile locale specification");
151
152 /* Strings for arguments in help texts.  */
153 static const char args_doc[] = N_("\
154 NAME\n\
155 [--add-to-archive|--delete-from-archive] FILE...\n\
156 --list-archive [FILE]");
157
158 /* Prototype for option handler.  */
159 static error_t parse_opt (int key, char *arg, struct argp_state *state);
160
161 /* Function to print some extra text in the help message.  */
162 static char *more_help (int key, const char *text, void *input);
163
164 /* Data structure to communicate with argp functions.  */
165 static struct argp argp =
166 {
167   options, parse_opt, args_doc, doc, NULL, more_help
168 };
169
170
171 /* Prototypes for global functions.  */
172 extern void *xmalloc (size_t __n);
173
174 /* Prototypes for local functions.  */
175 static void error_print (void);
176 static const char *construct_output_path (char *path);
177 static const char *normalize_codeset (const char *codeset, size_t name_len);
178
179
180 int
181 main (int argc, char *argv[])
182 {
183   const char *output_path;
184   int cannot_write_why;
185   struct charmap_t *charmap;
186   struct localedef_t global;
187   int remaining;
188
189   /* Set initial values for global variables.  */
190   copy_list = NULL;
191   posix_conformance = getenv ("POSIXLY_CORRECT") != NULL;
192   error_print_progname = error_print;
193
194   /* Set locale.  Do not set LC_ALL because the other categories must
195      not be affected (according to POSIX.2).  */
196   setlocale (LC_MESSAGES, "");
197   setlocale (LC_CTYPE, "");
198
199   /* Initialize the message catalog.  */
200   textdomain (_libc_intl_domainname);
201
202   /* Parse and process arguments.  */
203   argp_err_exit_status = 4;
204   argp_parse (&argp, argc, argv, 0, &remaining, NULL);
205
206   /* Handle a few special cases.  */
207   if (list_archive)
208     show_archive_content (verbose);
209   if (add_to_archive)
210     return add_locales_to_archive (argc - remaining, &argv[remaining],
211                                    replace_archive);
212   if (delete_from_archive)
213     return delete_locales_from_archive (argc - remaining, &argv[remaining]);
214
215   /* POSIX.2 requires to be verbose about missing characters in the
216      character map.  */
217   verbose |= posix_conformance;
218
219   if (argc - remaining != 1)
220     {
221       /* We need exactly one non-option parameter.  */
222       argp_help (&argp, stdout, ARGP_HELP_SEE | ARGP_HELP_EXIT_ERR,
223                  program_invocation_short_name);
224       exit (4);
225     }
226
227   /* The parameter describes the output path of the constructed files.
228      If the described files cannot be written return a NULL pointer.  */
229   output_path  = construct_output_path (argv[remaining]);
230   if (output_path == NULL && ! no_archive)
231     error (4, errno, _("cannot create directory for output files"));
232   cannot_write_why = errno;
233
234   /* Now that the parameters are processed we have to reset the local
235      ctype locale.  (P1003.2 4.35.5.2)  */
236   setlocale (LC_CTYPE, "POSIX");
237
238   /* Look whether the system really allows locale definitions.  POSIX
239      defines error code 3 for this situation so I think it must be
240      a fatal error (see P1003.2 4.35.8).  */
241   if (sysconf (_SC_2_LOCALEDEF) < 0)
242     WITH_CUR_LOCALE (error (3, 0, _("\
243 FATAL: system does not define `_POSIX2_LOCALEDEF'")));
244
245   /* Process charmap file.  */
246   charmap = charmap_read (charmap_file, verbose, be_quiet, 1);
247
248   /* Add the first entry in the locale list.  */
249   memset (&global, '\0', sizeof (struct localedef_t));
250   global.name = input_file ?: "/dev/stdin";
251   global.needed = ALL_LOCALES;
252   locales = &global;
253
254   /* Now read the locale file.  */
255   if (locfile_read (&global, charmap) != 0)
256     WITH_CUR_LOCALE (error (4, errno, _("\
257 cannot open locale definition file `%s'"), input_file));
258
259   /* Perhaps we saw some `copy' instructions.  */
260   while (1)
261     {
262       struct localedef_t *runp = locales;
263
264       while (runp != NULL && (runp->needed & runp->avail) == runp->needed)
265         runp = runp->next;
266
267       if (runp == NULL)
268         /* Everything read.  */
269         break;
270
271       if (locfile_read (runp, charmap) != 0)
272         WITH_CUR_LOCALE (error (4, errno, _("\
273 cannot open locale definition file `%s'"), runp->name));
274     }
275
276   /* Check the categories we processed in source form.  */
277   check_all_categories (locales, charmap);
278
279   /* We are now able to write the data files.  If warning were given we
280      do it only if it is explicitly requested (--force).  */
281   if (error_message_count == 0 || force_output != 0)
282     {
283       if (cannot_write_why != 0)
284         WITH_CUR_LOCALE (error (4, cannot_write_why, _("\
285 cannot write output files to `%s'"), output_path));
286       else
287         write_all_categories (locales, charmap, argv[remaining], output_path);
288     }
289   else
290     WITH_CUR_LOCALE (error (4, 0, _("\
291 no output file produced because warning were issued")));
292
293   /* This exit status is prescribed by POSIX.2 4.35.7.  */
294   exit (error_message_count != 0);
295 }
296
297
298 /* Handle program arguments.  */
299 static error_t
300 parse_opt (int key, char *arg, struct argp_state *state)
301 {
302   switch (key)
303     {
304     case OPT_QUIET:
305       be_quiet = 1;
306       break;
307     case OPT_POSIX:
308       posix_conformance = 1;
309       break;
310     case OPT_OLDSTYLE:
311       oldstyle_tables = 1;
312       break;
313     case OPT_PREFIX:
314       output_prefix = arg;
315       break;
316     case OPT_NO_ARCHIVE:
317       no_archive = true;
318       break;
319     case OPT_ADD_TO_ARCHIVE:
320       add_to_archive = true;
321       break;
322     case OPT_REPLACE:
323       replace_archive = true;
324       break;
325     case OPT_DELETE_FROM_ARCHIVE:
326       delete_from_archive = true;
327       break;
328     case OPT_LIST_ARCHIVE:
329       list_archive = true;
330       break;
331     case 'c':
332       force_output = 1;
333       break;
334     case 'f':
335       charmap_file = arg;
336       break;
337     case 'A':
338       alias_file = arg;
339       break;
340     case 'i':
341       input_file = arg;
342       break;
343     case 'u':
344       repertoire_global = arg;
345       break;
346     case 'v':
347       verbose = 1;
348       break;
349     default:
350       return ARGP_ERR_UNKNOWN;
351     }
352   return 0;
353 }
354
355
356 static char *
357 more_help (int key, const char *text, void *input)
358 {
359   char *cp;
360
361   switch (key)
362     {
363     case ARGP_KEY_HELP_EXTRA:
364       /* We print some extra information.  */
365       if (asprintf (&cp, gettext ("\
366 System's directory for character maps : %s\n\
367                        repertoire maps: %s\n\
368                        locale path    : %s\n\
369 %s"),
370                     CHARMAP_PATH, REPERTOIREMAP_PATH, LOCALE_PATH, gettext ("\
371 For bug reporting instructions, please see:\n\
372 <http://www.gnu.org/software/libc/bugs.html>.\n")) < 0)
373         return NULL;
374       return cp;
375     default:
376       break;
377     }
378   return (char *) text;
379 }
380
381 /* Print the version information.  */
382 static void
383 print_version (FILE *stream, struct argp_state *state)
384 {
385   fprintf (stream, "localedef (GNU %s) %s\n", PACKAGE, VERSION);
386   fprintf (stream, gettext ("\
387 Copyright (C) %s Free Software Foundation, Inc.\n\
388 This is free software; see the source for copying conditions.  There is NO\n\
389 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
390 "), "2005");
391   fprintf (stream, gettext ("Written by %s.\n"), "Ulrich Drepper");
392 }
393
394
395 /* The address of this function will be assigned to the hook in the error
396    functions.  */
397 static void
398 error_print (void)
399 {
400 }
401
402
403 /* The parameter to localedef describes the output path.  If it does
404    contain a '/' character it is a relative path.  Otherwise it names the
405    locale this definition is for.  */
406 static const char *
407 construct_output_path (char *path)
408 {
409   const char *normal = NULL;
410   char *result;
411   char *endp;
412
413   if (strchr (path, '/') == NULL)
414     {
415       /* This is a system path.  First examine whether the locale name
416          contains a reference to the codeset.  This should be
417          normalized.  */
418       char *startp;
419       size_t n;
420
421       startp = path;
422       /* We must be prepared for finding a CEN name or a location of
423          the introducing `.' where it is not possible anymore.  */
424       while (*startp != '\0' && *startp != '@' && *startp != '.')
425         ++startp;
426       if (*startp == '.')
427         {
428           /* We found a codeset specification.  Now find the end.  */
429           endp = ++startp;
430           while (*endp != '\0' && *endp != '@')
431             ++endp;
432
433           if (endp > startp)
434             normal = normalize_codeset (startp, endp - startp);
435         }
436       else
437         /* This is to keep gcc quiet.  */
438         endp = NULL;
439
440       /* We put an additional '\0' at the end of the string because at
441          the end of the function we need another byte for the trailing
442          '/'.  */
443       if (normal == NULL)
444         n = asprintf (&result, "%s%s/%s%c",
445                       output_prefix ?: "", LOCALEDIR, path, '\0');
446       else
447         n = asprintf (&result, "%s%s/%.*s%s%s%c",
448                       output_prefix ?: "", LOCALEDIR,
449                       (int) (startp - path), path, normal, endp, '\0');
450
451       if (n < 0)
452         return NULL;
453
454       endp = result + n - 1;
455     }
456   else
457     {
458       /* This is a user path.  Please note the additional byte in the
459          memory allocation.  */
460       size_t len = strlen (path) + 1;
461       result = xmalloc (len + 1);
462       endp = mempcpy (result, path, len) - 1;
463
464       /* If the user specified an output path we cannot add the output
465          to the archive.  */
466       no_archive = true;
467     }
468
469   errno = 0;
470
471   if (no_archive && euidaccess (result, W_OK) == -1)
472     /* Perhaps the directory does not exist now.  Try to create it.  */
473     if (errno == ENOENT)
474       {
475         errno = 0;
476         if (mkdir (result, 0777) < 0)
477           return NULL;
478       }
479
480   *endp++ = '/';
481   *endp = '\0';
482
483   return result;
484 }
485
486
487 /* Normalize codeset name.  There is no standard for the codeset
488    names.  Normalization allows the user to use any of the common
489    names.  */
490 static const char *
491 normalize_codeset (codeset, name_len)
492      const char *codeset;
493      size_t name_len;
494 {
495   int len = 0;
496   int only_digit = 1;
497   char *retval;
498   char *wp;
499   size_t cnt;
500
501   for (cnt = 0; cnt < name_len; ++cnt)
502     if (isalnum (codeset[cnt]))
503       {
504         ++len;
505
506         if (isalpha (codeset[cnt]))
507           only_digit = 0;
508       }
509
510   retval = (char *) malloc ((only_digit ? 3 : 0) + len + 1);
511
512   if (retval != NULL)
513     {
514       if (only_digit)
515         wp = stpcpy (retval, "iso");
516       else
517         wp = retval;
518
519       for (cnt = 0; cnt < name_len; ++cnt)
520         if (isalpha (codeset[cnt]))
521           *wp++ = tolower (codeset[cnt]);
522         else if (isdigit (codeset[cnt]))
523           *wp++ = codeset[cnt];
524
525       *wp = '\0';
526     }
527
528   return (const char *) retval;
529 }
530
531
532 struct localedef_t *
533 add_to_readlist (int locale, const char *name, const char *repertoire_name,
534                  int generate, struct localedef_t *copy_locale)
535 {
536   struct localedef_t *runp = locales;
537
538   while (runp != NULL && strcmp (name, runp->name) != 0)
539     runp = runp->next;
540
541   if (runp == NULL)
542     {
543       /* Add a new entry at the end.  */
544       struct localedef_t *newp;
545
546       assert (generate == 1);
547
548       newp = xcalloc (1, sizeof (struct localedef_t));
549       newp->name = name;
550       newp->repertoire_name = repertoire_name;
551
552       if (locales == NULL)
553         runp = locales = newp;
554       else
555         {
556           runp = locales;
557           while (runp->next != NULL)
558             runp = runp->next;
559           runp = runp->next = newp;
560         }
561     }
562
563   if (generate
564       && (runp->needed & (1 << locale)) != 0
565       && (runp->avail & (1 << locale)) == 0)
566     WITH_CUR_LOCALE (error (5, 0, _("\
567 circular dependencies between locale definitions")));
568
569   if (copy_locale != NULL)
570     {
571       if (runp->categories[locale].generic != NULL)
572         WITH_CUR_LOCALE (error (5, 0, _("\
573 cannot add already read locale `%s' a second time"), name));
574       else
575         runp->categories[locale].generic =
576           copy_locale->categories[locale].generic;
577     }
578
579   runp->needed |= 1 << locale;
580
581   return runp;
582 }
583
584
585 struct localedef_t *
586 find_locale (int locale, const char *name, const char *repertoire_name,
587              const struct charmap_t *charmap)
588 {
589   struct localedef_t *result;
590
591   /* Find the locale, but do not generate it since this would be a bug.  */
592   result = add_to_readlist (locale, name, repertoire_name, 0, NULL);
593
594   assert (result != NULL);
595
596   if ((result->avail & (1 << locale)) == 0
597       && locfile_read (result, charmap) != 0)
598     WITH_CUR_LOCALE (error (4, errno, _("\
599 cannot open locale definition file `%s'"), result->name));
600
601   return result;
602 }
603
604
605 struct localedef_t *
606 load_locale (int locale, const char *name, const char *repertoire_name,
607              const struct charmap_t *charmap, struct localedef_t *copy_locale)
608 {
609   struct localedef_t *result;
610
611   /* Generate the locale if it does not exist.  */
612   result = add_to_readlist (locale, name, repertoire_name, 1, copy_locale);
613
614   assert (result != NULL);
615
616   if ((result->avail & (1 << locale)) == 0
617       && locfile_read (result, charmap) != 0)
618     WITH_CUR_LOCALE (error (4, errno, _("\
619 cannot open locale definition file `%s'"), result->name));
620
621   return result;
622 }
623
624 static void
625 turn_on_mcheck (void)
626 {
627   /* Enable `malloc' debugging.  */
628   mcheck (NULL);
629   /* Use the following line for a more thorough but much slower testing.  */
630   /* mcheck_pedantic (NULL); */
631 }
632
633 void (*__malloc_initialize_hook) (void) = turn_on_mcheck;