1 /* GNU m4 -- A simple macro processor
3 Copyright (C) 1989-1994, 2004-2013 Free Software Foundation, Inc.
5 This file is part of GNU M4.
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.
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.
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/>.
28 #include "ignore-value.h"
30 #include "version-etc.h"
36 #define AUTHORS "Rene' Seindal"
38 static void usage (int) M4_GNUC_NORETURN;
40 /* Enable sync output for /lib/cpp (-s). */
43 /* Debug (-d[flags]). */
46 /* Hash table size (should be a prime) (-Hsize). */
47 size_t hash_table_size = HASHMAX;
49 /* Disable GNU extensions (-G). */
50 int no_gnu_extensions = 0;
52 /* Prefix all builtin functions by `m4_'. */
53 int prefix_all_builtins = 0;
55 /* Max length of arguments in trace output (-lsize). */
56 int max_debug_argument_length = 0;
58 /* Suppress warnings about missing arguments. */
59 int suppress_warnings = 0;
61 /* If true, then warnings affect exit status. */
62 static bool fatal_warnings = false;
64 /* If not zero, then value of exit status for warning diagnostics. */
65 int warning_status = 0;
67 /* Artificial limit for expansion_level in macro.c. */
68 int nesting_limit = 1024;
70 #ifdef ENABLE_CHANGEWORD
71 /* User provided regexp for describing m4 words. */
72 const char *user_word_regexp = "";
75 /* Global catchall for any errors that should affect final error status, but
76 where we try to continue execution in the meantime. */
79 struct macro_definition
81 struct macro_definition *next;
82 int code; /* D, U, s, t, '\1', or DEBUGFILE_OPTION. */
85 typedef struct macro_definition macro_definition;
87 /* Error handling functions. */
89 /*-----------------------.
90 | Wrapper around error. |
91 `-----------------------*/
94 m4_error (int status, int errnum, const char *format, ...)
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;
105 /*-------------------------------.
106 | Wrapper around error_at_line. |
107 `-------------------------------*/
110 m4_error_at_line (int status, int errnum, const char *file, int line,
111 const char *format, ...)
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;
122 # define SIGBUS SIGILL
127 # define MAX(a,b) ((a) < (b) ? (b) : (a))
129 # define NSIG (MAX (SIGABRT, MAX (SIGILL, MAX (SIGFPE, \
130 MAX (SIGSEGV, SIGBUS)))) + 1)
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];
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)
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])
161 WRITE (STDERR_FILENO, ": ", 2);
162 WRITE (STDERR_FILENO, signal_message[signo],
163 strlen (signal_message[signo]));
165 WRITE (STDERR_FILENO, "\n", 1);
167 _exit (EXIT_INTERNAL_ERROR);
172 /*---------------------------------------------.
173 | Print a usage message and exit with STATUS. |
174 `---------------------------------------------*/
179 if (status != EXIT_SUCCESS)
180 xfprintf (stderr, "Try `%s --help' for more information.\n", program_name);
183 xprintf ("Usage: %s [OPTION]... [FILE]...\n", program_name);
185 Process macros in FILEs. If no FILE or if FILE is `-', standard input\n\
190 Mandatory or optional arguments to long options are mandatory or optional\n\
191 for short options too.\n\
194 --help display this help and exit\n\
195 --version output version information and exit\n\
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\
206 ", DEFAULT_MACRO_SEQUENCE);
207 #ifdef ENABLE_CHANGEWORD
209 -W, --word-regexp=REGEXP use REGEXP for macro name syntax\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\
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\
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\
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\
246 a show actual arguments\n\
247 c show before collect, after collect and after call\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\
260 If defined, the environment variable `M4PATH' is a colon-separated list\n\
261 of directories included after any specified by `-I'.\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\
268 emit_bug_reporting_address ();
273 /*--------------------------------------.
274 | Decode options and launch execution. |
275 `--------------------------------------*/
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. */
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 */
285 HELP_OPTION, /* no short opt */
286 VERSION_OPTION /* no short opt */
289 static const struct option long_options[] =
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'},
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},
316 {"help", no_argument, NULL, HELP_OPTION},
317 {"version", no_argument, NULL, VERSION_OPTION},
319 { NULL, 0, NULL, 0 },
322 /* Process a command line file NAME, and return true only if it was
325 process_file (const char *name)
327 if (STREQ (name, "-"))
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);
338 FILE *fp = m4_path_search (name, &full_name);
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;
347 push_file (fp, full_name, true);
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:"
361 #define OPTSTRING "-B:D:EF:GH:I:L:N:PQR:S:T:U:d::egil:o:st:"
365 main (int argc, char *const *argv)
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 */
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 = "";
381 set_program_name (argv[0]);
382 retcode = EXIT_SUCCESS;
383 atexit (close_stdin);
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
394 program_error_message
395 = xasprintf (_("internal error detected; please report this bug to <%s>"),
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)
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. */
421 char *crash = getenv ("M4_CRASH");
424 if (!strtol (crash, NULL, 10))
430 #endif /* DEBUG_STKOVF */
432 /* First, we decode the arguments, to size up tables and stuff. */
435 while ((optchar = getopt_long (argc, (char **) argv, OPTSTRING,
436 long_options, NULL)) != -1)
440 usage (EXIT_FAILURE);
445 /* Compatibility junk: options that other implementations
446 support, but which we ignore as no-ops and don't list in
448 error (0, 0, _("warning: `m4 -%c' may be removed in a future release"),
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");
464 case DEBUGFILE_OPTION:
465 /* Arguments that cannot be handled until later are accumulated. */
467 defn = (macro_definition *) xmalloc (sizeof (macro_definition));
468 defn->code = optchar;
481 if (! fatal_warnings)
482 fatal_warnings = true;
484 warning_status = EXIT_FAILURE;
488 frozen_file_to_write = optarg;
492 no_gnu_extensions = 1;
496 hash_table_size = strtol (optarg, NULL, 10);
497 if (hash_table_size == 0)
498 hash_table_size = HASHMAX;
502 add_include_directory (optarg);
506 nesting_limit = strtol (optarg, NULL, 10);
510 prefix_all_builtins = 1;
514 suppress_warnings = 1;
518 frozen_file_to_read = optarg;
521 #ifdef ENABLE_CHANGEWORD
523 user_word_regexp = optarg;
528 debug_level = debug_decode (optarg);
531 error (0, 0, _("bad debug flags: `%s'"), optarg);
537 error (0, 0, _("warning: `m4 -e' is deprecated, use `-i' instead"));
544 no_gnu_extensions = 0;
548 max_debug_argument_length = strtol (optarg, NULL, 10);
549 if (max_debug_argument_length <= 0)
550 max_debug_argument_length = 0;
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. */
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;
571 version_etc (stdout, PACKAGE, PACKAGE_NAME, VERSION, AUTHORS, NULL);
576 usage (EXIT_SUCCESS);
582 /* Do the basic initializations. */
583 if (debugfile && !debug_set_output (debugfile))
584 M4ERROR ((warning_status, errno, "cannot set debug file `%s'", debugfile));
589 set_macro_sequence (macro_sequence);
592 if (frozen_file_to_read)
593 reload_frozen_state (frozen_file_to_read);
597 /* Interactive mode means unbuffered output, and interrupts ignored. */
601 signal (SIGINT, SIG_IGN);
602 setbuf (stdout, (char *) NULL);
605 /* Handle deferred command line macro definitions. Must come after
606 initialization of the symbol table. */
608 while (defines != NULL)
610 macro_definition *next;
613 switch (defines->code)
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, '=');
621 *macro_value++ = '\0';
622 define_user_macro (macro_name, macro_value, SYMBOL_INSERT);
628 lookup_symbol (defines->arg, SYMBOL_DELETE);
632 sym = lookup_symbol (defines->arg, SYMBOL_INSERT);
633 SYMBOL_TRACED (sym) = true;
642 process_file (defines->arg);
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")));
652 M4ERROR ((0, 0, "INTERNAL ERROR: bad code in deferred arguments"));
656 next = defines->next;
661 /* Handle remaining input files. Each file is pushed on the input,
662 and the input read. Wrapup text is handled separately later. */
664 if (optind == argc && !seen_file)
667 for (; optind < argc; optind++)
668 process_file (argv[optind]);
670 /* Now handle wrapup text. */
672 while (pop_wrapup ())
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);
680 if (frozen_file_to_write)
681 produce_frozen_state (frozen_file_to_write);
688 free_macro_sequence ();