1 /* $OpenBSD: gnum4.c,v 1.50 2015/04/29 00:13:26 millert Exp $ */
4 * Copyright (c) 1999 Marc Espie
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
31 * functions needed to support gnu-m4 extensions, including a fake freezing
34 #include <sys/types.h>
56 * Support for include path search
57 * First search in the current directory.
58 * If not found, and the path is not absolute, include path kicks in.
59 * First, -I options, in the order found on the command line.
60 * Then M4PATH env variable
63 static struct path_entry {
65 struct path_entry *next;
68 static struct path_entry *new_path_entry(const char *);
69 static void ensure_m4path(void);
70 static struct input_file *dopath(struct input_file *, const char *);
72 static struct path_entry *
73 new_path_entry(const char *dirname)
77 n = malloc(sizeof(struct path_entry));
79 errx(1, "out of memory");
80 n->name = xstrdup(dirname);
86 addtoincludepath(const char *dirname)
90 n = new_path_entry(dirname);
103 static int envpathdone = 0;
111 envpath = getenv("M4PATH");
114 /* for portability: getenv result is read-only */
115 envpath = xstrdup(envpath);
116 for (sweep = envpath;
117 (path = strsep(&sweep, ":")) != NULL;)
118 addtoincludepath(path);
124 dopath(struct input_file *i, const char *filename)
127 struct path_entry *pe;
130 for (pe = first; pe; pe = pe->next) {
131 snprintf(path, sizeof(path), "%s/%s", pe->name, filename);
132 if ((f = fopen(path, "r")) != NULL) {
133 set_input(i, f, path);
141 fopen_trypath(struct input_file *i, const char *filename)
145 f = fopen(filename, "r");
147 set_input(i, f, filename);
150 if (filename[0] == '/')
155 return dopath(i, filename);
159 doindir(const char *argv[], int argc)
162 struct macro_definition *p = NULL;
165 if (n == NULL || (p = macro_getdef(n)) == NULL)
166 m4errx(1, "indir: undefined macro %s.", argv[2]);
169 eval(argv+1, argc-1, p->type, is_traced(n));
173 dobuiltin(const char *argv[], int argc)
178 p = macro_getbuiltin(argv[2]);
180 eval(argv+1, argc-1, macro_builtin_type(p), is_traced(p));
182 m4errx(1, "unknown builtin %s.", argv[2]);
186 /* We need some temporary buffer space, as pb pushes BACK and substitution
187 * proceeds forward... */
189 static size_t bufsize = 0;
190 static size_t current = 0;
192 static void addchars(const char *, size_t);
193 static void addchar(int);
194 static char *twiddle(const char *);
195 static char *getstring(void);
196 static void exit_regerror(int, regex_t *, const char *);
197 static void do_subst(const char *, regex_t *, const char *, const char *,
199 static void do_regexpindex(const char *, regex_t *, const char *, regmatch_t *);
200 static void do_regexp(const char *, regex_t *, const char *, const char *,
202 static void add_sub(int, const char *, regex_t *, regmatch_t *);
203 static void add_replace(const char *, regex_t *, const char *, regmatch_t *);
204 #define addconstantstring(s) addchars((s), sizeof(s)-1)
207 addchars(const char *c, size_t n)
211 while (current + n > bufsize) {
214 else if (bufsize <= SIZE_MAX/2) {
217 errx(1, "size overflow");
219 buffer = xrealloc(buffer, bufsize, NULL);
221 memcpy(buffer+current, c, n);
228 if (current +1 > bufsize) {
233 buffer = xrealloc(buffer, bufsize, NULL);
235 buffer[current++] = c;
248 exit_regerror(int er, regex_t *re, const char *source)
253 errlen = regerror(er, re, NULL, 0);
254 errbuf = xalloc(errlen,
255 "malloc in regerror: %lu", (unsigned long)errlen);
256 regerror(er, re, errbuf, errlen);
257 m4errx(1, "regular expression error in %s: %s.", source, errbuf);
261 add_sub(int n, const char *string, regex_t *re, regmatch_t *pm)
263 if (n > (int)re->re_nsub)
264 warnx("No subexpression %d", n);
265 /* Subexpressions that did not match are
267 else if (pm[n].rm_so != -1 &&
269 addchars(string + pm[n].rm_so,
270 pm[n].rm_eo - pm[n].rm_so);
274 /* Add replacement string to the output buffer, recognizing special
275 * constructs and replacing them with substrings of the original string.
278 add_replace(const char *string, regex_t *re, const char *replace, regmatch_t *pm)
282 for (p = replace; *p != '\0'; p++) {
283 if (*p == '&' && !mimic_gnu) {
284 add_sub(0, string, re, pm);
295 add_sub(0, string, re, pm);
301 if (isdigit((unsigned char)p[1])) {
302 add_sub(*(++p) - '0', string, re, pm);
311 do_subst(const char *string, regex_t *re, const char *source,
312 const char *replace, regmatch_t *pm)
316 const char *last_match = NULL;
318 while ((error = regexec(re, string, re->re_nsub+1, pm, flags)) == 0) {
319 if (pm[0].rm_eo != 0) {
320 if (string[pm[0].rm_eo-1] == '\n')
326 /* NULL length matches are special... We use the `vi-mode'
327 * rule: don't allow a NULL-match at the last match
330 if (pm[0].rm_so == pm[0].rm_eo &&
331 string + pm[0].rm_so == last_match) {
335 if (*string++ == '\n')
341 last_match = string + pm[0].rm_so;
342 addchars(string, pm[0].rm_so);
343 add_replace(string, re, replace, pm);
344 string += pm[0].rm_eo;
346 if (error != REG_NOMATCH)
347 exit_regerror(error, re, source);
352 do_regexp(const char *string, regex_t *re, const char *source,
353 const char *replace, regmatch_t *pm)
357 switch(error = regexec(re, string, re->re_nsub+1, pm, 0)) {
359 add_replace(string, re, replace, pm);
365 exit_regerror(error, re, source);
370 do_regexpindex(const char *string, regex_t *re, const char *source,
375 switch(error = regexec(re, string, re->re_nsub+1, pm, 0)) {
377 pbunsigned(pm[0].rm_so);
383 exit_regerror(error, re, source);
387 /* In Gnu m4 mode, parentheses for backmatch don't work like POSIX 1003.2
388 * says. So we twiddle with the regexp before passing it to regcomp.
391 twiddle(const char *p)
393 /* + at start of regexp is a normal character for Gnu m4 */
401 /* This could use strcspn for speed... */
411 addconstantstring("[_a-zA-Z0-9]");
414 addconstantstring("[^_a-zA-Z0-9]");
417 addconstantstring("[[:<:]]");
420 addconstantstring("[[:>:]]");
429 if (*p == '(' || *p == ')' || *p == '|')
438 /* patsubst(string, regexp, opt replacement) */
444 dopatsubst(const char *argv[], int argc)
447 warnx("Too few arguments to patsubst");
450 /* special case: empty regexp */
451 if (argv[3][0] == '\0') {
454 if (argc > 4 && argv[4])
455 len = strlen(argv[4]);
458 for (s = argv[2]; *s != '\0'; s++) {
459 addchars(argv[4], len);
466 int mode = REG_EXTENDED;
468 size_t l = strlen(argv[3]);
471 (argv[3][0] == '^') ||
472 (l > 0 && argv[3][l-1] == '$'))
475 source = mimic_gnu ? twiddle(argv[3]) : argv[3];
476 error = regcomp(&re, source, mode);
478 exit_regerror(error, &re, source);
480 pmatch = xreallocarray(NULL, re.re_nsub+1, sizeof(regmatch_t),
482 do_subst(argv[2], &re, source,
483 argc > 4 && argv[4] != NULL ? argv[4] : "", pmatch);
491 doregexp(const char *argv[], int argc)
499 warnx("Too few arguments to regexp");
502 /* special gnu case */
503 if (argv[3][0] == '\0' && mimic_gnu) {
504 if (argc == 4 || argv[4] == NULL)
509 source = mimic_gnu ? twiddle(argv[3]) : argv[3];
510 error = regcomp(&re, source, REG_EXTENDED|REG_NEWLINE);
512 exit_regerror(error, &re, source);
514 pmatch = xreallocarray(NULL, re.re_nsub+1, sizeof(regmatch_t), NULL);
515 if (argc == 4 || argv[4] == NULL)
516 do_regexpindex(argv[2], &re, source, pmatch);
518 do_regexp(argv[2], &re, source, argv[4], pmatch);
524 doformat(const char *argv[], int argc)
526 const char *format = argv[2];
531 const char *thisarg = NULL;
535 while (*format != 0) {
536 if (*format != '%') {
542 if (*format == '%') {
551 if (*format == '*') {
555 "Format with too many format specifiers.");
556 width = strtol(argv[pos++], NULL, 10);
558 width = strtol(format, __DECONST(char **,&format), 10);
566 if (*format == '.') {
568 if (*format == '*') {
572 "Format with too many format specifiers.");
573 extra = strtol(argv[pos++], NULL, 10);
575 extra = strtol(format, __DECONST(char **, &format), 10);
581 m4errx(1, "Format with too many format specifiers.");
584 thisarg = argv[pos++];
587 temp[0] = strtoul(argv[pos++], NULL, 10);
592 m4errx(1, "Unsupported format specification: %s.",
600 while ((long)l < width--)
603 addchars(thisarg, l);
605 while ((long)l < width--)
613 doesyscmd(const char *cmd)
621 /* Follow gnu m4 documentation: first flush buffers. */
624 argv[0] = __DECONST(char *, "sh");
625 argv[1] = __DECONST(char *, "-c");
626 argv[2] = __DECONST(char *, cmd);
629 /* Just set up standard output, share stderr and stdin with m4 */
632 switch(cpid = fork()) {
638 (void) dup2(p[1], 1);
640 execv(_PATH_BSHELL, argv);
643 /* Read result in two stages, since m4's buffer is
647 char result[BUFSIZE];
648 cc = read(p[0], result, sizeof result);
650 addchars(result, cc);
651 } while (cc > 0 || (cc == -1 && errno == EINTR));
654 while ((pid = wait(&status)) != cpid && pid >= 0)
661 getdivfile(const char *name)
666 f = fopen(name, "r");
670 while ((c = getc(f))!= EOF)