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