1 /* $OpenBSD: main.c,v 1.87 2017/06/15 13:48:42 bcallah Exp $ */
2 /* $NetBSD: main.c,v 1.12 1997/02/08 23:54:49 cgd Exp $ */
5 * SPDX-License-Identifier: BSD-3-Clause
7 * Copyright (c) 1989, 1993
8 * The Regents of the University of California. All rights reserved.
10 * This code is derived from software contributed to Berkeley by
11 * Ozan Yigit at York University.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 * 3. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40 * Facility: m4 macro processor
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
61 #include "pathnames.h"
63 stae *mstack; /* stack of m4 machine */
64 char *sstack; /* shadow stack, for string space extension */
65 static size_t STACKMAX; /* current maximum size of stack */
66 int sp; /* current m4 stack pointer */
67 int fp; /* m4 call frame pointer */
68 struct input_file infile[MAXINP];/* input file stack (0=stdin) */
69 FILE **outfile; /* diversion array(0=bitbucket)*/
71 FILE *active; /* active output file pointer */
72 int ilevel = 0; /* input file stack pointer */
73 int oindex = 0; /* diversion index.. */
74 const char *null = ""; /* as it says.. just a null.. */
75 char **m4wraps = NULL; /* m4wraps array. */
76 int maxwraps = 0; /* size of m4wraps array */
77 int wrapindex = 0; /* current offset in m4wraps */
78 char lquote[MAXCCHARS+1] = {LQUOTE}; /* left quote character (`) */
79 char rquote[MAXCCHARS+1] = {RQUOTE}; /* right quote character (') */
80 char scommt[MAXCCHARS+1] = {SCOMMT}; /* start character for comment */
81 char ecommt[MAXCCHARS+1] = {ECOMMT}; /* end character for comment */
82 int synch_lines = 0; /* line synchronisation for C preprocessor */
83 int prefix_builtins = 0; /* -P option to prefix builtin keywords */
84 int error_warns = 0; /* -E option to make warnings exit_code = 1 */
85 int fatal_warns = 0; /* -E -E option to make warnings fatal */
88 const char *knam; /* keyword name */
89 int ktyp; /* keyword type */
92 static struct keyblk keywrds[] = { /* m4 keywords to be installed */
93 { "include", INCLTYPE },
94 { "sinclude", SINCTYPE },
95 { "define", DEFITYPE },
97 { "divert", DIVRTYPE | NOARGS },
100 { "substr", SUBSTYPE },
101 { "ifelse", IFELTYPE },
102 { "ifdef", IFDFTYPE },
104 { "incr", INCRTYPE },
105 { "decr", DECRTYPE },
106 { "dnl", DNLNTYPE | NOARGS },
107 { "changequote", CHNQTYPE | NOARGS },
108 { "changecom", CHNCTYPE | NOARGS },
109 { "index", INDXTYPE },
111 { "paste", PASTTYPE },
112 { "spaste", SPASTYPE },
113 /* Newer extensions, needed to handle gnu-m4 scripts */
114 { "indir", INDIRTYPE},
115 { "builtin", BUILTINTYPE},
116 { "patsubst", PATSTYPE},
117 { "regexp", REGEXPTYPE},
118 { "esyscmd", ESYSCMDTYPE},
119 { "__file__", FILENAMETYPE | NOARGS},
120 { "__line__", LINETYPE | NOARGS},
122 { "popdef", POPDTYPE },
123 { "pushdef", PUSDTYPE },
124 { "dumpdef", DUMPTYPE | NOARGS },
125 { "shift", SHIFTYPE | NOARGS },
126 { "translit", TRNLTYPE },
127 { "undefine", UNDFTYPE },
128 { "undivert", UNDVTYPE | NOARGS },
129 { "divnum", DIVNTYPE | NOARGS },
130 { "maketemp", MKTMTYPE },
131 { "mkstemp", MKTMTYPE },
132 { "errprint", ERRPTYPE | NOARGS },
133 { "m4wrap", M4WRTYPE | NOARGS },
134 { "m4exit", EXITTYPE | NOARGS },
135 { "syscmd", SYSCTYPE },
136 { "sysval", SYSVTYPE | NOARGS },
137 { "traceon", TRACEONTYPE | NOARGS },
138 { "traceoff", TRACEOFFTYPE | NOARGS },
140 { "unix", SELFTYPE | NOARGS },
143 #define MAXKEYS (sizeof(keywrds)/sizeof(struct keyblk))
149 static struct position {
152 } quotes[MAXRECORD], paren[MAXRECORD];
154 static void record(struct position *, int);
155 static void dump_stack(struct position *, int);
157 static void macro(void);
158 static void initkwds(void);
159 static ndptr inspect(int, char *);
160 static int do_look_ahead(int, const char *);
161 static void reallyoutputstr(const char *);
162 static void reallyputchar(int);
164 static void enlarge_stack(void);
166 int main(int, char *[]);
171 main(int argc, char *argv[])
177 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
178 signal(SIGINT, onintr);
182 STACKMAX = INITSTACKMAX;
184 mstack = xreallocarray(NULL, STACKMAX, sizeof(stae), NULL);
185 sstack = xalloc(STACKMAX, NULL);
191 while ((c = getopt(argc, argv, "gst:d:D:EU:o:I:P")) != -1)
194 case 'D': /* define something..*/
195 for (p = optarg; *p; p++)
202 case 'E': /* like GNU m4 1.4.9+ */
203 if (error_warns == 0)
209 addtoincludepath(optarg);
214 case 'U': /* undefine... */
215 macro_popdef(optarg);
221 set_trace_flags(optarg);
227 mark_traced(optarg, 1);
241 setup_builtin("format", FORMATTYPE);
243 active = stdout; /* default active output */
246 sp = -1; /* stack pointer initialized */
247 fp = 0; /* frame pointer initialized */
248 set_input(infile+0, stdin, "stdin");
249 /* default input (naturally) */
252 for (; argc--; ++argv) {
254 if (p[0] == '-' && p[1] == EOS)
255 set_input(infile, stdin, "stdin");
256 else if (fopen_trypath(infile, p) == NULL)
261 release_input(infile);
267 ilevel = 0; /* in case m4wrap includes.. */
268 bufbase = bp = buf; /* use the entire buffer */
270 while (wrapindex != 0) {
271 for (i = 0; i < wrapindex; i++)
277 for (i = 0; i < wrapindex; i++) {
284 if (active != stdout)
285 active = stdout; /* reset output just in case */
286 for (n = 1; n < maxout; n++) /* default wrap-up: undivert */
287 if (outfile[n] != NULL)
289 /* remove bitbucket if used */
290 if (outfile[0] != NULL) {
291 (void) fclose(outfile[0]);
298 * Look ahead for `token'.
299 * (on input `t == token[0]')
300 * Used for comment and quoting delimiters.
301 * Returns 1 if `token' present; copied to output.
302 * 0 if `token' not found; all characters pushed back
305 do_look_ahead(int t, const char *token)
309 assert((unsigned char)t == (unsigned char)token[0]);
311 for (i = 1; *++token; i++) {
313 if (t == EOF || (unsigned char)t != (unsigned char)*token) {
323 #define LOOK_AHEAD(t, token) (t != EOF && \
324 (unsigned char)(t)==(unsigned char)(token)[0] && \
325 do_look_ahead(t,token))
328 * macro - the work horse..
333 char token[MAXTOK+1];
341 if (LOOK_AHEAD(t,lquote)) { /* strip quotes */
343 record(quotes, nlpar++);
345 * Opening quote: scan forward until matching
346 * closing quote has been found.
351 if (LOOK_AHEAD(l,rquote)) {
354 } else if (LOOK_AHEAD(l,lquote)) {
355 record(quotes, nlpar++);
357 } else if (l == EOF) {
359 warnx("unclosed quote:");
361 warnx("%d unclosed quotes:", nlpar);
362 dump_stack(quotes, nlpar);
374 } else if (sp < 0 && LOOK_AHEAD(t, scommt)) {
375 reallyoutputstr(scommt);
379 if (LOOK_AHEAD(t, ecommt)) {
380 reallyoutputstr(ecommt);
387 } else if (t == '_' || isalpha(t)) {
388 p = inspect(t, token);
390 pushback(l = gpbc());
391 if (p == NULL || (l != LPAREN &&
392 (macro_getdef(p)->type & NEEDARGS) != 0))
396 * real thing.. First build a call frame:
398 pushf(fp); /* previous call frm */
399 pushf(macro_getdef(p)->type); /* type of the call */
401 pushf(0); /* parenthesis level */
402 fp = sp; /* new frame pointer */
404 * now push the string arguments:
406 pushdef(p); /* defn string */
407 pushs1((char *)macro_name(p)); /* macro name */
408 pushs(ep); /* start next..*/
410 if (l != LPAREN && PARLEV == 0) {
414 if (sp == (int)STACKMAX)
415 errx(1, "internal stack overflow");
416 eval((const char **) mstack+fp+1, 2,
417 CALTYP, TRACESTATUS);
419 ep = PREVEP; /* flush strspace */
420 sp = PREVSP; /* previous sp.. */
421 fp = PREVFP; /* rewind stack...*/
424 } else if (t == EOF) {
425 if (!mimic_gnu /* you can puke right there */
426 && sp > -1 && ilevel <= 0) {
427 warnx( "unexpected end of input, unclosed parenthesis:");
428 dump_stack(paren, PARLEV);
432 break; /* all done thanks.. */
433 release_input(infile+ilevel--);
435 bufbase = bbase[ilevel];
437 } else if (sp < 0) { /* not in a macro at all */
438 reallyputchar(t); /* output directly.. */
446 while (isspace(l = gpbc())) /* skip blank, tab, nl.. */
450 record(paren, PARLEV++);
456 else { /* end of argument list */
459 if (sp == (int)STACKMAX)
460 errx(1, "internal stack overflow");
462 eval((const char **) mstack+fp+1, sp-fp,
463 CALTYP, TRACESTATUS);
465 ep = PREVEP; /* flush strspace */
466 sp = PREVSP; /* previous sp.. */
467 fp = PREVFP; /* rewind stack...*/
473 chrsave(EOS); /* new argument */
474 while (isspace(l = gpbc()))
483 if (LOOK_AHEAD(t, scommt)) {
485 for (p = scommt; *p; p++)
489 if (LOOK_AHEAD(t, ecommt)) {
490 for (p = ecommt; *p; p++)
499 CHRSAVE(t); /* stack the char */
506 * output string directly, without pushing it for reparses.
509 outputstr(const char *s)
519 reallyoutputstr(const char *s)
525 infile[ilevel].synch_lineno++;
526 if (infile[ilevel].synch_lineno !=
527 infile[ilevel].lineno)
539 if (synch_lines && c == '\n') {
540 infile[ilevel].synch_lineno++;
541 if (infile[ilevel].synch_lineno != infile[ilevel].lineno)
547 * build an input token..
548 * consider only those starting with _ or A-Za-z.
551 inspect(int c, char *tp)
554 char *etp = tp+MAXTOK;
559 while ((isalnum(c = gpbc()) || c == '_') && tp < etp)
564 /* token is too long, it won't match anything, but it can still
568 while (isalnum(c = gpbc()) || c == '_') {
578 p = ohash_find(¯os, ohash_qlookupi(¯os, name, (const char **)&tp));
581 if (macro_getdef(p) == NULL)
587 * initkwds - initialise m4 keywords as fast as possible.
588 * This very similar to install, but without certain overheads,
589 * such as calling lookup. Malloc is not used for storing the
590 * keyword strings, since we simply use the static pointers
591 * within keywrds block.
599 for (i = 0; i < (int)MAXKEYS; i++) {
600 type = keywrds[i].ktyp & TYPEMASK;
601 if ((keywrds[i].ktyp & NOARGS) == 0)
603 setup_builtin(keywrds[i].knam, type);
608 record(struct position *t, int lev)
610 if (lev < MAXRECORD) {
611 t[lev].name = CURRENT_NAME;
612 t[lev].line = CURRENT_LINE;
617 dump_stack(struct position *t, int lev)
621 for (i = 0; i < lev; i++) {
622 if (i == MAXRECORD) {
623 fprintf(stderr, " ...\n");
626 fprintf(stderr, " %s at line %lu\n",
627 t[i].name, t[i].line);
635 STACKMAX += STACKMAX/2;
636 mstack = xreallocarray(mstack, STACKMAX, sizeof(stae),
637 "Evaluation stack overflow (%lu)",
638 (unsigned long)STACKMAX);
639 sstack = xrealloc(sstack, STACKMAX,
640 "Evaluation stack overflow (%lu)",
641 (unsigned long)STACKMAX);