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