1 /* $OpenBSD: gnum4.c,v 1.50 2015/04/29 00:13:26 millert Exp $ */
4 * SPDX-License-Identifier: BSD-2-Clause
6 * Copyright (c) 1999 Marc Espie
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
33 * functions needed to support gnu-m4 extensions, including a fake freezing
36 #include <sys/types.h>
58 * Support for include path search
59 * First search in the current directory.
60 * If not found, and the path is not absolute, include path kicks in.
61 * First, -I options, in the order found on the command line.
62 * Then M4PATH env variable
65 static struct path_entry {
67 struct path_entry *next;
70 static struct path_entry *new_path_entry(const char *);
71 static void ensure_m4path(void);
72 static struct input_file *dopath(struct input_file *, const char *);
74 static struct path_entry *
75 new_path_entry(const char *dirname)
79 n = malloc(sizeof(struct path_entry));
81 errx(1, "out of memory");
82 n->name = xstrdup(dirname);
88 addtoincludepath(const char *dirname)
92 n = new_path_entry(dirname);
105 static int envpathdone = 0;
113 envpath = getenv("M4PATH");
116 /* for portability: getenv result is read-only */
117 envpath = xstrdup(envpath);
118 for (sweep = envpath;
119 (path = strsep(&sweep, ":")) != NULL;)
120 addtoincludepath(path);
126 dopath(struct input_file *i, const char *filename)
129 struct path_entry *pe;
132 for (pe = first; pe; pe = pe->next) {
133 snprintf(path, sizeof(path), "%s/%s", pe->name, filename);
134 if ((f = fopen(path, "r")) != NULL) {
135 set_input(i, f, path);
143 fopen_trypath(struct input_file *i, const char *filename)
147 f = fopen(filename, "r");
149 set_input(i, f, filename);
152 if (filename[0] == '/')
157 return dopath(i, filename);
161 doindir(const char *argv[], int argc)
164 struct macro_definition *p = NULL;
167 if (n == NULL || (p = macro_getdef(n)) == NULL)
168 m4errx(1, "indir: undefined macro %s.", argv[2]);
171 eval(argv+1, argc-1, p->type, is_traced(n));
175 dobuiltin(const char *argv[], int argc)
180 p = macro_getbuiltin(argv[2]);
182 eval(argv+1, argc-1, macro_builtin_type(p), is_traced(p));
184 m4errx(1, "unknown builtin %s.", argv[2]);
188 /* We need some temporary buffer space, as pb pushes BACK and substitution
189 * proceeds forward... */
191 static size_t bufsize = 0;
192 static size_t current = 0;
194 static void addchars(const char *, size_t);
195 static void addchar(int);
196 static char *twiddle(const char *);
197 static char *getstring(void);
198 static void exit_regerror(int, regex_t *, const char *);
199 static void do_subst(const char *, regex_t *, const char *, const char *,
201 static void do_regexpindex(const char *, regex_t *, const char *, regmatch_t *);
202 static void do_regexp(const char *, regex_t *, const char *, const char *,
204 static void add_sub(int, const char *, regex_t *, regmatch_t *);
205 static void add_replace(const char *, regex_t *, const char *, regmatch_t *);
206 #define addconstantstring(s) addchars((s), sizeof(s)-1)
209 addchars(const char *c, size_t n)
213 while (current + n > bufsize) {
216 else if (bufsize <= SIZE_MAX/2) {
219 errx(1, "size overflow");
221 buffer = xrealloc(buffer, bufsize, NULL);
223 memcpy(buffer+current, c, n);
230 if (current +1 > bufsize) {
235 buffer = xrealloc(buffer, bufsize, NULL);
237 buffer[current++] = c;
250 exit_regerror(int er, regex_t *re, const char *source)
255 errlen = regerror(er, re, NULL, 0);
256 errbuf = xalloc(errlen,
257 "malloc in regerror: %lu", (unsigned long)errlen);
258 regerror(er, re, errbuf, errlen);
259 m4errx(1, "regular expression error in %s: %s.", source, errbuf);
263 add_sub(int n, const char *string, regex_t *re, regmatch_t *pm)
265 if (n > (int)re->re_nsub)
266 warnx("No subexpression %d", n);
267 /* Subexpressions that did not match are
269 else if (pm[n].rm_so != -1 &&
271 addchars(string + pm[n].rm_so,
272 pm[n].rm_eo - pm[n].rm_so);
276 /* Add replacement string to the output buffer, recognizing special
277 * constructs and replacing them with substrings of the original string.
280 add_replace(const char *string, regex_t *re, const char *replace, regmatch_t *pm)
284 for (p = replace; *p != '\0'; p++) {
285 if (*p == '&' && !mimic_gnu) {
286 add_sub(0, string, re, pm);
297 add_sub(0, string, re, pm);
303 if (isdigit((unsigned char)p[1])) {
304 add_sub(*(++p) - '0', string, re, pm);
313 do_subst(const char *string, regex_t *re, const char *source,
314 const char *replace, regmatch_t *pm)
318 const char *last_match = NULL;
320 while ((error = regexec(re, string, re->re_nsub+1, pm, flags)) == 0) {
321 if (pm[0].rm_eo != 0) {
322 if (string[pm[0].rm_eo-1] == '\n')
328 /* NULL length matches are special... We use the `vi-mode'
329 * rule: don't allow a NULL-match at the last match
332 if (pm[0].rm_so == pm[0].rm_eo &&
333 string + pm[0].rm_so == last_match) {
337 if (*string++ == '\n')
343 last_match = string + pm[0].rm_so;
344 addchars(string, pm[0].rm_so);
345 add_replace(string, re, replace, pm);
346 string += pm[0].rm_eo;
348 if (error != REG_NOMATCH)
349 exit_regerror(error, re, source);
354 do_regexp(const char *string, regex_t *re, const char *source,
355 const char *replace, regmatch_t *pm)
359 switch(error = regexec(re, string, re->re_nsub+1, pm, 0)) {
361 add_replace(string, re, replace, pm);
367 exit_regerror(error, re, source);
372 do_regexpindex(const char *string, regex_t *re, const char *source,
377 switch(error = regexec(re, string, re->re_nsub+1, pm, 0)) {
379 pbunsigned(pm[0].rm_so);
385 exit_regerror(error, re, source);
389 /* In Gnu m4 mode, parentheses for backmatch don't work like POSIX 1003.2
390 * says. So we twiddle with the regexp before passing it to regcomp.
393 twiddle(const char *p)
395 /* + at start of regexp is a normal character for Gnu m4 */
403 /* This could use strcspn for speed... */
413 addconstantstring("[_a-zA-Z0-9]");
416 addconstantstring("[^_a-zA-Z0-9]");
419 addconstantstring("[[:<:]]");
422 addconstantstring("[[:>:]]");
431 if (*p == '(' || *p == ')' || *p == '|')
440 /* patsubst(string, regexp, opt replacement) */
446 dopatsubst(const char *argv[], int argc)
449 warnx("Too few arguments to patsubst");
452 /* special case: empty regexp */
453 if (argv[3][0] == '\0') {
456 if (argc > 4 && argv[4])
457 len = strlen(argv[4]);
460 for (s = argv[2]; *s != '\0'; s++) {
461 addchars(argv[4], len);
468 int mode = REG_EXTENDED;
470 size_t l = strlen(argv[3]);
473 (argv[3][0] == '^') ||
474 (l > 0 && argv[3][l-1] == '$'))
477 source = mimic_gnu ? twiddle(argv[3]) : argv[3];
478 error = regcomp(&re, source, mode);
480 exit_regerror(error, &re, source);
482 pmatch = xreallocarray(NULL, re.re_nsub+1, sizeof(regmatch_t),
484 do_subst(argv[2], &re, source,
485 argc > 4 && argv[4] != NULL ? argv[4] : "", pmatch);
493 doregexp(const char *argv[], int argc)
501 warnx("Too few arguments to regexp");
504 /* special gnu case */
505 if (argv[3][0] == '\0' && mimic_gnu) {
506 if (argc == 4 || argv[4] == NULL)
511 source = mimic_gnu ? twiddle(argv[3]) : argv[3];
512 error = regcomp(&re, source, REG_EXTENDED|REG_NEWLINE);
514 exit_regerror(error, &re, source);
516 pmatch = xreallocarray(NULL, re.re_nsub+1, sizeof(regmatch_t), NULL);
517 if (argc == 4 || argv[4] == NULL)
518 do_regexpindex(argv[2], &re, source, pmatch);
520 do_regexp(argv[2], &re, source, argv[4], pmatch);
526 doformat(const char *argv[], int argc)
528 const char *format = argv[2];
533 const char *thisarg = NULL;
537 while (*format != 0) {
538 if (*format != '%') {
544 if (*format == '%') {
553 if (*format == '*') {
557 "Format with too many format specifiers.");
558 width = strtol(argv[pos++], NULL, 10);
560 width = strtol(format, __DECONST(char **,&format), 10);
568 if (*format == '.') {
570 if (*format == '*') {
574 "Format with too many format specifiers.");
575 extra = strtol(argv[pos++], NULL, 10);
577 extra = strtol(format, __DECONST(char **, &format), 10);
583 m4errx(1, "Format with too many format specifiers.");
586 thisarg = argv[pos++];
589 temp[0] = strtoul(argv[pos++], NULL, 10);
594 m4errx(1, "Unsupported format specification: %s.",
602 while ((long)l < width--)
605 addchars(thisarg, l);
607 while ((long)l < width--)
615 doesyscmd(const char *cmd)
623 /* Follow gnu m4 documentation: first flush buffers. */
626 argv[0] = __DECONST(char *, "sh");
627 argv[1] = __DECONST(char *, "-c");
628 argv[2] = __DECONST(char *, cmd);
631 /* Just set up standard output, share stderr and stdin with m4 */
634 switch(cpid = fork()) {
640 (void) dup2(p[1], 1);
642 execv(_PATH_BSHELL, argv);
645 /* Read result in two stages, since m4's buffer is
649 char result[BUFSIZE];
650 cc = read(p[0], result, sizeof result);
652 addchars(result, cc);
653 } while (cc > 0 || (cc == -1 && errno == EINTR));
656 while ((pid = wait(&status)) != cpid && pid >= 0)
663 getdivfile(const char *name)
668 f = fopen(name, "r");
672 while ((c = getc(f))!= EOF)