d7ad7cdac39ea18dddf0ba7ee310f647d5e47b33
[platform/upstream/m4.git] / src / m4.c
1 /* GNU m4 -- A simple macro processor
2
3    Copyright (C) 1989-1994, 2004-2011 Free Software Foundation, Inc.
4
5    This file is part of GNU M4.
6
7    GNU M4 is free software: you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation, either version 3 of the License, or
10    (at your option) any later version.
11
12    GNU M4 is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "m4.h"
22
23 #include <getopt.h>
24 #include <limits.h>
25 #include <signal.h>
26
27 #include "c-stack.h"
28 #include "ignore-value.h"
29 #include "progname.h"
30 #include "version-etc.h"
31
32 #ifdef DEBUG_STKOVF
33 # include "assert.h"
34 #endif
35
36 #define AUTHORS "Rene' Seindal"
37
38 static void usage (int) M4_GNUC_NORETURN;
39
40 /* Enable sync output for /lib/cpp (-s).  */
41 int sync_output = 0;
42
43 /* Debug (-d[flags]).  */
44 int debug_level = 0;
45
46 /* Hash table size (should be a prime) (-Hsize).  */
47 size_t hash_table_size = HASHMAX;
48
49 /* Disable GNU extensions (-G).  */
50 int no_gnu_extensions = 0;
51
52 /* Prefix all builtin functions by `m4_'.  */
53 int prefix_all_builtins = 0;
54
55 /* Max length of arguments in trace output (-lsize).  */
56 int max_debug_argument_length = 0;
57
58 /* Suppress warnings about missing arguments.  */
59 int suppress_warnings = 0;
60
61 /* If true, then warnings affect exit status.  */
62 static bool fatal_warnings = false;
63
64 /* If not zero, then value of exit status for warning diagnostics.  */
65 int warning_status = 0;
66
67 /* Artificial limit for expansion_level in macro.c.  */
68 int nesting_limit = 1024;
69
70 #ifdef ENABLE_CHANGEWORD
71 /* User provided regexp for describing m4 words.  */
72 const char *user_word_regexp = "";
73 #endif
74
75 /* Global catchall for any errors that should affect final error status, but
76    where we try to continue execution in the meantime.  */
77 int retcode;
78
79 struct macro_definition
80 {
81   struct macro_definition *next;
82   int code; /* D, U, s, t, '\1', or DEBUGFILE_OPTION.  */
83   const char *arg;
84 };
85 typedef struct macro_definition macro_definition;
86 \f
87 /* Error handling functions.  */
88
89 /*-----------------------.
90 | Wrapper around error.  |
91 `-----------------------*/
92
93 void
94 m4_error (int status, int errnum, const char *format, ...)
95 {
96   va_list args;
97   va_start (args, format);
98   verror_at_line (status, errnum, current_line ? current_file : NULL,
99                   current_line, format, args);
100   if (fatal_warnings && ! retcode)
101     retcode = EXIT_FAILURE;
102 }
103
104 /*-------------------------------.
105 | Wrapper around error_at_line.  |
106 `-------------------------------*/
107
108 void
109 m4_error_at_line (int status, int errnum, const char *file, int line,
110                   const char *format, ...)
111 {
112   va_list args;
113   va_start (args, format);
114   verror_at_line (status, errnum, line ? file : NULL, line, format, args);
115   if (fatal_warnings && ! retcode)
116     retcode = EXIT_FAILURE;
117 }
118
119 #ifndef SIGBUS
120 # define SIGBUS SIGILL
121 #endif
122
123 #ifndef NSIG
124 # ifndef MAX
125 #  define MAX(a,b) ((a) < (b) ? (b) : (a))
126 # endif
127 # define NSIG (MAX (SIGABRT, MAX (SIGILL, MAX (SIGFPE,  \
128                                                MAX (SIGSEGV, SIGBUS)))) + 1)
129 #endif
130
131 /* Pre-translated messages for program errors.  Do not translate in
132    the signal handler, since gettext and strsignal are not
133    async-signal-safe.  */
134 static const char * volatile program_error_message;
135 static const char * volatile signal_message[NSIG];
136
137 /* Print a nicer message about any programmer errors, then exit.  This
138    must be aysnc-signal safe, since it is executed as a signal
139    handler.  If SIGNO is zero, this represents a stack overflow; in
140    that case, we return to allow c_stack_action to handle things.  */
141 static void
142 fault_handler (int signo)
143 {
144   if (signo)
145     {
146       /* POSIX states that reading static memory is, in general, not
147          async-safe.  However, the static variables that we read are
148          never modified once this handler is installed, so this
149          particular usage is safe.  And it seems an oversight that
150          POSIX claims strlen is not async-safe.  Ignore write
151          failures, since we will exit with non-zero status anyway.  */
152 #define WRITE(f, b, l) ignore_value (write (f, b, l))
153       WRITE (STDERR_FILENO, program_name, strlen (program_name));
154       WRITE (STDERR_FILENO, ": ", 2);
155       WRITE (STDERR_FILENO, program_error_message,
156              strlen (program_error_message));
157       if (signal_message[signo])
158         {
159           WRITE (STDERR_FILENO, ": ", 2);
160           WRITE (STDERR_FILENO, signal_message[signo],
161                  strlen (signal_message[signo]));
162         }
163       WRITE (STDERR_FILENO, "\n", 1);
164 #undef WRITE
165       _exit (EXIT_INTERNAL_ERROR);
166     }
167 }
168 \f
169
170 /*---------------------------------------------.
171 | Print a usage message and exit with STATUS.  |
172 `---------------------------------------------*/
173
174 static void
175 usage (int status)
176 {
177   if (status != EXIT_SUCCESS)
178     xfprintf (stderr, "Try `%s --help' for more information.\n", program_name);
179   else
180     {
181       xprintf ("Usage: %s [OPTION]... [FILE]...\n", program_name);
182       fputs ("\
183 Process macros in FILEs.  If no FILE or if FILE is `-', standard input\n\
184 is read.\n\
185 ", stdout);
186       fputs ("\
187 \n\
188 Mandatory or optional arguments to long options are mandatory or optional\n\
189 for short options too.\n\
190 \n\
191 Operation modes:\n\
192       --help                   display this help and exit\n\
193       --version                output version information and exit\n\
194 ", stdout);
195       xprintf ("\
196   -E, --fatal-warnings         once: warnings become errors, twice: stop\n\
197                                  execution at first error\n\
198   -i, --interactive            unbuffer output, ignore interrupts\n\
199   -P, --prefix-builtins        force a `m4_' prefix to all builtins\n\
200   -Q, --quiet, --silent        suppress some warnings for builtins\n\
201       --warn-macro-sequence[=REGEXP]\n\
202                                warn if macro definition matches REGEXP,\n\
203                                  default %s\n\
204 ", DEFAULT_MACRO_SEQUENCE);
205 #ifdef ENABLE_CHANGEWORD
206       fputs ("\
207   -W, --word-regexp=REGEXP     use REGEXP for macro name syntax\n\
208 ", stdout);
209 #endif
210       fputs ("\
211 \n\
212 Preprocessor features:\n\
213   -D, --define=NAME[=VALUE]    define NAME as having VALUE, or empty\n\
214   -I, --include=DIRECTORY      append DIRECTORY to include path\n\
215   -s, --synclines              generate `#line NUM \"FILE\"' lines\n\
216   -U, --undefine=NAME          undefine NAME\n\
217 ", stdout);
218       puts ("");
219       xprintf (_("\
220 Limits control:\n\
221   -g, --gnu                    override -G to re-enable GNU extensions\n\
222   -G, --traditional            suppress all GNU extensions\n\
223   -H, --hashsize=PRIME         set symbol lookup hash table size [509]\n\
224   -L, --nesting-limit=NUMBER   change nesting limit, 0 for unlimited [%d]\n\
225 "), nesting_limit);
226       puts ("");
227       fputs ("\
228 Frozen state files:\n\
229   -F, --freeze-state=FILE      produce a frozen state on FILE at end\n\
230   -R, --reload-state=FILE      reload a frozen state from FILE at start\n\
231 ", stdout);
232       fputs ("\
233 \n\
234 Debugging:\n\
235   -d, --debug[=FLAGS]          set debug level (no FLAGS implies `aeq')\n\
236       --debugfile[=FILE]       redirect debug and trace output to FILE\n\
237                                  (default stderr, discard if empty string)\n\
238   -l, --arglength=NUM          restrict macro tracing size\n\
239   -t, --trace=NAME             trace NAME when it is defined\n\
240 ", stdout);
241       fputs ("\
242 \n\
243 FLAGS is any of:\n\
244   a   show actual arguments\n\
245   c   show before collect, after collect and after call\n\
246   e   show expansion\n\
247   f   say current input file name\n\
248   i   show changes in input files\n\
249   l   say current input line number\n\
250   p   show results of path searches\n\
251   q   quote values as necessary, with a or e flag\n\
252   t   trace for all macro calls, not only traceon'ed\n\
253   x   add a unique macro call id, useful with c flag\n\
254   V   shorthand for all of the above flags\n\
255 ", stdout);
256       fputs ("\
257 \n\
258 If defined, the environment variable `M4PATH' is a colon-separated list\n\
259 of directories included after any specified by `-I'.\n\
260 ", stdout);
261       fputs ("\
262 \n\
263 Exit status is 0 for success, 1 for failure, 63 for frozen file version\n\
264 mismatch, or whatever value was passed to the m4exit macro.\n\
265 ", stdout);
266       emit_bug_reporting_address ();
267     }
268   exit (status);
269 }
270
271 /*--------------------------------------.
272 | Decode options and launch execution.  |
273 `--------------------------------------*/
274
275 /* For long options that have no equivalent short option, use a
276    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
277 enum
278 {
279   DEBUGFILE_OPTION = CHAR_MAX + 1,      /* no short opt */
280   DIVERSIONS_OPTION,                    /* not quite -N, because of message */
281   WARN_MACRO_SEQUENCE_OPTION,           /* no short opt */
282
283   HELP_OPTION,                          /* no short opt */
284   VERSION_OPTION                        /* no short opt */
285 };
286
287 static const struct option long_options[] =
288 {
289   {"arglength", required_argument, NULL, 'l'},
290   {"debug", optional_argument, NULL, 'd'},
291   {"define", required_argument, NULL, 'D'},
292   {"error-output", required_argument, NULL, 'o'}, /* FIXME: deprecate in 2.0 */
293   {"fatal-warnings", no_argument, NULL, 'E'},
294   {"freeze-state", required_argument, NULL, 'F'},
295   {"gnu", no_argument, NULL, 'g'},
296   {"hashsize", required_argument, NULL, 'H'},
297   {"include", required_argument, NULL, 'I'},
298   {"interactive", no_argument, NULL, 'i'},
299   {"nesting-limit", required_argument, NULL, 'L'},
300   {"prefix-builtins", no_argument, NULL, 'P'},
301   {"quiet", no_argument, NULL, 'Q'},
302   {"reload-state", required_argument, NULL, 'R'},
303   {"silent", no_argument, NULL, 'Q'},
304   {"synclines", no_argument, NULL, 's'},
305   {"trace", required_argument, NULL, 't'},
306   {"traditional", no_argument, NULL, 'G'},
307   {"undefine", required_argument, NULL, 'U'},
308   {"word-regexp", required_argument, NULL, 'W'},
309
310   {"debugfile", optional_argument, NULL, DEBUGFILE_OPTION},
311   {"diversions", required_argument, NULL, DIVERSIONS_OPTION},
312   {"warn-macro-sequence", optional_argument, NULL, WARN_MACRO_SEQUENCE_OPTION},
313
314   {"help", no_argument, NULL, HELP_OPTION},
315   {"version", no_argument, NULL, VERSION_OPTION},
316
317   { NULL, 0, NULL, 0 },
318 };
319
320 /* Process a command line file NAME, and return true only if it was
321    stdin.  */
322 static void
323 process_file (const char *name)
324 {
325   if (STREQ (name, "-"))
326     {
327       /* If stdin is a terminal, we want to allow 'm4 - file -'
328          to read input from stdin twice, like GNU cat.  Besides,
329          there is no point closing stdin before wrapped text, to
330          minimize bugs in syscmd called from wrapped text.  */
331       push_file (stdin, "stdin", false);
332     }
333   else
334     {
335       char *full_name;
336       FILE *fp = m4_path_search (name, &full_name);
337       if (fp == NULL)
338         {
339           error (0, errno, _("cannot open `%s'"), name);
340           /* Set the status to EXIT_FAILURE, even though we
341              continue to process files after a missing file.  */
342           retcode = EXIT_FAILURE;
343           return;
344         }
345       push_file (fp, full_name, true);
346       free (full_name);
347     }
348   expand_input ();
349 }
350
351 /* POSIX requires only -D, -U, and -s; and says that the first two
352    must be recognized when interspersed with file names.  Traditional
353    behavior also handles -s between files.  Starting OPTSTRING with
354    '-' forces getopt_long to hand back file names as arguments to opt
355    '\1', rather than reordering the command line.  */
356 #ifdef ENABLE_CHANGEWORD
357 #define OPTSTRING "-B:D:EF:GH:I:L:N:PQR:S:T:U:W:d::egil:o:st:"
358 #else
359 #define OPTSTRING "-B:D:EF:GH:I:L:N:PQR:S:T:U:d::egil:o:st:"
360 #endif
361
362 int
363 main (int argc, char *const *argv)
364 {
365   struct sigaction act;
366   macro_definition *head;       /* head of deferred argument list */
367   macro_definition *tail;
368   macro_definition *defn;
369   int optchar;                  /* option character */
370
371   macro_definition *defines;
372   bool interactive = false;
373   bool seen_file = false;
374   const char *debugfile = NULL;
375   const char *frozen_file_to_read = NULL;
376   const char *frozen_file_to_write = NULL;
377   const char *macro_sequence = "";
378
379   set_program_name (argv[0]);
380   retcode = EXIT_SUCCESS;
381   atexit (close_stdin);
382
383   include_init ();
384   debug_init ();
385
386   /* Stack overflow and program error handling.  Ignore failure to
387      install a handler, since this is merely for improved output on
388      crash, and we should never crash ;).  We install SIGBUS and
389      SIGSEGV handlers prior to using the c-stack module; depending on
390      the platform, c-stack will then override none, SIGSEGV, or both
391      handlers.  */
392   program_error_message
393     = xasprintf (_("internal error detected; please report this bug to <%s>"),
394                  PACKAGE_BUGREPORT);
395   signal_message[SIGSEGV] = xstrdup (strsignal (SIGSEGV));
396   signal_message[SIGABRT] = xstrdup (strsignal (SIGABRT));
397   signal_message[SIGILL] = xstrdup (strsignal (SIGILL));
398   signal_message[SIGFPE] = xstrdup (strsignal (SIGFPE));
399   if (SIGBUS != SIGILL && SIGBUS != SIGSEGV)
400     signal_message[SIGBUS] = xstrdup (strsignal (SIGBUS));
401   sigemptyset (&act.sa_mask);
402   /* One-shot - if we fault while handling a fault, we want to revert
403      to default signal behavior.  */
404   act.sa_flags = SA_NODEFER | SA_RESETHAND;
405   act.sa_handler = fault_handler;
406   sigaction (SIGSEGV, &act, NULL);
407   sigaction (SIGABRT, &act, NULL);
408   sigaction (SIGILL, &act, NULL);
409   sigaction (SIGFPE, &act, NULL);
410   sigaction (SIGBUS, &act, NULL);
411   if (c_stack_action (fault_handler) == 0)
412     nesting_limit = 0;
413
414 #ifdef DEBUG_STKOVF
415   /* Make it easier to test our fault handlers.  Exporting M4_CRASH=0
416      attempts a SIGSEGV, exporting it as 1 attempts an assertion
417      failure with a fallback to abort.  */
418   {
419     char *crash = getenv ("M4_CRASH");
420     if (crash)
421       {
422         if (!strtol (crash, NULL, 10))
423           ++*(int *) 8;
424         assert (false);
425         abort ();
426       }
427   }
428 #endif /* DEBUG_STKOVF */
429
430   /* First, we decode the arguments, to size up tables and stuff.  */
431   head = tail = NULL;
432
433   while ((optchar = getopt_long (argc, (char **) argv, OPTSTRING,
434                                  long_options, NULL)) != -1)
435     switch (optchar)
436       {
437       default:
438         usage (EXIT_FAILURE);
439
440       case 'B':
441       case 'S':
442       case 'T':
443         /* Compatibility junk: options that other implementations
444            support, but which we ignore as no-ops and don't list in
445            --help.  */
446         error (0, 0, _("warning: `m4 -%c' may be removed in a future release"),
447                optchar);
448         break;
449
450       case 'N':
451       case DIVERSIONS_OPTION:
452         /* -N became an obsolete no-op in 1.4.x.  */
453         error (0, 0, _("warning: `m4 %s' is deprecated"),
454                optchar == 'N' ? "-N" : "--diversions");
455         break;
456
457       case 'D':
458       case 'U':
459       case 's':
460       case 't':
461       case '\1':
462       case DEBUGFILE_OPTION:
463         /* Arguments that cannot be handled until later are accumulated.  */
464
465         defn = (macro_definition *) xmalloc (sizeof (macro_definition));
466         defn->code = optchar;
467         defn->arg = optarg;
468         defn->next = NULL;
469
470         if (head == NULL)
471           head = defn;
472         else
473           tail->next = defn;
474         tail = defn;
475
476         break;
477
478       case 'E':
479         if (! fatal_warnings)
480           fatal_warnings = true;
481         else
482           warning_status = EXIT_FAILURE;
483         break;
484
485       case 'F':
486         frozen_file_to_write = optarg;
487         break;
488
489       case 'G':
490         no_gnu_extensions = 1;
491         break;
492
493       case 'H':
494         hash_table_size = strtol (optarg, NULL, 10);
495         if (hash_table_size == 0)
496           hash_table_size = HASHMAX;
497         break;
498
499       case 'I':
500         add_include_directory (optarg);
501         break;
502
503       case 'L':
504         nesting_limit = strtol (optarg, NULL, 10);
505         break;
506
507       case 'P':
508         prefix_all_builtins = 1;
509         break;
510
511       case 'Q':
512         suppress_warnings = 1;
513         break;
514
515       case 'R':
516         frozen_file_to_read = optarg;
517         break;
518
519 #ifdef ENABLE_CHANGEWORD
520       case 'W':
521         user_word_regexp = optarg;
522         break;
523 #endif
524
525       case 'd':
526         debug_level = debug_decode (optarg);
527         if (debug_level < 0)
528           {
529             error (0, 0, _("bad debug flags: `%s'"), optarg);
530             debug_level = 0;
531           }
532         break;
533
534       case 'e':
535         error (0, 0, _("warning: `m4 -e' is deprecated, use `-i' instead"));
536         /* fall through */
537       case 'i':
538         interactive = true;
539         break;
540
541       case 'g':
542         no_gnu_extensions = 0;
543         break;
544
545       case 'l':
546         max_debug_argument_length = strtol (optarg, NULL, 10);
547         if (max_debug_argument_length <= 0)
548           max_debug_argument_length = 0;
549         break;
550
551       case 'o':
552         /* -o/--error-output are deprecated synonyms of --debugfile,
553            but don't issue a deprecation warning until autoconf 2.61
554            or later is more widely established, as such a warning
555            would interfere with all earlier versions of autoconf.  */
556         /* Don't call debug_set_output here, as it has side effects.  */
557         debugfile = optarg;
558         break;
559
560       case WARN_MACRO_SEQUENCE_OPTION:
561          /* Don't call set_macro_sequence here, as it can exit.
562             --warn-macro-sequence sets optarg to NULL (which uses the
563             default regexp); --warn-macro-sequence= sets optarg to ""
564             (which disables these warnings).  */
565         macro_sequence = optarg;
566         break;
567
568       case VERSION_OPTION:
569         version_etc (stdout, PACKAGE, PACKAGE_NAME, VERSION, AUTHORS, NULL);
570         exit (EXIT_SUCCESS);
571         break;
572
573       case HELP_OPTION:
574         usage (EXIT_SUCCESS);
575         break;
576       }
577
578   defines = head;
579
580   /* Do the basic initializations.  */
581   if (debugfile && !debug_set_output (debugfile))
582     M4ERROR ((warning_status, errno, "cannot set debug file `%s'", debugfile));
583
584   input_init ();
585   output_init ();
586   symtab_init ();
587   set_macro_sequence (macro_sequence);
588   include_env_init ();
589
590   if (frozen_file_to_read)
591     reload_frozen_state (frozen_file_to_read);
592   else
593     builtin_init ();
594
595   /* Interactive mode means unbuffered output, and interrupts ignored.  */
596
597   if (interactive)
598     {
599       signal (SIGINT, SIG_IGN);
600       setbuf (stdout, (char *) NULL);
601     }
602
603   /* Handle deferred command line macro definitions.  Must come after
604      initialization of the symbol table.  */
605
606   while (defines != NULL)
607     {
608       macro_definition *next;
609       symbol *sym;
610
611       switch (defines->code)
612         {
613         case 'D':
614           {
615             /* defines->arg is read-only, so we need a copy.  */
616             char *macro_name = xstrdup (defines->arg);
617             char *macro_value = strchr (macro_name, '=');
618             if (macro_value)
619               *macro_value++ = '\0';
620             define_user_macro (macro_name, macro_value, SYMBOL_INSERT);
621             free (macro_name);
622           }
623           break;
624
625         case 'U':
626           lookup_symbol (defines->arg, SYMBOL_DELETE);
627           break;
628
629         case 't':
630           sym = lookup_symbol (defines->arg, SYMBOL_INSERT);
631           SYMBOL_TRACED (sym) = true;
632           break;
633
634         case 's':
635           sync_output = 1;
636           break;
637
638         case '\1':
639           seen_file = true;
640           process_file (defines->arg);
641           break;
642
643         case DEBUGFILE_OPTION:
644           if (!debug_set_output (defines->arg))
645             M4ERROR ((warning_status, errno, "cannot set debug file `%s'",
646                       debugfile ? debugfile : _("stderr")));
647           break;
648
649         default:
650           M4ERROR ((0, 0, "INTERNAL ERROR: bad code in deferred arguments"));
651           abort ();
652         }
653
654       next = defines->next;
655       free (defines);
656       defines = next;
657     }
658
659   /* Handle remaining input files.  Each file is pushed on the input,
660      and the input read.  Wrapup text is handled separately later.  */
661
662   if (optind == argc && !seen_file)
663     process_file ("-");
664   else
665     for (; optind < argc; optind++)
666       process_file (argv[optind]);
667
668   /* Now handle wrapup text.  */
669
670   while (pop_wrapup ())
671     expand_input ();
672
673   /* Change debug stream back to stderr, to force flushing the debug
674      stream and detect any errors it might have encountered.  The
675      three standard streams are closed by close_stdin.  */
676   debug_set_output (NULL);
677
678   if (frozen_file_to_write)
679     produce_frozen_state (frozen_file_to_write);
680   else
681     {
682       make_diversion (0);
683       undivert_all ();
684     }
685   output_exit ();
686   free_macro_sequence ();
687   exit (retcode);
688 }