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