1 /* GNU m4 -- A simple macro processor
3 Copyright (C) 1989-1994, 2004-2014, 2016-2017, 2020-2021 Free
4 Software Foundation, Inc.
6 This file is part of GNU M4.
8 GNU M4 is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU M4 is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <https://www.gnu.org/licenses/>.
29 #include "configmake.h"
30 #include "ignore-value.h"
32 #include "propername.h"
33 #include "version-etc.h"
39 /* TRANSLATORS: This is a non-ASCII name: The first name is (with
40 Unicode escapes) "Ren\u00e9" or (with HTML entities) "René". */
41 #define AUTHORS proper_name_utf8 ("Rene' Seindal", "Ren\xC3\xA9 Seindal")
43 static _Noreturn void usage (int);
45 /* Enable sync output for /lib/cpp (-s). */
48 /* Debug (-d[flags]). */
51 /* Hash table size (should be a prime) (-Hsize). */
52 size_t hash_table_size = HASHMAX;
54 /* Disable GNU extensions (-G). */
55 int no_gnu_extensions = 0;
57 /* Prefix all builtin functions by `m4_'. */
58 int prefix_all_builtins = 0;
60 /* Max length of arguments in trace output (-lsize). */
61 int max_debug_argument_length = 0;
63 /* Suppress warnings about missing arguments. */
64 int suppress_warnings = 0;
66 /* If true, then warnings affect exit status. */
67 static bool fatal_warnings = false;
69 /* If not zero, then value of exit status for warning diagnostics. */
70 int warning_status = 0;
72 /* Artificial limit for expansion_level in macro.c. */
73 int nesting_limit = 1024;
75 #ifdef ENABLE_CHANGEWORD
76 /* User provided regexp for describing m4 words. */
77 const char *user_word_regexp = "";
80 /* Global catchall for any errors that should affect final error status, but
81 where we try to continue execution in the meantime. */
84 struct macro_definition
86 struct macro_definition *next;
87 int code; /* D, U, s, t, '\1', or DEBUGFILE_OPTION. */
90 typedef struct macro_definition macro_definition;
92 /* Error handling functions. */
94 /*-----------------------.
95 | Wrapper around error. |
96 `-----------------------*/
99 m4_error (int status, int errnum, const char *format, ...)
102 va_start (args, format);
103 verror_at_line (status, errnum, current_line ? current_file : NULL,
104 current_line, format, args);
105 if (fatal_warnings && ! retcode)
106 retcode = EXIT_FAILURE;
111 m4_failure (int errnum, const char *format, ...)
114 va_start (args, format);
115 verror_at_line (EXIT_FAILURE, errnum, current_line ? current_file : NULL,
116 current_line, format, args);
120 /*-------------------------------.
121 | Wrapper around error_at_line. |
122 `-------------------------------*/
125 m4_error_at_line (int status, int errnum, const char *file, int line,
126 const char *format, ...)
129 va_start (args, format);
130 verror_at_line (status, errnum, line ? file : NULL, line, format, args);
131 if (fatal_warnings && ! retcode)
132 retcode = EXIT_FAILURE;
137 m4_failure_at_line (int errnum, const char *file, int line,
138 const char *format, ...)
141 va_start (args, format);
142 verror_at_line (EXIT_FAILURE, errnum, line ? file : NULL,
148 # define SIGBUS SIGILL
153 # define MAX(a,b) ((a) < (b) ? (b) : (a))
155 # define NSIG (MAX (SIGABRT, MAX (SIGILL, MAX (SIGFPE, \
156 MAX (SIGSEGV, SIGBUS)))) + 1)
159 /* Pre-translated messages for program errors. Do not translate in
160 the signal handler, since gettext and strsignal are not
161 async-signal-safe. */
162 static const char * volatile program_error_message;
163 static const char * volatile signal_message[NSIG];
165 /* Print a nicer message about any programmer errors, then exit. This
166 must be aysnc-signal safe, since it is executed as a signal
167 handler. If SIGNO is zero, this represents a stack overflow; in
168 that case, we return to allow c_stack_action to handle things. */
170 fault_handler (int signo)
174 /* POSIX states that reading static memory is, in general, not
175 async-safe. However, the static variables that we read are
176 never modified once this handler is installed, so this
177 particular usage is safe. And it seems an oversight that
178 POSIX claims strlen is not async-safe. Ignore write
179 failures, since we will exit with non-zero status anyway. */
180 #define WRITE(f, b, l) ignore_value (write (f, b, l))
181 WRITE (STDERR_FILENO, program_name, strlen (program_name));
182 WRITE (STDERR_FILENO, ": ", 2);
183 WRITE (STDERR_FILENO, program_error_message,
184 strlen (program_error_message));
185 if (signal_message[signo])
187 WRITE (STDERR_FILENO, ": ", 2);
188 WRITE (STDERR_FILENO, signal_message[signo],
189 strlen (signal_message[signo]));
191 WRITE (STDERR_FILENO, "\n", 1);
193 _exit (EXIT_INTERNAL_ERROR);
198 /*---------------------------------------------.
199 | Print a usage message and exit with STATUS. |
200 `---------------------------------------------*/
205 if (status != EXIT_SUCCESS)
207 xfprintf (stderr, _("Try `%s --help' for more information."),
209 fputs ("\n", stderr);
213 xprintf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
215 Process macros in FILEs. If no FILE or if FILE is `-', standard input\n\
220 Mandatory or optional arguments to long options are mandatory or optional\n\
221 for short options too.\n\
226 --help display this help and exit\n\
227 --version output version information and exit\n\
230 -E, --fatal-warnings once: warnings become errors, twice: stop\n\
231 execution at first error\n\
232 -i, --interactive unbuffer output, ignore interrupts\n\
233 -P, --prefix-builtins force a `m4_' prefix to all builtins\n\
234 -Q, --quiet, --silent suppress some warnings for builtins\n\
237 --warn-macro-sequence[=REGEXP]\n\
238 warn if macro definition matches REGEXP,\n\
240 "), DEFAULT_MACRO_SEQUENCE);
241 #ifdef ENABLE_CHANGEWORD
243 -W, --word-regexp=REGEXP use REGEXP for macro name syntax\n\
248 Preprocessor features:\n\
249 -D, --define=NAME[=VALUE] define NAME as having VALUE, or empty\n\
250 -I, --include=DIRECTORY append DIRECTORY to include path\n\
251 -s, --synclines generate `#line NUM \"FILE\"' lines\n\
252 -U, --undefine=NAME undefine NAME\n\
257 -g, --gnu override -G to re-enable GNU extensions\n\
258 -G, --traditional suppress all GNU extensions\n\
259 -H, --hashsize=PRIME set symbol lookup hash table size [509]\n\
260 -L, --nesting-limit=NUMBER change nesting limit, 0 for unlimited [%d]\n\
264 Frozen state files:\n\
265 -F, --freeze-state=FILE produce a frozen state on FILE at end\n\
266 -R, --reload-state=FILE reload a frozen state from FILE at start\n\
271 -d, --debug[=FLAGS] set debug level (no FLAGS implies `aeq')\n\
272 --debugfile[=FILE] redirect debug and trace output to FILE\n\
273 (default stderr, discard if empty string)\n\
274 -l, --arglength=NUM restrict macro tracing size\n\
275 -t, --trace=NAME trace NAME when it is defined\n\
280 a show actual arguments\n\
281 c show before collect, after collect and after call\n\
283 f say current input file name\n\
284 i show changes in input files\n\
287 l say current input line number\n\
288 p show results of path searches\n\
289 q quote values as necessary, with a or e flag\n\
290 t trace for all macro calls, not only traceon'ed\n\
291 x add a unique macro call id, useful with c flag\n\
292 V shorthand for all of the above flags\n\
296 If defined, the environment variable `M4PATH' is a colon-separated list\n\
297 of directories included after any specified by `-I'.\n\
301 Exit status is 0 for success, 1 for failure, 63 for frozen file version\n\
302 mismatch, or whatever value was passed to the m4exit macro.\n\
304 emit_bug_reporting_address ();
309 /*--------------------------------------.
310 | Decode options and launch execution. |
311 `--------------------------------------*/
313 /* For long options that have no equivalent short option, use a
314 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
317 DEBUGFILE_OPTION = CHAR_MAX + 1, /* no short opt */
318 DIVERSIONS_OPTION, /* not quite -N, because of message */
319 WARN_MACRO_SEQUENCE_OPTION, /* no short opt */
321 HELP_OPTION, /* no short opt */
322 VERSION_OPTION /* no short opt */
325 static const struct option long_options[] =
327 {"arglength", required_argument, NULL, 'l'},
328 {"debug", optional_argument, NULL, 'd'},
329 {"define", required_argument, NULL, 'D'},
330 {"error-output", required_argument, NULL, 'o'}, /* FIXME: deprecate in 2.0 */
331 {"fatal-warnings", no_argument, NULL, 'E'},
332 {"freeze-state", required_argument, NULL, 'F'},
333 {"gnu", no_argument, NULL, 'g'},
334 {"hashsize", required_argument, NULL, 'H'},
335 {"include", required_argument, NULL, 'I'},
336 {"interactive", no_argument, NULL, 'i'},
337 {"nesting-limit", required_argument, NULL, 'L'},
338 {"prefix-builtins", no_argument, NULL, 'P'},
339 {"quiet", no_argument, NULL, 'Q'},
340 {"reload-state", required_argument, NULL, 'R'},
341 {"silent", no_argument, NULL, 'Q'},
342 {"synclines", no_argument, NULL, 's'},
343 {"trace", required_argument, NULL, 't'},
344 {"traditional", no_argument, NULL, 'G'},
345 {"undefine", required_argument, NULL, 'U'},
346 #ifdef ENABLE_CHANGEWORD
347 {"word-regexp", required_argument, NULL, 'W'},
350 {"debugfile", optional_argument, NULL, DEBUGFILE_OPTION},
351 {"diversions", required_argument, NULL, DIVERSIONS_OPTION},
352 {"warn-macro-sequence", optional_argument, NULL, WARN_MACRO_SEQUENCE_OPTION},
354 {"help", no_argument, NULL, HELP_OPTION},
355 {"version", no_argument, NULL, VERSION_OPTION},
357 { NULL, 0, NULL, 0 },
360 /* Process a command line file NAME, and return true only if it was
363 process_file (const char *name)
365 if (STREQ (name, "-"))
367 /* If stdin is a terminal, we want to allow 'm4 - file -'
368 to read input from stdin twice, like GNU cat. Besides,
369 there is no point closing stdin before wrapped text, to
370 minimize bugs in syscmd called from wrapped text. */
371 push_file (stdin, "stdin", false);
376 FILE *fp = m4_path_search (name, &full_name);
379 error (0, errno, _("cannot open `%s'"), name);
380 /* Set the status to EXIT_FAILURE, even though we
381 continue to process files after a missing file. */
382 retcode = EXIT_FAILURE;
385 push_file (fp, full_name, true);
391 /* POSIX requires only -D, -U, and -s; and says that the first two
392 must be recognized when interspersed with file names. Traditional
393 behavior also handles -s between files. Starting OPTSTRING with
394 '-' forces getopt_long to hand back file names as arguments to opt
395 '\1', rather than reordering the command line. */
396 #ifdef ENABLE_CHANGEWORD
397 #define OPTSTRING "-B:D:EF:GH:I:L:N:PQR:S:T:U:W:d::egil:o:st:"
399 #define OPTSTRING "-B:D:EF:GH:I:L:N:PQR:S:T:U:d::egil:o:st:"
403 main (int argc, char *const *argv)
405 struct sigaction act;
406 macro_definition *head; /* head of deferred argument list */
407 macro_definition *tail;
408 macro_definition *defn;
409 int optchar; /* option character */
411 macro_definition *defines;
412 bool interactive = false;
413 bool seen_file = false;
414 const char *debugfile = NULL;
415 const char *frozen_file_to_read = NULL;
416 const char *frozen_file_to_write = NULL;
417 const char *macro_sequence = "";
419 set_program_name (argv[0]);
420 retcode = EXIT_SUCCESS;
421 setlocale (LC_ALL, "");
422 bindtextdomain (PACKAGE, LOCALEDIR);
423 textdomain (PACKAGE);
424 atexit (close_stdin);
429 /* Stack overflow and program error handling. Ignore failure to
430 install a handler, since this is merely for improved output on
431 crash, and we should never crash ;). We install SIGBUS and
432 SIGSEGV handlers prior to using the c-stack module; depending on
433 the platform, c-stack will then override none, SIGSEGV, or both
435 program_error_message
436 = xasprintf (_("internal error detected; please report this bug to <%s>"),
438 signal_message[SIGSEGV] = xstrdup (strsignal (SIGSEGV));
439 signal_message[SIGABRT] = xstrdup (strsignal (SIGABRT));
440 signal_message[SIGILL] = xstrdup (strsignal (SIGILL));
441 signal_message[SIGFPE] = xstrdup (strsignal (SIGFPE));
442 if (SIGBUS != SIGILL && SIGBUS != SIGSEGV)
443 signal_message[SIGBUS] = xstrdup (strsignal (SIGBUS));
444 sigemptyset (&act.sa_mask);
445 /* One-shot - if we fault while handling a fault, we want to revert
446 to default signal behavior. */
447 act.sa_flags = SA_NODEFER | SA_RESETHAND;
448 act.sa_handler = fault_handler;
449 sigaction (SIGSEGV, &act, NULL);
450 sigaction (SIGABRT, &act, NULL);
451 sigaction (SIGILL, &act, NULL);
452 sigaction (SIGFPE, &act, NULL);
453 sigaction (SIGBUS, &act, NULL);
454 if (c_stack_action (fault_handler) == 0)
458 /* Make it easier to test our fault handlers. Exporting M4_CRASH=0
459 attempts a SIGSEGV, exporting it as 1 attempts an assertion
460 failure with a fallback to abort. */
462 char *crash = getenv ("M4_CRASH");
465 if (!strtol (crash, NULL, 10))
471 #endif /* DEBUG_STKOVF */
473 /* First, we decode the arguments, to size up tables and stuff. */
476 while ((optchar = getopt_long (argc, (char **) argv, OPTSTRING,
477 long_options, NULL)) != -1)
481 usage (EXIT_FAILURE);
486 /* Compatibility junk: options that other implementations
487 support, but which we ignore as no-ops and don't list in
489 error (0, 0, _("warning: `m4 -%c' may be removed in a future release"),
494 case DIVERSIONS_OPTION:
495 /* -N became an obsolete no-op in 1.4.x. */
496 error (0, 0, _("warning: `m4 %s' is deprecated"),
497 optchar == 'N' ? "-N" : "--diversions");
505 case DEBUGFILE_OPTION:
506 /* Arguments that cannot be handled until later are accumulated. */
508 defn = (macro_definition *) xmalloc (sizeof (macro_definition));
509 defn->code = optchar;
522 if (! fatal_warnings)
523 fatal_warnings = true;
525 warning_status = EXIT_FAILURE;
529 frozen_file_to_write = optarg;
533 no_gnu_extensions = 1;
537 hash_table_size = strtol (optarg, NULL, 10);
538 if (hash_table_size == 0)
539 hash_table_size = HASHMAX;
543 add_include_directory (optarg);
547 nesting_limit = strtol (optarg, NULL, 10);
551 prefix_all_builtins = 1;
555 suppress_warnings = 1;
559 frozen_file_to_read = optarg;
562 #ifdef ENABLE_CHANGEWORD
564 user_word_regexp = optarg;
569 debug_level = debug_decode (optarg);
572 error (0, 0, _("bad debug flags: `%s'"), optarg);
578 error (0, 0, _("warning: `m4 -e' is deprecated, use `-i' instead"));
585 no_gnu_extensions = 0;
589 max_debug_argument_length = strtol (optarg, NULL, 10);
590 if (max_debug_argument_length <= 0)
591 max_debug_argument_length = 0;
595 /* -o/--error-output are deprecated synonyms of --debugfile,
596 but don't issue a deprecation warning until autoconf 2.61
597 or later is more widely established, as such a warning
598 would interfere with all earlier versions of autoconf. */
599 /* Don't call debug_set_output here, as it has side effects. */
603 case WARN_MACRO_SEQUENCE_OPTION:
604 /* Don't call set_macro_sequence here, as it can exit.
605 --warn-macro-sequence sets optarg to NULL (which uses the
606 default regexp); --warn-macro-sequence= sets optarg to ""
607 (which disables these warnings). */
608 macro_sequence = optarg;
612 version_etc (stdout, PACKAGE, PACKAGE_NAME, VERSION, AUTHORS, NULL);
617 usage (EXIT_SUCCESS);
623 /* Do the basic initializations. */
624 if (debugfile && !debug_set_output (debugfile))
625 M4ERROR ((warning_status, errno, _("cannot set debug file `%s'"),
631 set_macro_sequence (macro_sequence);
634 if (frozen_file_to_read)
635 reload_frozen_state (frozen_file_to_read);
639 /* Interactive mode means unbuffered output, and interrupts ignored. */
643 signal (SIGINT, SIG_IGN);
644 setbuf (stdout, (char *) NULL);
647 /* Handle deferred command line macro definitions. Must come after
648 initialization of the symbol table. */
650 while (defines != NULL)
652 macro_definition *next;
655 switch (defines->code)
659 /* defines->arg is read-only, so we need a copy. */
660 char *macro_name = xstrdup (defines->arg);
661 char *macro_value = strchr (macro_name, '=');
663 *macro_value++ = '\0';
664 define_user_macro (macro_name, macro_value, SYMBOL_INSERT);
670 lookup_symbol (defines->arg, SYMBOL_DELETE);
674 sym = lookup_symbol (defines->arg, SYMBOL_INSERT);
675 SYMBOL_TRACED (sym) = true;
684 process_file (defines->arg);
687 case DEBUGFILE_OPTION:
688 if (!debug_set_output (defines->arg))
689 M4ERROR ((warning_status, errno, _("cannot set debug file `%s'"),
690 debugfile ? debugfile : _("stderr")));
694 M4ERROR ((0, 0, "INTERNAL ERROR: bad code in deferred arguments"));
698 next = defines->next;
703 /* Handle remaining input files. Each file is pushed on the input,
704 and the input read. Wrapup text is handled separately later. */
706 if (optind == argc && !seen_file)
709 for (; optind < argc; optind++)
710 process_file (argv[optind]);
712 /* Now handle wrapup text. */
714 while (pop_wrapup ())
717 /* Change debug stream back to stderr, to force flushing the debug
718 stream and detect any errors it might have encountered. The
719 three standard streams are closed by close_stdin. */
720 debug_set_output (NULL);
722 if (frozen_file_to_write)
723 produce_frozen_state (frozen_file_to_write);
730 free_macro_sequence ();