1 /* GNU m4 -- A simple macro processor
3 Copyright (C) 1989-1994, 2004-2011 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;
104 /*-------------------------------.
105 | Wrapper around error_at_line. |
106 `-------------------------------*/
109 m4_error_at_line (int status, int errnum, const char *file, int line,
110 const char *format, ...)
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;
120 # define SIGBUS SIGILL
125 # define MAX(a,b) ((a) < (b) ? (b) : (a))
127 # define NSIG (MAX (SIGABRT, MAX (SIGILL, MAX (SIGFPE, \
128 MAX (SIGSEGV, SIGBUS)))) + 1)
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];
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. */
142 fault_handler (int signo)
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])
159 WRITE (STDERR_FILENO, ": ", 2);
160 WRITE (STDERR_FILENO, signal_message[signo],
161 strlen (signal_message[signo]));
163 WRITE (STDERR_FILENO, "\n", 1);
165 _exit (EXIT_INTERNAL_ERROR);
170 /*---------------------------------------------.
171 | Print a usage message and exit with STATUS. |
172 `---------------------------------------------*/
177 if (status != EXIT_SUCCESS)
178 xfprintf (stderr, "Try `%s --help' for more information.\n", program_name);
181 xprintf ("Usage: %s [OPTION]... [FILE]...\n", program_name);
183 Process macros in FILEs. If no FILE or if FILE is `-', standard input\n\
188 Mandatory or optional arguments to long options are mandatory or optional\n\
189 for short options too.\n\
192 --help display this help and exit\n\
193 --version output version information and exit\n\
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\
204 ", DEFAULT_MACRO_SEQUENCE);
205 #ifdef ENABLE_CHANGEWORD
207 -W, --word-regexp=REGEXP use REGEXP for macro name syntax\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\
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\
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\
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\
244 a show actual arguments\n\
245 c show before collect, after collect and after call\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\
258 If defined, the environment variable `M4PATH' is a colon-separated list\n\
259 of directories included after any specified by `-I'.\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\
266 emit_bug_reporting_address ();
271 /*--------------------------------------.
272 | Decode options and launch execution. |
273 `--------------------------------------*/
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. */
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 */
283 HELP_OPTION, /* no short opt */
284 VERSION_OPTION /* no short opt */
287 static const struct option long_options[] =
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'},
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},
314 {"help", no_argument, NULL, HELP_OPTION},
315 {"version", no_argument, NULL, VERSION_OPTION},
317 { NULL, 0, NULL, 0 },
320 /* Process a command line file NAME, and return true only if it was
323 process_file (const char *name)
325 if (STREQ (name, "-"))
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);
336 FILE *fp = m4_path_search (name, &full_name);
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;
345 push_file (fp, full_name, true);
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:"
359 #define OPTSTRING "-B:D:EF:GH:I:L:N:PQR:S:T:U:d::egil:o:st:"
363 main (int argc, char *const *argv)
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 */
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 = "";
379 set_program_name (argv[0]);
380 retcode = EXIT_SUCCESS;
381 atexit (close_stdin);
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
392 program_error_message
393 = xasprintf (_("internal error detected; please report this bug to <%s>"),
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)
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. */
419 char *crash = getenv ("M4_CRASH");
422 if (!strtol (crash, NULL, 10))
428 #endif /* DEBUG_STKOVF */
430 /* First, we decode the arguments, to size up tables and stuff. */
433 while ((optchar = getopt_long (argc, (char **) argv, OPTSTRING,
434 long_options, NULL)) != -1)
438 usage (EXIT_FAILURE);
443 /* Compatibility junk: options that other implementations
444 support, but which we ignore as no-ops and don't list in
446 error (0, 0, _("warning: `m4 -%c' may be removed in a future release"),
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");
462 case DEBUGFILE_OPTION:
463 /* Arguments that cannot be handled until later are accumulated. */
465 defn = (macro_definition *) xmalloc (sizeof (macro_definition));
466 defn->code = optchar;
479 if (! fatal_warnings)
480 fatal_warnings = true;
482 warning_status = EXIT_FAILURE;
486 frozen_file_to_write = optarg;
490 no_gnu_extensions = 1;
494 hash_table_size = strtol (optarg, NULL, 10);
495 if (hash_table_size == 0)
496 hash_table_size = HASHMAX;
500 add_include_directory (optarg);
504 nesting_limit = strtol (optarg, NULL, 10);
508 prefix_all_builtins = 1;
512 suppress_warnings = 1;
516 frozen_file_to_read = optarg;
519 #ifdef ENABLE_CHANGEWORD
521 user_word_regexp = optarg;
526 debug_level = debug_decode (optarg);
529 error (0, 0, _("bad debug flags: `%s'"), optarg);
535 error (0, 0, _("warning: `m4 -e' is deprecated, use `-i' instead"));
542 no_gnu_extensions = 0;
546 max_debug_argument_length = strtol (optarg, NULL, 10);
547 if (max_debug_argument_length <= 0)
548 max_debug_argument_length = 0;
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. */
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;
569 version_etc (stdout, PACKAGE, PACKAGE_NAME, VERSION, AUTHORS, NULL);
574 usage (EXIT_SUCCESS);
580 /* Do the basic initializations. */
581 if (debugfile && !debug_set_output (debugfile))
582 M4ERROR ((warning_status, errno, "cannot set debug file `%s'", debugfile));
587 set_macro_sequence (macro_sequence);
590 if (frozen_file_to_read)
591 reload_frozen_state (frozen_file_to_read);
595 /* Interactive mode means unbuffered output, and interrupts ignored. */
599 signal (SIGINT, SIG_IGN);
600 setbuf (stdout, (char *) NULL);
603 /* Handle deferred command line macro definitions. Must come after
604 initialization of the symbol table. */
606 while (defines != NULL)
608 macro_definition *next;
611 switch (defines->code)
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, '=');
619 *macro_value++ = '\0';
620 define_user_macro (macro_name, macro_value, SYMBOL_INSERT);
626 lookup_symbol (defines->arg, SYMBOL_DELETE);
630 sym = lookup_symbol (defines->arg, SYMBOL_INSERT);
631 SYMBOL_TRACED (sym) = true;
640 process_file (defines->arg);
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")));
650 M4ERROR ((0, 0, "INTERNAL ERROR: bad code in deferred arguments"));
654 next = defines->next;
659 /* Handle remaining input files. Each file is pushed on the input,
660 and the input read. Wrapup text is handled separately later. */
662 if (optind == argc && !seen_file)
665 for (; optind < argc; optind++)
666 process_file (argv[optind]);
668 /* Now handle wrapup text. */
670 while (pop_wrapup ())
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);
678 if (frozen_file_to_write)
679 produce_frozen_state (frozen_file_to_write);
686 free_macro_sequence ();