Index: head/usr.bin/m4/extern.h =================================================================== --- head/usr.bin/m4/extern.h (revision 283088) +++ head/usr.bin/m4/extern.h (revision 283089) @@ -1,180 +1,179 @@ /* $OpenBSD: extern.h,v 1.54 2014/05/12 19:11:19 espie Exp $ */ /* $NetBSD: extern.h,v 1.3 1996/01/13 23:25:24 pk Exp $ */ /*- * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Ozan Yigit at York University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)extern.h 8.1 (Berkeley) 6/6/93 * $FreeBSD$ */ /* eval.c */ extern void eval(const char *[], int, int, int); extern void dodefine(const char *, const char *); extern unsigned long expansion_id; /* expr.c */ extern int expr(const char *); -extern int32_t end_result; /* gnum4.c */ extern void addtoincludepath(const char *); extern struct input_file *fopen_trypath(struct input_file *, const char *); extern void doindir(const char *[], int); extern void dobuiltin(const char *[], int); extern void dopatsubst(const char *[], int); extern void doregexp(const char *[], int); extern void doprintlineno(struct input_file *); extern void doprintfilename(struct input_file *); extern void doesyscmd(const char *); extern void getdivfile(const char *); extern void doformat(const char *[], int); /* look.c */ #define FLAG_UNTRACED 0 #define FLAG_TRACED 1 #define FLAG_NO_TRACE 2 extern void init_macros(void); extern ndptr lookup(const char *); extern void mark_traced(const char *, int); extern struct ohash macros; extern struct macro_definition *lookup_macro_definition(const char *); extern void macro_define(const char *, const char *); extern void macro_pushdef(const char *, const char *); extern void macro_popdef(const char *); extern void macro_undefine(const char *); extern void setup_builtin(const char *, unsigned int); extern void macro_for_all(void (*)(const char *, struct macro_definition *)); #define macro_getdef(p) ((p)->d) #define macro_name(p) ((p)->name) #define macro_builtin_type(p) ((p)->builtin_type) #define is_traced(p) ((p)->trace_flags == FLAG_NO_TRACE ? (trace_flags & TRACE_ALL) : (p)->trace_flags) extern ndptr macro_getbuiltin(const char *); /* main.c */ extern void outputstr(const char *); extern void do_emit_synchline(void); extern int exit_code; #define emit_synchline() do { if (synch_lines) do_emit_synchline(); } while(0) /* misc.c */ extern void chrsave(int); extern char *compute_prevep(void); extern void getdiv(int); extern ptrdiff_t indx(const char *, const char *); extern void initspaces(void); extern void killdiv(void); extern void onintr(int); extern void pbnum(int); extern void pbnumbase(int, int, int); extern void pbunsigned(unsigned long); extern void pbstr(const char *); extern void pushback(int); extern void *xalloc(size_t, const char *, ...); extern void *xcalloc(size_t, size_t, const char *, ...); extern void *xrealloc(void *, size_t, const char *, ...); extern void *xreallocarray(void *, size_t, size_t, const char *, ...); extern char *xstrdup(const char *); extern void usage(void); extern void resizedivs(int); extern size_t buffer_mark(void); extern void dump_buffer(FILE *, size_t); extern void m4errx(int, const char *, ...); extern int obtain_char(struct input_file *); extern void set_input(struct input_file *, FILE *, const char *); extern void release_input(struct input_file *); /* speeded-up versions of chrsave/pushback */ #define PUSHBACK(c) \ do { \ if (bp >= endpbb) \ enlarge_bufspace(); \ *bp++ = (c); \ } while(0) #define CHRSAVE(c) \ do { \ if (ep >= endest) \ enlarge_strspace(); \ *ep++ = (c); \ } while(0) /* and corresponding exposure for local symbols */ extern void enlarge_bufspace(void); extern void enlarge_strspace(void); extern unsigned char *endpbb; extern char *endest; /* trace.c */ extern unsigned int trace_flags; #define TRACE_ALL 512 extern void trace_file(const char *); extern size_t trace(const char **, int, struct input_file *); extern void finish_trace(size_t); extern void set_trace_flags(const char *); extern FILE *traceout; extern stae *mstack; /* stack of m4 machine */ extern char *sstack; /* shadow stack, for string space extension */ extern FILE *active; /* active output file pointer */ extern struct input_file infile[];/* input file stack (0=stdin) */ extern FILE **outfile; /* diversion array(0=bitbucket) */ extern int maxout; /* maximum number of diversions */ extern int fp; /* m4 call frame pointer */ extern int ilevel; /* input file stack pointer */ extern int oindex; /* diversion index. */ extern int sp; /* current m4 stack pointer */ extern unsigned char *bp; /* first available character */ extern unsigned char *buf; /* push-back buffer */ extern unsigned char *bufbase; /* buffer base for this ilevel */ extern unsigned char *bbase[]; /* buffer base per ilevel */ extern char ecommt[MAXCCHARS+1];/* end character for comment */ extern char *ep; /* first free char in strspace */ extern char lquote[MAXCCHARS+1];/* left quote character (`) */ extern char **m4wraps; /* m4wrap string default. */ extern int maxwraps; /* size of m4wraps array */ extern int wrapindex; /* current index in m4wraps */ extern const char *null; /* as it says.. just a null. */ extern char rquote[MAXCCHARS+1];/* right quote character (') */ extern char scommt[MAXCCHARS+1];/* start character for comment */ extern int synch_lines; /* line synchronisation directives */ extern int mimic_gnu; /* behaves like gnu-m4 */ extern int prefix_builtins; /* prefix builtin macros with m4_ */ Index: head/usr.bin/m4/gnum4.c =================================================================== --- head/usr.bin/m4/gnum4.c (revision 283088) +++ head/usr.bin/m4/gnum4.c (revision 283089) @@ -1,673 +1,673 @@ -/* $OpenBSD: gnum4.c,v 1.46 2014/07/10 14:12:31 espie Exp $ */ +/* $OpenBSD: gnum4.c,v 1.50 2015/04/29 00:13:26 millert Exp $ */ /* * Copyright (c) 1999 Marc Espie * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * functions needed to support gnu-m4 extensions, including a fake freezing */ -#include #include #include #include #include #include #include #include #include +#include #include #include #include #include +#include #include "mdef.h" #include "stdd.h" #include "extern.h" int mimic_gnu = 0; /* * Support for include path search * First search in the current directory. * If not found, and the path is not absolute, include path kicks in. * First, -I options, in the order found on the command line. * Then M4PATH env variable */ static struct path_entry { char *name; struct path_entry *next; } *first, *last; static struct path_entry *new_path_entry(const char *); static void ensure_m4path(void); static struct input_file *dopath(struct input_file *, const char *); static struct path_entry * new_path_entry(const char *dirname) { struct path_entry *n; n = malloc(sizeof(struct path_entry)); if (!n) errx(1, "out of memory"); - n->name = strdup(dirname); - if (!n->name) - errx(1, "out of memory"); + n->name = xstrdup(dirname); n->next = 0; return n; } void addtoincludepath(const char *dirname) { struct path_entry *n; n = new_path_entry(dirname); if (last) { last->next = n; last = n; } else last = first = n; } static void ensure_m4path(void) { static int envpathdone = 0; char *envpath; char *sweep; char *path; if (envpathdone) return; envpathdone = TRUE; envpath = getenv("M4PATH"); if (!envpath) return; /* for portability: getenv result is read-only */ - envpath = strdup(envpath); - if (!envpath) - errx(1, "out of memory"); + envpath = xstrdup(envpath); for (sweep = envpath; (path = strsep(&sweep, ":")) != NULL;) addtoincludepath(path); free(envpath); } static struct input_file * dopath(struct input_file *i, const char *filename) { - char path[MAXPATHLEN]; + char path[PATH_MAX]; struct path_entry *pe; FILE *f; for (pe = first; pe; pe = pe->next) { snprintf(path, sizeof(path), "%s/%s", pe->name, filename); if ((f = fopen(path, "r")) != 0) { set_input(i, f, path); return i; } } return NULL; } struct input_file * fopen_trypath(struct input_file *i, const char *filename) { FILE *f; f = fopen(filename, "r"); if (f != NULL) { set_input(i, f, filename); return i; } if (filename[0] == '/') return NULL; ensure_m4path(); return dopath(i, filename); } void doindir(const char *argv[], int argc) { ndptr n; struct macro_definition *p = NULL; n = lookup(argv[2]); if (n == NULL || (p = macro_getdef(n)) == NULL) m4errx(1, "indir: undefined macro %s.", argv[2]); argv[1] = p->defn; eval(argv+1, argc-1, p->type, is_traced(n)); } void dobuiltin(const char *argv[], int argc) { ndptr p; argv[1] = NULL; p = macro_getbuiltin(argv[2]); if (p != NULL) eval(argv+1, argc-1, macro_builtin_type(p), is_traced(p)); else m4errx(1, "unknown builtin %s.", argv[2]); } /* We need some temporary buffer space, as pb pushes BACK and substitution * proceeds forward... */ static char *buffer; static size_t bufsize = 0; static size_t current = 0; static void addchars(const char *, size_t); static void addchar(int); static char *twiddle(const char *); static char *getstring(void); static void exit_regerror(int, regex_t *, const char *); static void do_subst(const char *, regex_t *, const char *, const char *, regmatch_t *); static void do_regexpindex(const char *, regex_t *, const char *, regmatch_t *); static void do_regexp(const char *, regex_t *, const char *, const char *, regmatch_t *); static void add_sub(int, const char *, regex_t *, regmatch_t *); static void add_replace(const char *, regex_t *, const char *, regmatch_t *); #define addconstantstring(s) addchars((s), sizeof(s)-1) static void addchars(const char *c, size_t n) { if (n == 0) return; while (current + n > bufsize) { if (bufsize == 0) bufsize = 1024; - else + else if (bufsize <= SIZE_MAX/2) { bufsize *= 2; + } else { + errx(1, "size overflow"); + } buffer = xrealloc(buffer, bufsize, NULL); } memcpy(buffer+current, c, n); current += n; } static void addchar(int c) { if (current +1 > bufsize) { if (bufsize == 0) bufsize = 1024; else bufsize *= 2; buffer = xrealloc(buffer, bufsize, NULL); } buffer[current++] = c; } static char * getstring(void) { addchar('\0'); current = 0; return buffer; } static void exit_regerror(int er, regex_t *re, const char *source) { size_t errlen; char *errbuf; errlen = regerror(er, re, NULL, 0); errbuf = xalloc(errlen, "malloc in regerror: %lu", (unsigned long)errlen); regerror(er, re, errbuf, errlen); m4errx(1, "regular expression error in %s: %s.", source, errbuf); } static void add_sub(int n, const char *string, regex_t *re, regmatch_t *pm) { if (n > (int)re->re_nsub) warnx("No subexpression %d", n); /* Subexpressions that did not match are * not an error. */ else if (pm[n].rm_so != -1 && pm[n].rm_eo != -1) { addchars(string + pm[n].rm_so, pm[n].rm_eo - pm[n].rm_so); } } /* Add replacement string to the output buffer, recognizing special * constructs and replacing them with substrings of the original string. */ static void add_replace(const char *string, regex_t *re, const char *replace, regmatch_t *pm) { const char *p; for (p = replace; *p != '\0'; p++) { if (*p == '&' && !mimic_gnu) { add_sub(0, string, re, pm); continue; } if (*p == '\\') { if (p[1] == '\\') { addchar(p[1]); p++; continue; } if (p[1] == '&') { if (mimic_gnu) add_sub(0, string, re, pm); else addchar(p[1]); p++; continue; } if (isdigit((unsigned char)p[1])) { add_sub(*(++p) - '0', string, re, pm); continue; } } addchar(*p); } } static void do_subst(const char *string, regex_t *re, const char *source, const char *replace, regmatch_t *pm) { int error; int flags = 0; const char *last_match = NULL; while ((error = regexec(re, string, re->re_nsub+1, pm, flags)) == 0) { if (pm[0].rm_eo != 0) { if (string[pm[0].rm_eo-1] == '\n') flags = 0; else flags = REG_NOTBOL; } /* NULL length matches are special... We use the `vi-mode' * rule: don't allow a NULL-match at the last match * position. */ if (pm[0].rm_so == pm[0].rm_eo && string + pm[0].rm_so == last_match) { if (*string == '\0') return; addchar(*string); if (*string++ == '\n') flags = 0; else flags = REG_NOTBOL; continue; } last_match = string + pm[0].rm_so; addchars(string, pm[0].rm_so); add_replace(string, re, replace, pm); string += pm[0].rm_eo; } if (error != REG_NOMATCH) exit_regerror(error, re, source); pbstr(string); } static void do_regexp(const char *string, regex_t *re, const char *source, const char *replace, regmatch_t *pm) { int error; switch(error = regexec(re, string, re->re_nsub+1, pm, 0)) { case 0: add_replace(string, re, replace, pm); pbstr(getstring()); break; case REG_NOMATCH: break; default: exit_regerror(error, re, source); } } static void do_regexpindex(const char *string, regex_t *re, const char *source, regmatch_t *pm) { int error; switch(error = regexec(re, string, re->re_nsub+1, pm, 0)) { case 0: pbunsigned(pm[0].rm_so); break; case REG_NOMATCH: pbnum(-1); break; default: exit_regerror(error, re, source); } } /* In Gnu m4 mode, parentheses for backmatch don't work like POSIX 1003.2 * says. So we twiddle with the regexp before passing it to regcomp. */ static char * twiddle(const char *p) { /* + at start of regexp is a normal character for Gnu m4 */ if (*p == '^') { addchar(*p); p++; } if (*p == '+') { addchar('\\'); } /* This could use strcspn for speed... */ while (*p != '\0') { if (*p == '\\') { switch(p[1]) { case '(': case ')': case '|': addchar(p[1]); break; case 'w': addconstantstring("[_a-zA-Z0-9]"); break; case 'W': addconstantstring("[^_a-zA-Z0-9]"); break; case '<': addconstantstring("[[:<:]]"); break; case '>': addconstantstring("[[:>:]]"); break; default: addchars(p, 2); break; } p+=2; continue; } if (*p == '(' || *p == ')' || *p == '|') addchar('\\'); addchar(*p); p++; } return getstring(); } /* patsubst(string, regexp, opt replacement) */ /* argv[2]: string * argv[3]: regexp * argv[4]: opt rep */ void dopatsubst(const char *argv[], int argc) { if (argc <= 3) { warnx("Too few arguments to patsubst"); return; } /* special case: empty regexp */ if (argv[3][0] == '\0') { const char *s; size_t len; if (argc > 4 && argv[4]) len = strlen(argv[4]); else len = 0; for (s = argv[2]; *s != '\0'; s++) { addchars(argv[4], len); addchar(*s); } } else { int error; regex_t re; regmatch_t *pmatch; int mode = REG_EXTENDED; const char *source; size_t l = strlen(argv[3]); if (!mimic_gnu || (argv[3][0] == '^') || (l > 0 && argv[3][l-1] == '$')) mode |= REG_NEWLINE; source = mimic_gnu ? twiddle(argv[3]) : argv[3]; error = regcomp(&re, source, mode); if (error != 0) exit_regerror(error, &re, source); pmatch = xreallocarray(NULL, re.re_nsub+1, sizeof(regmatch_t), NULL); do_subst(argv[2], &re, source, argc > 4 && argv[4] != NULL ? argv[4] : "", pmatch); free(pmatch); regfree(&re); } pbstr(getstring()); } void doregexp(const char *argv[], int argc) { int error; regex_t re; regmatch_t *pmatch; const char *source; if (argc <= 3) { warnx("Too few arguments to regexp"); return; } /* special gnu case */ if (argv[3][0] == '\0' && mimic_gnu) { if (argc == 4 || argv[4] == NULL) return; else pbstr(argv[4]); } source = mimic_gnu ? twiddle(argv[3]) : argv[3]; error = regcomp(&re, source, REG_EXTENDED|REG_NEWLINE); if (error != 0) exit_regerror(error, &re, source); pmatch = xreallocarray(NULL, re.re_nsub+1, sizeof(regmatch_t), NULL); if (argc == 4 || argv[4] == NULL) do_regexpindex(argv[2], &re, source, pmatch); else do_regexp(argv[2], &re, source, argv[4], pmatch); free(pmatch); regfree(&re); } void doformat(const char *argv[], int argc) { const char *format = argv[2]; int pos = 3; int left_padded; long width; size_t l; const char *thisarg = NULL; char temp[2]; long extra; while (*format != 0) { if (*format != '%') { addchar(*format++); continue; } format++; if (*format == '%') { addchar(*format++); continue; } if (*format == 0) { addchar('%'); break; } if (*format == '*') { format++; if (pos >= argc) m4errx(1, "Format with too many format specifiers."); width = strtol(argv[pos++], NULL, 10); } else { width = strtol(format, __DECONST(char **,&format), 10); } if (width < 0) { left_padded = 1; width = -width; } else { left_padded = 0; } if (*format == '.') { format++; if (*format == '*') { format++; if (pos >= argc) m4errx(1, "Format with too many format specifiers."); extra = strtol(argv[pos++], NULL, 10); } else { extra = strtol(format, __DECONST(char **, &format), 10); } } else { extra = LONG_MAX; } if (pos >= argc) m4errx(1, "Format with too many format specifiers."); switch(*format) { case 's': thisarg = argv[pos++]; break; case 'c': temp[0] = strtoul(argv[pos++], NULL, 10); temp[1] = 0; thisarg = temp; break; default: m4errx(1, "Unsupported format specification: %s.", argv[2]); } format++; l = strlen(thisarg); if ((long)l > extra) l = extra; if (!left_padded) { while ((long)l < width--) addchar(' '); } addchars(thisarg, l); if (left_padded) { while ((long)l < width--) addchar(' '); } } pbstr(getstring()); } void doesyscmd(const char *cmd) { int p[2]; pid_t pid, cpid; char *argv[4]; int cc; int status; /* Follow gnu m4 documentation: first flush buffers. */ fflush(NULL); argv[0] = __DECONST(char *, "sh"); argv[1] = __DECONST(char *, "-c"); argv[2] = __DECONST(char *, cmd); argv[3] = NULL; /* Just set up standard output, share stderr and stdin with m4 */ if (pipe(p) == -1) err(1, "bad pipe"); switch(cpid = fork()) { case -1: err(1, "bad fork"); /* NOTREACHED */ case 0: (void) close(p[0]); (void) dup2(p[1], 1); (void) close(p[1]); execv(_PATH_BSHELL, argv); exit(1); default: /* Read result in two stages, since m4's buffer is * pushback-only. */ (void) close(p[1]); do { char result[BUFSIZE]; cc = read(p[0], result, sizeof result); if (cc > 0) addchars(result, cc); } while (cc > 0 || (cc == -1 && errno == EINTR)); (void) close(p[0]); while ((pid = wait(&status)) != cpid && pid >= 0) continue; pbstr(getstring()); } } void getdivfile(const char *name) { FILE *f; int c; f = fopen(name, "r"); if (!f) return; while ((c = getc(f))!= EOF) putc(c, active); (void) fclose(f); } Index: head/usr.bin/m4/look.c =================================================================== --- head/usr.bin/m4/look.c (revision 283088) +++ head/usr.bin/m4/look.c (revision 283089) @@ -1,275 +1,339 @@ -/* $OpenBSD: look.c,v 1.23 2014/05/12 19:11:19 espie Exp $ */ +/* $OpenBSD: look.c,v 1.24 2014/12/21 09:33:12 espie Exp $ */ /* * Copyright (c) 1989, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Ozan Yigit at York University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * look.c * Facility: m4 macro processor * by: oz */ #include #include #include #include #include #include #include #include "mdef.h" #include "stdd.h" #include "extern.h" static void *hash_calloc(size_t, size_t, void *); static void hash_free(void *, void *); static void *element_alloc(size_t, void *); static void setup_definition(struct macro_definition *, const char *, const char *); +static void free_definition(char *); +static void keep(char *); +static int string_in_use(const char *); static struct ohash_info macro_info = { offsetof(struct ndblock, name), NULL, hash_calloc, hash_free, element_alloc }; struct ohash macros; /* Support routines for hash tables. */ void * hash_calloc(size_t n, size_t s, void *u __unused) { void *storage = xcalloc(n, s, "hash alloc"); return storage; } void hash_free(void *p, void *u __unused) { free(p); } void * element_alloc(size_t s, void *u __unused) { return xalloc(s, "element alloc"); } void init_macros(void) { ohash_init(¯os, 10, ¯o_info); } /* * find name in the hash table */ ndptr lookup(const char *name) { return ohash_find(¯os, ohash_qlookup(¯os, name)); } struct macro_definition * lookup_macro_definition(const char *name) { ndptr p; p = ohash_find(¯os, ohash_qlookup(¯os, name)); if (p) return p->d; else return NULL; } static void setup_definition(struct macro_definition *d, const char *defn, const char *name) { ndptr p; if (strncmp(defn, BUILTIN_MARKER, sizeof(BUILTIN_MARKER)-1) == 0 && (p = macro_getbuiltin(defn+sizeof(BUILTIN_MARKER)-1)) != NULL) { d->type = macro_builtin_type(p); d->defn = xstrdup(defn+sizeof(BUILTIN_MARKER)-1); } else { if (!*defn) d->defn = __DECONST(char *, null); else d->defn = xstrdup(defn); d->type = MACRTYPE; } if (STREQ(name, defn)) d->type |= RECDEF; } static ndptr create_entry(const char *name) { const char *end = NULL; unsigned int i; ndptr n; i = ohash_qlookupi(¯os, name, &end); n = ohash_find(¯os, i); if (n == NULL) { n = ohash_create_entry(¯o_info, name, &end); ohash_insert(¯os, i, n); n->trace_flags = FLAG_NO_TRACE; n->builtin_type = MACRTYPE; n->d = NULL; } return n; } void macro_define(const char *name, const char *defn) { ndptr n = create_entry(name); if (n->d != NULL) { if (n->d->defn != null) - free(n->d->defn); + free_definition(n->d->defn); } else { n->d = xalloc(sizeof(struct macro_definition), NULL); n->d->next = NULL; } setup_definition(n->d, defn, name); } void macro_pushdef(const char *name, const char *defn) { ndptr n; struct macro_definition *d; n = create_entry(name); d = xalloc(sizeof(struct macro_definition), NULL); d->next = n->d; n->d = d; setup_definition(n->d, defn, name); } void macro_undefine(const char *name) { ndptr n = lookup(name); if (n != NULL) { struct macro_definition *r, *r2; for (r = n->d; r != NULL; r = r2) { r2 = r->next; if (r->defn != null) free(r->defn); free(r); } n->d = NULL; } } void macro_popdef(const char *name) { ndptr n = lookup(name); if (n != NULL) { struct macro_definition *r = n->d; if (r != NULL) { n->d = r->next; if (r->defn != null) free(r->defn); free(r); } } } void macro_for_all(void (*f)(const char *, struct macro_definition *)) { ndptr n; unsigned int i; for (n = ohash_first(¯os, &i); n != NULL; n = ohash_next(¯os, &i)) if (n->d != NULL) f(n->name, n->d); } void setup_builtin(const char *name, unsigned int type) { ndptr n; char *name2; if (prefix_builtins) { name2 = xalloc(strlen(name)+3+1, NULL); memcpy(name2, "m4_", 3); memcpy(name2 + 3, name, strlen(name)+1); } else name2 = xstrdup(name); n = create_entry(name2); n->builtin_type = type; n->d = xalloc(sizeof(struct macro_definition), NULL); n->d->defn = name2; n->d->type = type; n->d->next = NULL; } void mark_traced(const char *name, int on) { ndptr p; unsigned int i; if (name == NULL) { if (on) trace_flags |= TRACE_ALL; else trace_flags &= ~TRACE_ALL; for (p = ohash_first(¯os, &i); p != NULL; p = ohash_next(¯os, &i)) p->trace_flags = FLAG_NO_TRACE; } else { p = create_entry(name); p->trace_flags = on; } } ndptr macro_getbuiltin(const char *name) { ndptr p; p = lookup(name); if (p == NULL || p->builtin_type == MACRTYPE) return NULL; else return p; } + +/* XXX things are slightly more complicated than they seem. + * a macro may actually be "live" (in the middle of an expansion + * on the stack. + * So we actually may need to place it in an array for later... + */ + +static int kept_capacity = 0; +static int kept_size = 0; +static char **kept = NULL; + +static void +keep(char *ptr) +{ + if (kept_capacity <= kept_size) { + if (kept_capacity) + kept_capacity *= 2; + else + kept_capacity = 50; + kept = xreallocarray(kept, kept_capacity, + sizeof(char *), "Out of memory while saving %d strings\n", + kept_capacity); + } + kept[kept_size++] = ptr; +} + +static int +string_in_use(const char *ptr) +{ + int i; + for (i = 0; i <= sp; i++) { + if (sstack[i] == STORAGE_MACRO && mstack[i].sstr == ptr) + return 1; + } + return 0; +} + + +static void +free_definition(char *ptr) +{ + int i; + + /* first try to free old strings */ + for (i = 0; i < kept_size; i++) { + if (!string_in_use(kept[i])) { + kept_size--; + free(kept[i]); + if (i != kept_size) + kept[i] = kept[kept_size]; + i--; + } + } + + /* then deal with us */ + if (string_in_use(ptr)) + keep(ptr); + else + free(ptr); +} + Index: head/usr.bin/m4/m4.1 =================================================================== --- head/usr.bin/m4/m4.1 (revision 283088) +++ head/usr.bin/m4/m4.1 (revision 283089) @@ -1,512 +1,514 @@ .\" $NetBSD: m4.1,v 1.23 2012/04/08 22:00:39 wiz Exp $ .\" @(#) $OpenBSD: m4.1,v 1.62 2014/04/14 07:00:47 jmc Exp $ .\" .\" Copyright (c) 1989, 1993 .\" The Regents of the University of California. All rights reserved. .\" .\" This code is derived from software contributed to Berkeley by .\" Ozan Yigit at York University. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" 3. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $FreeBSD$ .\" -.Dd January 12, 2014 +.Dd $Mdocdate: April 14 2014 $ .Dt M4 1 .Os .Sh NAME .Nm m4 .Nd macro language processor .Sh SYNOPSIS .Nm .Op Fl gPs .Oo .Sm off .Fl D Ar name Op No = Ar value .Sm on .Oc .Op Fl d Ar flags .Op Fl I Ar dirname .Op Fl o Ar filename .Op Fl t Ar macro .Op Fl U Ns Ar name .Op Ar .Sh DESCRIPTION The .Nm utility is a macro processor that can be used as a front end to any language (e.g., C, ratfor, fortran, lex, and yacc). If no input files are given, .Nm reads from the standard input, otherwise files specified on the command line are processed in the given order. Input files can be regular files, files in the m4 include paths, or a single dash .Pq Sq - , denoting standard input. .Nm writes the processed text to the standard output, unless told otherwise. .Pp Macro calls have the form name(argument1[, argument2, ..., argumentN]). .Pp There cannot be any space following the macro name and the open parenthesis .Pq Sq \&( . If the macro name is not followed by an open parenthesis it is processed with no arguments. .Pp Macro names consist of a leading alphabetic or underscore possibly followed by alphanumeric or underscore characters, e.g., valid macro names match the pattern .Dq [a-zA-Z_][a-zA-Z0-9_]* . .Pp In arguments to macros, leading unquoted space, tab, and newline .Pq Sq \en characters are ignored. To quote strings, use left and right single quotes .Pq e.g., Sq \ \&this is a string with a leading space . You can change the quote characters with the .Ic changequote built-in macro. .Pp Most built-ins do not make any sense without arguments, and hence are not recognized as special when not followed by an open parenthesis. .Pp The options are as follows: .Bl -tag -width Ds -.It Fl D Ns Ar name Ns Op Pf = Ns Ar value +.It Fl D Ns Ar name Ns Oo +.Pf = Ns Ar value +.Oc Define the symbol .Ar name to have some value (or .Dv NULL ) . .It Fl d Ar "flags" Set trace flags. .Ar flags may hold the following: .Bl -tag -width Ds .It Ar a print macro arguments. .It Ar c print macro expansion over several lines. .It Ar e print result of macro expansion. .It Ar f print filename location. .It Ar l print line number. .It Ar q quote arguments and expansion with the current quotes. .It Ar t start with all macros traced. .It Ar x number macro expansions. .It Ar V turn on all options. .El .Pp By default, trace is set to .Qq eq . .It Fl g Activate GNU-m4 compatibility mode. In this mode, translit handles simple character ranges (e.g., a-z), regular expressions mimic emacs behavior, multiple m4wrap calls are handled as a stack, the number of diversions is unlimited, empty names for macro definitions are allowed, and eval understands .Sq 0rbase:value numbers. .It Fl I Ar "dirname" Add directory .Ar dirname to the include path. .It Fl o Ar filename Send trace output to .Ar filename . .It Fl P Prefix all built-in macros with .Sq m4_ . For example, instead of writing .Ic define , use .Ic m4_define . .It Fl s Output line synchronization directives, suitable for .Xr cpp 1 . .It Fl t Ar macro Turn tracing on for .Ar macro . .It Fl "U" Ns Ar "name" Undefine the symbol .Ar name . .El .Sh SYNTAX .Nm provides the following built-in macros. They may be redefined, losing their original meaning. Return values are null unless otherwise stated. .Bl -tag -width changequote .It Fn builtin name Calls a built-in by its .Fa name , overriding possible redefinitions. .It Fn changecom startcomment endcomment Changes the start comment and end comment sequences. Comment sequences may be up to five characters long. The default values are the hash sign and the newline character. .Bd -literal -offset indent # This is a comment .Ed .Pp With no arguments, comments are turned off. With one single argument, the end comment sequence is set to the newline character. .It Fn changequote beginquote endquote Defines the open quote and close quote sequences. Quote sequences may be up to five characters long. The default values are the backquote character and the quote character. .Bd -literal -offset indent `Here is a quoted string' .Ed .Pp With no arguments, the default quotes are restored. With one single argument, the close quote sequence is set to the newline character. .It Fn decr arg Decrements the argument .Fa arg by 1. The argument .Fa arg must be a valid numeric string. .It Fn define name value Define a new macro named by the first argument .Fa name to have the value of the second argument .Fa value . Each occurrence of .Sq $n (where .Ar n is 0 through 9) is replaced by the .Ar n Ns 'th argument. .Sq $0 is the name of the calling macro. Undefined arguments are replaced by a null string. .Sq $# is replaced by the number of arguments; .Sq $* is replaced by all arguments comma separated; .Sq $@ is the same as .Sq $* but all arguments are quoted against further expansion. .It Fn defn name ... Returns the quoted definition for each argument. This can be used to rename macro definitions (even for built-in macros). .It Fn divert num There are 10 output queues (numbered 0-9). At the end of processing .Nm concatenates all the queues in numerical order to produce the final output. Initially the output queue is 0. The divert macro allows you to select a new output queue (an invalid argument passed to divert causes output to be discarded). .It Ic divnum Returns the current output queue number. .It Ic dnl Discard input characters up to and including the next newline. .It Fn dumpdef name ... Prints the names and definitions for the named items, or for everything if no arguments are passed. .It Fn errprint msg Prints the first argument on the standard error output stream. .It Fn esyscmd cmd Passes its first argument to a shell and returns the shell's standard output. Note that the shell shares its standard input and standard error with .Nm . .It Fn eval expr[,radix[,minimum]] Computes the first argument as an arithmetic expression using 32-bit arithmetic. Operators are the standard C ternary, arithmetic, logical, shift, relational, bitwise, and parentheses operators. You can specify octal, decimal, and hexadecimal numbers as in C. The optional second argument .Fa radix specifies the radix for the result and the optional third argument .Fa minimum specifies the minimum number of digits in the result. .It Fn expr expr This is an alias for .Ic eval . .It Fn format formatstring arg1 ... Returns .Fa formatstring with escape sequences substituted with .Fa arg1 and following arguments, in a way similar to .Xr printf 3 . This built-in is only available in GNU-m4 compatibility mode, and the only parameters implemented are there for autoconf compatibility: left-padding flag, an optional field width, a maximum field width, *-specified field widths, and the %s and %c data type. .It Fn ifdef name yes no If the macro named by the first argument is defined then return the second argument, otherwise the third. If there is no third argument, the value is .Dv NULL . The word .Qq unix is predefined. .It Fn ifelse a b yes ... If the first argument .Fa a matches the second argument .Fa b then .Fn ifelse returns the third argument .Fa yes . If the match fails the three arguments are discarded and the next three arguments are used until there is zero or one arguments left, either this last argument or .Dv NULL is returned if no other matches were found. .It Fn include name Returns the contents of the file specified in the first argument. If the file is not found as is, look through the include path: first the directories specified with .Fl I on the command line, then the environment variable .Ev M4PATH , as a colon-separated list of directories. Include aborts with an error message if the file cannot be included. .It Fn incr arg Increments the argument by 1. The argument must be a valid numeric string. .It Fn index string substring Returns the index of the second argument in the first argument (e.g., .Ic index(the quick brown fox jumped, fox) returns 16). If the second argument is not found index returns \-1. .It Fn indir macro arg1 ... Indirectly calls the macro whose name is passed as the first argument, with the remaining arguments passed as first, ... arguments. .It Fn len arg Returns the number of characters in the first argument. Extra arguments are ignored. .It Fn m4exit code Immediately exits with the return value specified by the first argument, 0 if none. .It Fn m4wrap todo Allows you to define what happens at the final .Dv EOF , usually for cleanup purposes (e.g., .Ic m4wrap("cleanup(tempfile)") causes the macro cleanup to be invoked after all other processing is done). .Pp Multiple calls to .Fn m4wrap get inserted in sequence at the final .Dv EOF . .It Fn maketemp template Like .Ic mkstemp . .It Fn mkstemp template Invokes .Xr mkstemp 3 on the first argument, and returns the modified string. This can be used to create unique temporary file names. .It Fn paste file Includes the contents of the file specified by the first argument without any macro processing. Aborts with an error message if the file cannot be included. .It Fn patsubst string regexp replacement Substitutes a regular expression in a string with a replacement string. Usual substitution patterns apply: an ampersand .Pq Sq \&& is replaced by the string matching the regular expression. The string .Sq \e# , where .Sq # is a digit, is replaced by the corresponding back-reference. .It Fn popdef arg ... Restores the .Ic pushdef Ns ed definition for each argument. .It Fn pushdef macro def Takes the same arguments as .Ic define , but it saves the definition on a stack for later retrieval by .Fn popdef . .It Fn regexp string regexp replacement Finds a regular expression in a string. If no further arguments are given, it returns the first match position or \-1 if no match. If a third argument is provided, it returns the replacement string, with sub-patterns replaced. .It Fn shift arg1 ... Returns all but the first argument, the remaining arguments are quoted and pushed back with commas in between. The quoting nullifies the effect of the extra scan that will subsequently be performed. .It Fn sinclude file Similar to .Ic include , except it ignores any errors. .It Fn spaste file Similar to .Fn paste , except it ignores any errors. .It Fn substr string offset length Returns a substring of the first argument starting at the offset specified by the second argument and the length specified by the third argument. If no third argument is present it returns the rest of the string. .It Fn syscmd cmd Passes the first argument to the shell. Nothing is returned. .It Ic sysval Returns the return value from the last .Ic syscmd . .It Fn traceon arg ... Enables tracing of macro expansions for the given arguments, or for all macros if no argument is given. .It Fn traceoff arg ... Disables tracing of macro expansions for the given arguments, or for all macros if no argument is given. .It Fn translit string mapfrom mapto Transliterate the characters in the first argument from the set given by the second argument to the set given by the third. You cannot use .Xr tr 1 style abbreviations. .It Fn undefine name1 ... Removes the definition for the macros specified by its arguments. .It Fn undivert arg ... Flushes the named output queues (or all queues if no arguments). .It Ic unix A pre-defined macro for testing the OS platform. .It Ic __line__ Returns the current file's line number. .It Ic __file__ Returns the current file's name. .El .Sh EXIT STATUS .Ex -std m4 .Pp But note that the .Ic m4exit macro can modify the exit status. .Sh STANDARDS The .Nm utility is compliant with the .St -p1003.1-2008 specification. .Pp The flags .Op Fl dgIPot and the macros .Ic builtin , .Ic esyscmd , .Ic expr , .Ic format , .Ic indir , .Ic paste , .Ic patsubst , .Ic regexp , .Ic spaste , .Ic unix , .Ic __line__ , and .Ic __file__ are extensions to that specification. .Pp .Ic maketemp is not supposed to be a synonym for .Ic mkstemp , but instead to be an insecure temporary file name creation function. It is marked by .St -p1003.1-2008 as being obsolescent and should not be used if portability is a concern. .Pp The output format of .Ic traceon and .Ic dumpdef are not specified in any standard, are likely to change and should not be relied upon. The current format of tracing is closely modelled on .Nm gnu-m4 , to allow .Nm autoconf to work. .Pp The built-ins .Ic pushdef and .Ic popdef handle macro definitions as a stack. However, .Ic define interacts with the stack in an undefined way. In this implementation, .Ic define replaces the top-most definition only. Other implementations may erase all definitions on the stack instead. .Pp All built-ins do expand without arguments in many other .Nm . .Pp Many other .Nm have dire size limitations with respect to buffer sizes. .Sh AUTHORS .An -nosplit .An Ozan Yigit Aq Mt oz@sis.yorku.ca and .An Richard A. O'Keefe Aq Mt ok@goanna.cs.rmit.OZ.AU . .Pp GNU-m4 compatibility extensions by .An Marc Espie Aq Mt espie@cvs.openbsd.org . Index: head/usr.bin/m4/main.c =================================================================== --- head/usr.bin/m4/main.c (revision 283088) +++ head/usr.bin/m4/main.c (revision 283089) @@ -1,635 +1,638 @@ -/* $OpenBSD: main.c,v 1.83 2014/05/12 19:11:19 espie Exp $ */ +/* $OpenBSD: main.c,v 1.84 2014/12/21 09:33:12 espie Exp $ */ /* $NetBSD: main.c,v 1.12 1997/02/08 23:54:49 cgd Exp $ */ /*- * Copyright (c) 1989, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Ozan Yigit at York University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * main.c * Facility: m4 macro processor * by: oz */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include "mdef.h" #include "stdd.h" #include "extern.h" #include "pathnames.h" stae *mstack; /* stack of m4 machine */ char *sstack; /* shadow stack, for string space extension */ static size_t STACKMAX; /* current maximum size of stack */ int sp; /* current m4 stack pointer */ int fp; /* m4 call frame pointer */ struct input_file infile[MAXINP];/* input file stack (0=stdin) */ FILE **outfile; /* diversion array(0=bitbucket)*/ int maxout; FILE *active; /* active output file pointer */ int ilevel = 0; /* input file stack pointer */ int oindex = 0; /* diversion index.. */ const char *null = ""; /* as it says.. just a null.. */ char **m4wraps = NULL; /* m4wraps array. */ int maxwraps = 0; /* size of m4wraps array */ int wrapindex = 0; /* current offset in m4wraps */ char lquote[MAXCCHARS+1] = {LQUOTE}; /* left quote character (`) */ char rquote[MAXCCHARS+1] = {RQUOTE}; /* right quote character (') */ char scommt[MAXCCHARS+1] = {SCOMMT}; /* start character for comment */ char ecommt[MAXCCHARS+1] = {ECOMMT}; /* end character for comment */ int synch_lines = 0; /* line synchronisation for C preprocessor */ int prefix_builtins = 0; /* -P option to prefix builtin keywords */ struct keyblk { const char *knam; /* keyword name */ int ktyp; /* keyword type */ }; static struct keyblk keywrds[] = { /* m4 keywords to be installed */ { "include", INCLTYPE }, { "sinclude", SINCTYPE }, { "define", DEFITYPE }, { "defn", DEFNTYPE }, { "divert", DIVRTYPE | NOARGS }, { "expr", EXPRTYPE }, { "eval", EXPRTYPE }, { "substr", SUBSTYPE }, { "ifelse", IFELTYPE }, { "ifdef", IFDFTYPE }, { "len", LENGTYPE }, { "incr", INCRTYPE }, { "decr", DECRTYPE }, { "dnl", DNLNTYPE | NOARGS }, { "changequote", CHNQTYPE | NOARGS }, { "changecom", CHNCTYPE | NOARGS }, { "index", INDXTYPE }, #ifdef EXTENDED { "paste", PASTTYPE }, { "spaste", SPASTYPE }, /* Newer extensions, needed to handle gnu-m4 scripts */ { "indir", INDIRTYPE}, { "builtin", BUILTINTYPE}, { "patsubst", PATSTYPE}, { "regexp", REGEXPTYPE}, { "esyscmd", ESYSCMDTYPE}, { "__file__", FILENAMETYPE | NOARGS}, { "__line__", LINETYPE | NOARGS}, #endif { "popdef", POPDTYPE }, { "pushdef", PUSDTYPE }, { "dumpdef", DUMPTYPE | NOARGS }, { "shift", SHIFTYPE | NOARGS }, { "translit", TRNLTYPE }, { "undefine", UNDFTYPE }, { "undivert", UNDVTYPE | NOARGS }, { "divnum", DIVNTYPE | NOARGS }, { "maketemp", MKTMTYPE }, { "mkstemp", MKTMTYPE }, { "errprint", ERRPTYPE | NOARGS }, { "m4wrap", M4WRTYPE | NOARGS }, { "m4exit", EXITTYPE | NOARGS }, { "syscmd", SYSCTYPE }, { "sysval", SYSVTYPE | NOARGS }, { "traceon", TRACEONTYPE | NOARGS }, { "traceoff", TRACEOFFTYPE | NOARGS }, #if defined(unix) || defined(__unix__) { "unix", SELFTYPE | NOARGS }, #else #ifdef vms { "vms", SELFTYPE | NOARGS }, #endif #endif }; #define MAXKEYS (sizeof(keywrds)/sizeof(struct keyblk)) +extern int optind; +extern char *optarg; + #define MAXRECORD 50 static struct position { char *name; unsigned long line; } quotes[MAXRECORD], paren[MAXRECORD]; static void record(struct position *, int); static void dump_stack(struct position *, int); static void macro(void); static void initkwds(void); static ndptr inspect(int, char *); static int do_look_ahead(int, const char *); static void reallyoutputstr(const char *); static void reallyputchar(int); static void enlarge_stack(void); int main(int, char *[]); int exit_code = 0; int main(int argc, char *argv[]) { int c; int n; char *p; if (signal(SIGINT, SIG_IGN) != SIG_IGN) signal(SIGINT, onintr); init_macros(); initspaces(); STACKMAX = INITSTACKMAX; mstack = xreallocarray(NULL, STACKMAX, sizeof(stae), NULL); sstack = xalloc(STACKMAX, NULL); maxout = 0; outfile = NULL; resizedivs(MAXOUT); while ((c = getopt(argc, argv, "gst:d:D:U:o:I:P")) != -1) switch(c) { case 'D': /* define something..*/ for (p = optarg; *p; p++) if (*p == '=') break; if (*p) *p++ = EOS; dodefine(optarg, p); break; case 'I': addtoincludepath(optarg); break; case 'P': prefix_builtins = 1; break; case 'U': /* undefine... */ macro_popdef(optarg); break; case 'g': mimic_gnu = 1; break; case 'd': set_trace_flags(optarg); break; case 's': synch_lines = 1; break; case 't': mark_traced(optarg, 1); break; case 'o': trace_file(optarg); break; case '?': usage(); } argc -= optind; argv += optind; initkwds(); if (mimic_gnu) setup_builtin("format", FORMATTYPE); active = stdout; /* default active output */ bbase[0] = bufbase; if (!argc) { sp = -1; /* stack pointer initialized */ fp = 0; /* frame pointer initialized */ set_input(infile+0, stdin, "stdin"); /* default input (naturally) */ macro(); } else for (; argc--; ++argv) { p = *argv; if (p[0] == '-' && p[1] == EOS) set_input(infile, stdin, "stdin"); else if (fopen_trypath(infile, p) == NULL) err(1, "%s", p); sp = -1; fp = 0; macro(); release_input(infile); } if (wrapindex) { int i; ilevel = 0; /* in case m4wrap includes.. */ bufbase = bp = buf; /* use the entire buffer */ if (mimic_gnu) { while (wrapindex != 0) { for (i = 0; i < wrapindex; i++) pbstr(m4wraps[i]); wrapindex =0; macro(); } } else { for (i = 0; i < wrapindex; i++) { pbstr(m4wraps[i]); macro(); } } } if (active != stdout) active = stdout; /* reset output just in case */ for (n = 1; n < maxout; n++) /* default wrap-up: undivert */ if (outfile[n] != NULL) getdiv(n); /* remove bitbucket if used */ if (outfile[0] != NULL) { (void) fclose(outfile[0]); } return exit_code; } /* * Look ahead for `token'. * (on input `t == token[0]') * Used for comment and quoting delimiters. * Returns 1 if `token' present; copied to output. * 0 if `token' not found; all characters pushed back */ static int do_look_ahead(int t, const char *token) { int i; assert((unsigned char)t == (unsigned char)token[0]); for (i = 1; *++token; i++) { t = gpbc(); if (t == EOF || (unsigned char)t != (unsigned char)*token) { pushback(t); while (--i) pushback(*--token); return 0; } } return 1; } #define LOOK_AHEAD(t, token) (t != EOF && \ (unsigned char)(t)==(unsigned char)(token)[0] && \ do_look_ahead(t,token)) /* * macro - the work horse.. */ static void macro(void) { char token[MAXTOK+1]; int t, l; ndptr p; int nlpar; cycle { t = gpbc(); if (LOOK_AHEAD(t,lquote)) { /* strip quotes */ nlpar = 0; record(quotes, nlpar++); /* * Opening quote: scan forward until matching * closing quote has been found. */ do { l = gpbc(); if (LOOK_AHEAD(l,rquote)) { if (--nlpar > 0) outputstr(rquote); } else if (LOOK_AHEAD(l,lquote)) { record(quotes, nlpar++); outputstr(lquote); } else if (l == EOF) { if (nlpar == 1) warnx("unclosed quote:"); else warnx("%d unclosed quotes:", nlpar); dump_stack(quotes, nlpar); exit(1); } else { if (nlpar > 0) { if (sp < 0) reallyputchar(l); else CHRSAVE(l); } } } while (nlpar != 0); } else if (sp < 0 && LOOK_AHEAD(t, scommt)) { reallyoutputstr(scommt); for(;;) { t = gpbc(); if (LOOK_AHEAD(t, ecommt)) { reallyoutputstr(ecommt); break; } if (t == EOF) break; reallyputchar(t); } } else if (t == '_' || isalpha(t)) { p = inspect(t, token); if (p != NULL) pushback(l = gpbc()); if (p == NULL || (l != LPAREN && (macro_getdef(p)->type & NEEDARGS) != 0)) outputstr(token); else { /* * real thing.. First build a call frame: */ pushf(fp); /* previous call frm */ pushf(macro_getdef(p)->type); /* type of the call */ pushf(is_traced(p)); pushf(0); /* parenthesis level */ fp = sp; /* new frame pointer */ /* * now push the string arguments: */ - pushs1(macro_getdef(p)->defn); /* defn string */ + pushdef(p); /* defn string */ pushs1((char *)macro_name(p)); /* macro name */ pushs(ep); /* start next..*/ if (l != LPAREN && PARLEV == 0) { /* no bracks */ chrsave(EOS); if (sp == (int)STACKMAX) errx(1, "internal stack overflow"); eval((const char **) mstack+fp+1, 2, CALTYP, TRACESTATUS); ep = PREVEP; /* flush strspace */ sp = PREVSP; /* previous sp.. */ fp = PREVFP; /* rewind stack...*/ } } } else if (t == EOF) { if (!mimic_gnu /* you can puke right there */ && sp > -1 && ilevel <= 0) { warnx( "unexpected end of input, unclosed parenthesis:"); dump_stack(paren, PARLEV); exit(1); } if (ilevel <= 0) break; /* all done thanks.. */ release_input(infile+ilevel--); emit_synchline(); bufbase = bbase[ilevel]; continue; } else if (sp < 0) { /* not in a macro at all */ reallyputchar(t); /* output directly.. */ } else switch(t) { case LPAREN: if (PARLEV > 0) chrsave(t); while (isspace(l = gpbc())) /* skip blank, tab, nl.. */ if (PARLEV > 0) chrsave(l); pushback(l); record(paren, PARLEV++); break; case RPAREN: if (--PARLEV > 0) chrsave(t); else { /* end of argument list */ chrsave(EOS); if (sp == (int)STACKMAX) errx(1, "internal stack overflow"); eval((const char **) mstack+fp+1, sp-fp, CALTYP, TRACESTATUS); ep = PREVEP; /* flush strspace */ sp = PREVSP; /* previous sp.. */ fp = PREVFP; /* rewind stack...*/ } break; case COMMA: if (PARLEV == 1) { chrsave(EOS); /* new argument */ while (isspace(l = gpbc())) ; pushback(l); pushs(ep); } else chrsave(t); break; default: if (LOOK_AHEAD(t, scommt)) { char *cp; for (cp = scommt; *cp; cp++) chrsave(*cp); for(;;) { t = gpbc(); if (LOOK_AHEAD(t, ecommt)) { for (cp = ecommt; *cp; cp++) chrsave(*cp); break; } if (t == EOF) break; CHRSAVE(t); } } else CHRSAVE(t); /* stack the char */ break; } } } /* * output string directly, without pushing it for reparses. */ void outputstr(const char *s) { if (sp < 0) reallyoutputstr(s); else while (*s) CHRSAVE(*s++); } void reallyoutputstr(const char *s) { if (synch_lines) { while (*s) { fputc(*s, active); if (*s++ == '\n') { infile[ilevel].synch_lineno++; if (infile[ilevel].synch_lineno != infile[ilevel].lineno) do_emit_synchline(); } } } else fputs(s, active); } void reallyputchar(int c) { putc(c, active); if (synch_lines && c == '\n') { infile[ilevel].synch_lineno++; if (infile[ilevel].synch_lineno != infile[ilevel].lineno) do_emit_synchline(); } } /* * build an input token.. * consider only those starting with _ or A-Za-z. */ static ndptr inspect(int c, char *tp) { char *name = tp; char *etp = tp+MAXTOK; ndptr p; *tp++ = c; while ((isalnum(c = gpbc()) || c == '_') && tp < etp) *tp++ = c; if (c != EOF) PUSHBACK(c); *tp = EOS; /* token is too long, it won't match anything, but it can still * be output. */ if (tp == ep) { outputstr(name); while (isalnum(c = gpbc()) || c == '_') { if (sp < 0) reallyputchar(c); else CHRSAVE(c); } *name = EOS; return NULL; } p = ohash_find(¯os, ohash_qlookupi(¯os, name, (const char **)&tp)); if (p == NULL) return NULL; if (macro_getdef(p) == NULL) return NULL; return p; } /* * initkwds - initialise m4 keywords as fast as possible. * This very similar to install, but without certain overheads, * such as calling lookup. Malloc is not used for storing the * keyword strings, since we simply use the static pointers * within keywrds block. */ static void initkwds(void) { unsigned int type; int i; for (i = 0; i < (int)MAXKEYS; i++) { type = keywrds[i].ktyp & TYPEMASK; if ((keywrds[i].ktyp & NOARGS) == 0) type |= NEEDARGS; setup_builtin(keywrds[i].knam, type); } } static void record(struct position *t, int lev) { if (lev < MAXRECORD) { t[lev].name = CURRENT_NAME; t[lev].line = CURRENT_LINE; } } static void dump_stack(struct position *t, int lev) { int i; for (i = 0; i < lev; i++) { if (i == MAXRECORD) { fprintf(stderr, " ...\n"); break; } fprintf(stderr, " %s at line %lu\n", t[i].name, t[i].line); } } static void enlarge_stack(void) { STACKMAX += STACKMAX/2; mstack = xreallocarray(mstack, STACKMAX, sizeof(stae), "Evaluation stack overflow (%lu)", (unsigned long)STACKMAX); sstack = xrealloc(sstack, STACKMAX, "Evaluation stack overflow (%lu)", (unsigned long)STACKMAX); } Index: head/usr.bin/m4/mdef.h =================================================================== --- head/usr.bin/m4/mdef.h (revision 283088) +++ head/usr.bin/m4/mdef.h (revision 283089) @@ -1,229 +1,242 @@ -/* $OpenBSD: mdef.h,v 1.31 2011/09/27 07:24:02 espie Exp $ */ +/* $OpenBSD: mdef.h,v 1.32 2014/12/21 09:33:12 espie Exp $ */ /* $NetBSD: mdef.h,v 1.7 1996/01/13 23:25:27 pk Exp $ */ /* * Copyright (c) 1989, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Ozan Yigit at York University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)mdef.h 8.1 (Berkeley) 6/6/93 * $FreeBSD$ */ #ifdef __GNUC__ # define UNUSED __attribute__((__unused__)) #else # define UNUSED #endif #define MACRTYPE 1 #define DEFITYPE 2 #define EXPRTYPE 3 #define SUBSTYPE 4 #define IFELTYPE 5 #define LENGTYPE 6 #define CHNQTYPE 7 #define SYSCTYPE 8 #define UNDFTYPE 9 #define INCLTYPE 10 #define SINCTYPE 11 #define PASTTYPE 12 #define SPASTYPE 13 #define INCRTYPE 14 #define IFDFTYPE 15 #define PUSDTYPE 16 #define POPDTYPE 17 #define SHIFTYPE 18 #define DECRTYPE 19 #define DIVRTYPE 20 #define UNDVTYPE 21 #define DIVNTYPE 22 #define MKTMTYPE 23 #define ERRPTYPE 24 #define M4WRTYPE 25 #define TRNLTYPE 26 #define DNLNTYPE 27 #define DUMPTYPE 28 #define CHNCTYPE 29 #define INDXTYPE 30 #define SYSVTYPE 31 #define EXITTYPE 32 #define DEFNTYPE 33 #define SELFTYPE 34 #define INDIRTYPE 35 #define BUILTINTYPE 36 #define PATSTYPE 37 #define FILENAMETYPE 38 #define LINETYPE 39 #define REGEXPTYPE 40 #define ESYSCMDTYPE 41 #define TRACEONTYPE 42 #define TRACEOFFTYPE 43 #define FORMATTYPE 44 #define BUILTIN_MARKER "__builtin_" #define TYPEMASK 63 /* Keep bits really corresponding to a type. */ #define RECDEF 256 /* Pure recursive def, don't expand it */ #define NOARGS 512 /* builtin needs no args */ #define NEEDARGS 1024 /* mark builtin that need args with this */ /* * m4 special characters */ #define ARGFLAG '$' #define LPAREN '(' #define RPAREN ')' #define LQUOTE '`' #define RQUOTE '\'' #define COMMA ',' #define SCOMMT '#' #define ECOMMT '\n' #ifdef msdos #define system(str) (-1) #endif /* * other important constants */ #define EOS '\0' #define MAXINP 10 /* maximum include files */ #define MAXOUT 10 /* maximum # of diversions */ #define BUFSIZE 4096 /* starting size of pushback buffer */ #define INITSTACKMAX 4096 /* starting size of call stack */ #define STRSPMAX 4096 /* starting size of string space */ #define MAXTOK 512 /* maximum chars in a tokn */ #define MAXCCHARS 5 /* max size of comment/quote delim */ #define ALL 1 #define TOP 0 #define TRUE 1 #define FALSE 0 #define cycle for(;;) /* * m4 data structures */ typedef struct ndblock *ndptr; struct macro_definition { struct macro_definition *next; char *defn; /* definition.. */ unsigned int type; /* type of the entry.. */ }; struct ndblock { /* hashtable structure */ unsigned int builtin_type; unsigned int trace_flags; struct macro_definition *d; char name[1]; /* entry name.. */ }; typedef union { /* stack structure */ int sfra; /* frame entry */ char *sstr; /* string entry */ } stae; struct input_file { FILE *file; char *name; unsigned long lineno; unsigned long synch_lineno; /* used for -s */ int c; }; +#define STORAGE_STRSPACE 0 +#define STORAGE_MACRO 1 +#define STORAGE_OTHER 2 + #define CURRENT_NAME (infile[ilevel].name) #define CURRENT_LINE (infile[ilevel].lineno) /* * macros for readibility and/or speed * * gpbc() - get a possibly pushed-back character * pushf() - push a call frame entry onto stack * pushs() - push a string pointer onto stack */ #define gpbc() (bp > bufbase) ? *--bp : obtain_char(infile+ilevel) #define pushf(x) \ do { \ if (++sp == (int)STACKMAX) \ enlarge_stack();\ mstack[sp].sfra = (x); \ - sstack[sp] = 0; \ + sstack[sp] = STORAGE_OTHER; \ } while (0) #define pushs(x) \ do { \ if (++sp == (int)STACKMAX) \ enlarge_stack();\ mstack[sp].sstr = (x); \ - sstack[sp] = 1; \ + sstack[sp] = STORAGE_STRSPACE; \ } while (0) #define pushs1(x) \ do { \ if (++sp == (int)STACKMAX) \ enlarge_stack();\ mstack[sp].sstr = (x); \ - sstack[sp] = 0; \ + sstack[sp] = STORAGE_OTHER; \ } while (0) + +#define pushdef(p) \ + do { \ + if (++sp == (int)STACKMAX) \ + enlarge_stack();\ + mstack[sp].sstr = macro_getdef(p)->defn;\ + sstack[sp] = STORAGE_MACRO; \ + } while (0) + /* * . . * | . | <-- sp | . | * +-------+ +-----+ * | arg 3 ----------------------->| str | * +-------+ | . | * | arg 2 ---PREVEP-----+ . * +-------+ | * . | | | * +-------+ | +-----+ * | plev | PARLEV +-------->| str | * +-------+ | . | * | type | CALTYP . * +-------+ * | prcf ---PREVFP--+ * +-------+ | * | . | PREVSP | * . | * +-------+ | * | <----------+ * +-------+ * */ #define PARLEV (mstack[fp].sfra) #define CALTYP (mstack[fp-2].sfra) #define TRACESTATUS (mstack[fp-1].sfra) #define PREVEP (mstack[fp+3].sstr) #define PREVSP (fp-4) #define PREVFP (mstack[fp-3].sfra) Index: head/usr.bin/m4/misc.c =================================================================== --- head/usr.bin/m4/misc.c (revision 283088) +++ head/usr.bin/m4/misc.c (revision 283089) @@ -1,467 +1,468 @@ -/* $OpenBSD: misc.c,v 1.44 2014/05/12 19:11:19 espie Exp $ */ +/* $OpenBSD: misc.c,v 1.45 2014/12/21 09:33:12 espie Exp $ */ /* $NetBSD: misc.c,v 1.6 1995/09/28 05:37:41 tls Exp $ */ /* * Copyright (c) 1989, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Ozan Yigit at York University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include "mdef.h" #include "stdd.h" #include "extern.h" #include "pathnames.h" char *ep; /* first free char in strspace */ static char *strspace; /* string space for evaluation */ char *endest; /* end of string space */ static size_t strsize = STRSPMAX; static size_t bufsize = BUFSIZE; unsigned char *buf; /* push-back buffer */ unsigned char *bufbase; /* the base for current ilevel */ unsigned char *bbase[MAXINP]; /* the base for each ilevel */ unsigned char *bp; /* first available character */ unsigned char *endpbb; /* end of push-back buffer */ + /* * find the index of second str in the first str. */ ptrdiff_t indx(const char *s1, const char *s2) { char *t; t = strstr(s1, s2); if (t == NULL) return (-1); else return (t - s1); } /* * pushback - push character back onto input */ void pushback(int c) { if (c == EOF) return; if (bp >= endpbb) enlarge_bufspace(); *bp++ = c; } /* * pbstr - push string back onto input * pushback is replicated to improve * performance. */ void pbstr(const char *s) { size_t n; n = strlen(s); while (endpbb - bp <= (long)n) enlarge_bufspace(); while (n > 0) *bp++ = s[--n]; } /* * pbnum - convert number to string, push back on input. */ void pbnum(int n) { pbnumbase(n, 10, 0); } void pbnumbase(int n, int base, int d) { static char digits[36] = "0123456789abcdefghijklmnopqrstuvwxyz"; int num; int printed = 0; if (base > 36) m4errx(1, "base %d > 36: not supported.", base); if (base < 2) m4errx(1, "bad base %d for conversion.", base); num = (n < 0) ? -n : n; do { pushback(digits[num % base]); printed++; } while ((num /= base) > 0); if (n < 0) printed++; while (printed++ < d) pushback('0'); if (n < 0) pushback('-'); } /* * pbunsigned - convert unsigned long to string, push back on input. */ void pbunsigned(unsigned long n) { do { pushback(n % 10 + '0'); } while ((n /= 10) > 0); } void initspaces(void) { int i; strspace = xalloc(strsize+1, NULL); ep = strspace; endest = strspace+strsize; buf = xalloc(bufsize, NULL); bufbase = buf; bp = buf; endpbb = buf + bufsize; for (i = 0; i < MAXINP; i++) bbase[i] = buf; } void enlarge_strspace(void) { char *newstrspace; int i; strsize *= 2; newstrspace = malloc(strsize + 1); if (!newstrspace) errx(1, "string space overflow"); memcpy(newstrspace, strspace, strsize/2); for (i = 0; i <= sp; i++) - if (sstack[i]) + if (sstack[i] == STORAGE_STRSPACE) mstack[i].sstr = (mstack[i].sstr - strspace) + newstrspace; ep = (ep-strspace) + newstrspace; free(strspace); strspace = newstrspace; endest = strspace + strsize; } void enlarge_bufspace(void) { unsigned char *newbuf; int i; bufsize += bufsize/2; newbuf = xrealloc(buf, bufsize, "too many characters pushed back"); for (i = 0; i < MAXINP; i++) bbase[i] = (bbase[i]-buf)+newbuf; bp = (bp-buf)+newbuf; bufbase = (bufbase-buf)+newbuf; buf = newbuf; endpbb = buf+bufsize; } /* * chrsave - put single char on string space */ void chrsave(int c) { if (ep >= endest) enlarge_strspace(); *ep++ = c; } /* * read in a diversion file, and dispose it. */ void getdiv(int n) { int c; if (active == outfile[n]) m4errx(1, "undivert: diversion still active."); rewind(outfile[n]); while ((c = getc(outfile[n])) != EOF) putc(c, active); (void) fclose(outfile[n]); outfile[n] = NULL; } void onintr(int signo __unused) { #define intrmessage "m4: interrupted.\n" write(STDERR_FILENO, intrmessage, sizeof(intrmessage)-1); _exit(1); } /* * killdiv - get rid of the diversion files */ void killdiv(void) { int n; for (n = 0; n < maxout; n++) if (outfile[n] != NULL) { (void) fclose(outfile[n]); } } extern char *__progname; void -m4errx(int exitstatus, const char *fmt, ...) +m4errx(int eval, const char *fmt, ...) { fprintf(stderr, "%s: ", __progname); fprintf(stderr, "%s at line %lu: ", CURRENT_NAME, CURRENT_LINE); if (fmt != NULL) { va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); } fprintf(stderr, "\n"); - exit(exitstatus); + exit(eval); } /* * resizedivs: allocate more diversion files */ void resizedivs(int n) { int i; outfile = xreallocarray(outfile, n, sizeof(FILE *), "too many diverts %d", n); for (i = maxout; i < n; i++) outfile[i] = NULL; maxout = n; } void * xalloc(size_t n, const char *fmt, ...) { void *p = malloc(n); if (p == NULL) { if (fmt == NULL) err(1, "malloc"); else { va_list va; va_start(va, fmt); verr(1, fmt, va); va_end(va); } } return p; } void * xcalloc(size_t n, size_t s, const char *fmt, ...) { void *p = calloc(n, s); if (p == NULL) { if (fmt == NULL) err(1, "calloc"); else { va_list va; va_start(va, fmt); verr(1, fmt, va); va_end(va); } } return p; } void * xrealloc(void *old, size_t n, const char *fmt, ...) { char *p = realloc(old, n); if (p == NULL) { free(old); if (fmt == NULL) err(1, "realloc"); else { va_list va; va_start(va, fmt); verr(1, fmt, va); va_end(va); } } return p; } void * xreallocarray(void *old, size_t s1, size_t s2, const char *fmt, ...) { void *p = reallocarray(old, s1, s2); if (p == NULL) { free(old); if (fmt == NULL) err(1, "reallocarray"); else { va_list va; va_start(va, fmt); verr(1, fmt, va); va_end(va); } } return p; } char * xstrdup(const char *s) { char *p = strdup(s); if (p == NULL) err(1, "strdup"); return p; } void usage(void) { fprintf(stderr, "usage: m4 [-gPs] [-Dname[=value]] [-d flags] " "[-I dirname] [-o filename]\n" "\t[-t macro] [-Uname] [file ...]\n"); exit(1); } int obtain_char(struct input_file *f) { if (f->c == EOF) return EOF; f->c = fgetc(f->file); if (f->c == '\n') f->lineno++; return f->c; } void set_input(struct input_file *f, FILE *real, const char *name) { f->file = real; f->lineno = 1; f->c = 0; f->name = xstrdup(name); emit_synchline(); } void do_emit_synchline(void) { fprintf(active, "#line %lu \"%s\"\n", infile[ilevel].lineno, infile[ilevel].name); infile[ilevel].synch_lineno = infile[ilevel].lineno; } void release_input(struct input_file *f) { if (f->file != stdin) fclose(f->file); f->c = EOF; /* * XXX can't free filename, as there might still be * error information pointing to it. */ } void doprintlineno(struct input_file *f) { pbunsigned(f->lineno); } void doprintfilename(struct input_file *f) { pbstr(rquote); pbstr(f->name); pbstr(lquote); } /* * buffer_mark/dump_buffer: allows one to save a mark in a buffer, * and later dump everything that was added since then to a file. */ size_t buffer_mark(void) { return bp - buf; } void dump_buffer(FILE *f, size_t m) { unsigned char *s; for (s = bp; s-buf > (long)m;) fputc(*--s, f); } Index: head/usr.bin/m4/parser.y =================================================================== --- head/usr.bin/m4/parser.y (revision 283088) +++ head/usr.bin/m4/parser.y (revision 283089) @@ -1,92 +1,86 @@ %{ /* $OpenBSD: parser.y,v 1.7 2012/04/12 17:00:11 espie Exp $ */ /* * Copyright (c) 2004 Marc Espie * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * $FreeBSD$ */ #include -#include -#include #include - -#include "mdef.h" -#include "extern.h" - #define YYSTYPE int32_t - +extern int32_t end_result; extern int yylex(void); extern int yyerror(const char *); %} %token NUMBER %token ERROR %left LOR %left LAND %left '|' %left '^' %left '&' %left EQ NE %left '<' LE '>' GE %left LSHIFT RSHIFT %left '+' '-' %left '*' '/' '%' %right EXPONENT %right UMINUS UPLUS '!' '~' %% top : expr { end_result = $1; } ; expr : expr '+' expr { $$ = $1 + $3; } | expr '-' expr { $$ = $1 - $3; } | expr EXPONENT expr { $$ = pow($1, $3); } | expr '*' expr { $$ = $1 * $3; } | expr '/' expr { if ($3 == 0) { yyerror("division by zero"); exit(1); } $$ = $1 / $3; } | expr '%' expr { if ($3 == 0) { yyerror("modulo zero"); exit(1); } $$ = $1 % $3; } | expr LSHIFT expr { $$ = $1 << $3; } | expr RSHIFT expr { $$ = $1 >> $3; } | expr '<' expr { $$ = $1 < $3; } | expr '>' expr { $$ = $1 > $3; } | expr LE expr { $$ = $1 <= $3; } | expr GE expr { $$ = $1 >= $3; } | expr EQ expr { $$ = $1 == $3; } | expr NE expr { $$ = $1 != $3; } | expr '&' expr { $$ = $1 & $3; } | expr '^' expr { $$ = $1 ^ $3; } | expr '|' expr { $$ = $1 | $3; } | expr LAND expr { $$ = $1 && $3; } | expr LOR expr { $$ = $1 || $3; } | '(' expr ')' { $$ = $2; } | '-' expr %prec UMINUS { $$ = -$2; } | '+' expr %prec UPLUS { $$ = $2; } | '!' expr { $$ = !$2; } | '~' expr { $$ = ~$2; } | NUMBER ; %%