1 /* $OpenBSD: main.c,v 1.86 2015/11/03 16:21:47 deraadt Exp $ */
2 /* $NetBSD: main.c,v 1.12 1997/02/08 23:54:49 cgd Exp $ */
5 * Copyright (c) 1989, 1993
6 * The Regents of the University of California. All rights reserved.
8 * This code is derived from software contributed to Berkeley by
9 * Ozan Yigit at York University.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * Facility: m4 macro processor
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
59 #include "pathnames.h"
61 stae *mstack; /* stack of m4 machine */
62 char *sstack; /* shadow stack, for string space extension */
63 static size_t STACKMAX; /* current maximum size of stack */
64 int sp; /* current m4 stack pointer */
65 int fp; /* m4 call frame pointer */
66 struct input_file infile[MAXINP];/* input file stack (0=stdin) */
67 FILE **outfile; /* diversion array(0=bitbucket)*/
69 FILE *active; /* active output file pointer */
70 int ilevel = 0; /* input file stack pointer */
71 int oindex = 0; /* diversion index.. */
72 const char *null = ""; /* as it says.. just a null.. */
73 char **m4wraps = NULL; /* m4wraps array. */
74 int maxwraps = 0; /* size of m4wraps array */
75 int wrapindex = 0; /* current offset in m4wraps */
76 char lquote[MAXCCHARS+1] = {LQUOTE}; /* left quote character (`) */
77 char rquote[MAXCCHARS+1] = {RQUOTE}; /* right quote character (') */
78 char scommt[MAXCCHARS+1] = {SCOMMT}; /* start character for comment */
79 char ecommt[MAXCCHARS+1] = {ECOMMT}; /* end character for comment */
80 int synch_lines = 0; /* line synchronisation for C preprocessor */
81 int prefix_builtins = 0; /* -P option to prefix builtin keywords */
84 const char *knam; /* keyword name */
85 int ktyp; /* keyword type */
88 static struct keyblk keywrds[] = { /* m4 keywords to be installed */
89 { "include", INCLTYPE },
90 { "sinclude", SINCTYPE },
91 { "define", DEFITYPE },
93 { "divert", DIVRTYPE | NOARGS },
96 { "substr", SUBSTYPE },
97 { "ifelse", IFELTYPE },
98 { "ifdef", IFDFTYPE },
100 { "incr", INCRTYPE },
101 { "decr", DECRTYPE },
102 { "dnl", DNLNTYPE | NOARGS },
103 { "changequote", CHNQTYPE | NOARGS },
104 { "changecom", CHNCTYPE | NOARGS },
105 { "index", INDXTYPE },
107 { "paste", PASTTYPE },
108 { "spaste", SPASTYPE },
109 /* Newer extensions, needed to handle gnu-m4 scripts */
110 { "indir", INDIRTYPE},
111 { "builtin", BUILTINTYPE},
112 { "patsubst", PATSTYPE},
113 { "regexp", REGEXPTYPE},
114 { "esyscmd", ESYSCMDTYPE},
115 { "__file__", FILENAMETYPE | NOARGS},
116 { "__line__", LINETYPE | NOARGS},
118 { "popdef", POPDTYPE },
119 { "pushdef", PUSDTYPE },
120 { "dumpdef", DUMPTYPE | NOARGS },
121 { "shift", SHIFTYPE | NOARGS },
122 { "translit", TRNLTYPE },
123 { "undefine", UNDFTYPE },
124 { "undivert", UNDVTYPE | NOARGS },
125 { "divnum", DIVNTYPE | NOARGS },
126 { "maketemp", MKTMTYPE },
127 { "mkstemp", MKTMTYPE },
128 { "errprint", ERRPTYPE | NOARGS },
129 { "m4wrap", M4WRTYPE | NOARGS },
130 { "m4exit", EXITTYPE | NOARGS },
131 { "syscmd", SYSCTYPE },
132 { "sysval", SYSVTYPE | NOARGS },
133 { "traceon", TRACEONTYPE | NOARGS },
134 { "traceoff", TRACEOFFTYPE | NOARGS },
136 { "unix", SELFTYPE | NOARGS },
139 #define MAXKEYS (sizeof(keywrds)/sizeof(struct keyblk))
145 static struct position {
148 } quotes[MAXRECORD], paren[MAXRECORD];
150 static void record(struct position *, int);
151 static void dump_stack(struct position *, int);
153 static void macro(void);
154 static void initkwds(void);
155 static ndptr inspect(int, char *);
156 static int do_look_ahead(int, const char *);
157 static void reallyoutputstr(const char *);
158 static void reallyputchar(int);
160 static void enlarge_stack(void);
162 int main(int, char *[]);
167 main(int argc, char *argv[])
173 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
174 signal(SIGINT, onintr);
178 STACKMAX = INITSTACKMAX;
180 mstack = xreallocarray(NULL, STACKMAX, sizeof(stae), NULL);
181 sstack = xalloc(STACKMAX, NULL);
187 while ((c = getopt(argc, argv, "gst:d:D:U:o:I:P")) != -1)
190 case 'D': /* define something..*/
191 for (p = optarg; *p; p++)
199 addtoincludepath(optarg);
204 case 'U': /* undefine... */
205 macro_popdef(optarg);
211 set_trace_flags(optarg);
217 mark_traced(optarg, 1);
231 setup_builtin("format", FORMATTYPE);
233 active = stdout; /* default active output */
236 sp = -1; /* stack pointer initialized */
237 fp = 0; /* frame pointer initialized */
238 set_input(infile+0, stdin, "stdin");
239 /* default input (naturally) */
242 for (; argc--; ++argv) {
244 if (p[0] == '-' && p[1] == EOS)
245 set_input(infile, stdin, "stdin");
246 else if (fopen_trypath(infile, p) == NULL)
251 release_input(infile);
257 ilevel = 0; /* in case m4wrap includes.. */
258 bufbase = bp = buf; /* use the entire buffer */
260 while (wrapindex != 0) {
261 for (i = 0; i < wrapindex; i++)
267 for (i = 0; i < wrapindex; i++) {
274 if (active != stdout)
275 active = stdout; /* reset output just in case */
276 for (n = 1; n < maxout; n++) /* default wrap-up: undivert */
277 if (outfile[n] != NULL)
279 /* remove bitbucket if used */
280 if (outfile[0] != NULL) {
281 (void) fclose(outfile[0]);
288 * Look ahead for `token'.
289 * (on input `t == token[0]')
290 * Used for comment and quoting delimiters.
291 * Returns 1 if `token' present; copied to output.
292 * 0 if `token' not found; all characters pushed back
295 do_look_ahead(int t, const char *token)
299 assert((unsigned char)t == (unsigned char)token[0]);
301 for (i = 1; *++token; i++) {
303 if (t == EOF || (unsigned char)t != (unsigned char)*token) {
313 #define LOOK_AHEAD(t, token) (t != EOF && \
314 (unsigned char)(t)==(unsigned char)(token)[0] && \
315 do_look_ahead(t,token))
318 * macro - the work horse..
323 char token[MAXTOK+1];
331 if (LOOK_AHEAD(t,lquote)) { /* strip quotes */
333 record(quotes, nlpar++);
335 * Opening quote: scan forward until matching
336 * closing quote has been found.
341 if (LOOK_AHEAD(l,rquote)) {
344 } else if (LOOK_AHEAD(l,lquote)) {
345 record(quotes, nlpar++);
347 } else if (l == EOF) {
349 warnx("unclosed quote:");
351 warnx("%d unclosed quotes:", nlpar);
352 dump_stack(quotes, nlpar);
364 } else if (sp < 0 && LOOK_AHEAD(t, scommt)) {
365 reallyoutputstr(scommt);
369 if (LOOK_AHEAD(t, ecommt)) {
370 reallyoutputstr(ecommt);
377 } else if (t == '_' || isalpha(t)) {
378 p = inspect(t, token);
380 pushback(l = gpbc());
381 if (p == NULL || (l != LPAREN &&
382 (macro_getdef(p)->type & NEEDARGS) != 0))
386 * real thing.. First build a call frame:
388 pushf(fp); /* previous call frm */
389 pushf(macro_getdef(p)->type); /* type of the call */
391 pushf(0); /* parenthesis level */
392 fp = sp; /* new frame pointer */
394 * now push the string arguments:
396 pushdef(p); /* defn string */
397 pushs1((char *)macro_name(p)); /* macro name */
398 pushs(ep); /* start next..*/
400 if (l != LPAREN && PARLEV == 0) {
404 if (sp == (int)STACKMAX)
405 errx(1, "internal stack overflow");
406 eval((const char **) mstack+fp+1, 2,
407 CALTYP, TRACESTATUS);
409 ep = PREVEP; /* flush strspace */
410 sp = PREVSP; /* previous sp.. */
411 fp = PREVFP; /* rewind stack...*/
414 } else if (t == EOF) {
415 if (!mimic_gnu /* you can puke right there */
416 && sp > -1 && ilevel <= 0) {
417 warnx( "unexpected end of input, unclosed parenthesis:");
418 dump_stack(paren, PARLEV);
422 break; /* all done thanks.. */
423 release_input(infile+ilevel--);
425 bufbase = bbase[ilevel];
427 } else if (sp < 0) { /* not in a macro at all */
428 reallyputchar(t); /* output directly.. */
436 while (isspace(l = gpbc())) /* skip blank, tab, nl.. */
440 record(paren, PARLEV++);
446 else { /* end of argument list */
449 if (sp == (int)STACKMAX)
450 errx(1, "internal stack overflow");
452 eval((const char **) mstack+fp+1, sp-fp,
453 CALTYP, TRACESTATUS);
455 ep = PREVEP; /* flush strspace */
456 sp = PREVSP; /* previous sp.. */
457 fp = PREVFP; /* rewind stack...*/
463 chrsave(EOS); /* new argument */
464 while (isspace(l = gpbc()))
473 if (LOOK_AHEAD(t, scommt)) {
475 for (p = scommt; *p; p++)
479 if (LOOK_AHEAD(t, ecommt)) {
480 for (p = ecommt; *p; p++)
489 CHRSAVE(t); /* stack the char */
496 * output string directly, without pushing it for reparses.
499 outputstr(const char *s)
509 reallyoutputstr(const char *s)
515 infile[ilevel].synch_lineno++;
516 if (infile[ilevel].synch_lineno !=
517 infile[ilevel].lineno)
529 if (synch_lines && c == '\n') {
530 infile[ilevel].synch_lineno++;
531 if (infile[ilevel].synch_lineno != infile[ilevel].lineno)
537 * build an input token..
538 * consider only those starting with _ or A-Za-z.
541 inspect(int c, char *tp)
544 char *etp = tp+MAXTOK;
549 while ((isalnum(c = gpbc()) || c == '_') && tp < etp)
554 /* token is too long, it won't match anything, but it can still
558 while (isalnum(c = gpbc()) || c == '_') {
568 p = ohash_find(¯os, ohash_qlookupi(¯os, name, (const char **)&tp));
571 if (macro_getdef(p) == NULL)
577 * initkwds - initialise m4 keywords as fast as possible.
578 * This very similar to install, but without certain overheads,
579 * such as calling lookup. Malloc is not used for storing the
580 * keyword strings, since we simply use the static pointers
581 * within keywrds block.
589 for (i = 0; i < (int)MAXKEYS; i++) {
590 type = keywrds[i].ktyp & TYPEMASK;
591 if ((keywrds[i].ktyp & NOARGS) == 0)
593 setup_builtin(keywrds[i].knam, type);
598 record(struct position *t, int lev)
600 if (lev < MAXRECORD) {
601 t[lev].name = CURRENT_NAME;
602 t[lev].line = CURRENT_LINE;
607 dump_stack(struct position *t, int lev)
611 for (i = 0; i < lev; i++) {
612 if (i == MAXRECORD) {
613 fprintf(stderr, " ...\n");
616 fprintf(stderr, " %s at line %lu\n",
617 t[i].name, t[i].line);
625 STACKMAX += STACKMAX/2;
626 mstack = xreallocarray(mstack, STACKMAX, sizeof(stae),
627 "Evaluation stack overflow (%lu)",
628 (unsigned long)STACKMAX);
629 sstack = xrealloc(sstack, STACKMAX,
630 "Evaluation stack overflow (%lu)",
631 (unsigned long)STACKMAX);