1 /* $OpenBSD: gnum4.c,v 1.52 2017/08/21 21:41:13 deraadt 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>
31 * functions needed to support gnu-m4 extensions, including a fake freezing
34 #include <sys/types.h>
57 * Support for include path search
58 * First search in the current directory.
59 * If not found, and the path is not absolute, include path kicks in.
60 * First, -I options, in the order found on the command line.
61 * Then M4PATH env variable
64 static struct path_entry {
66 struct path_entry *next;
69 static struct path_entry *new_path_entry(const char *);
70 static void ensure_m4path(void);
71 static struct input_file *dopath(struct input_file *, const char *);
73 static struct path_entry *
74 new_path_entry(const char *dirname)
78 n = malloc(sizeof(struct path_entry));
80 errx(1, "out of memory");
81 n->name = xstrdup(dirname);
87 addtoincludepath(const char *dirname)
91 n = new_path_entry(dirname);
104 static int envpathdone = 0;
112 envpath = getenv("M4PATH");
115 /* for portability: getenv result is read-only */
116 envpath = xstrdup(envpath);
117 for (sweep = envpath;
118 (path = strsep(&sweep, ":")) != NULL;)
119 addtoincludepath(path);
125 dopath(struct input_file *i, const char *filename)
128 struct path_entry *pe;
131 for (pe = first; pe; pe = pe->next) {
132 snprintf(path, sizeof(path), "%s/%s", pe->name, filename);
133 if ((f = fopen(path, "r")) != NULL) {
134 set_input(i, f, path);
142 fopen_trypath(struct input_file *i, const char *filename)
146 f = fopen(filename, "r");
148 set_input(i, f, filename);
151 if (filename[0] == '/')
156 return dopath(i, filename);
160 doindir(const char *argv[], int argc)
163 struct macro_definition *p = NULL;
166 if (n == NULL || (p = macro_getdef(n)) == NULL)
167 m4errx(1, "indir: undefined macro %s.", argv[2]);
170 eval(argv+1, argc-1, p->type, is_traced(n));
174 dobuiltin(const char *argv[], int argc)
179 p = macro_getbuiltin(argv[2]);
181 eval(argv+1, argc-1, macro_builtin_type(p), is_traced(p));
183 m4errx(1, "unknown builtin %s.", argv[2]);
187 /* We need some temporary buffer space, as pb pushes BACK and substitution
188 * proceeds forward... */
190 static size_t bufsize = 0;
191 static size_t current = 0;
193 static void addchars(const char *, size_t);
194 static void addchar(int);
195 static char *twiddle(const char *);
196 static char *getstring(void);
197 static void exit_regerror(int, regex_t *, const char *);
198 static void do_subst(const char *, regex_t *, const char *, const char *,
200 static void do_regexpindex(const char *, regex_t *, const char *, regmatch_t *);
201 static void do_regexp(const char *, regex_t *, const char *, const char *,
203 static void add_sub(int, const char *, regex_t *, regmatch_t *);
204 static void add_replace(const char *, regex_t *, const char *, regmatch_t *);
205 #define addconstantstring(s) addchars((s), sizeof(s)-1)
208 addchars(const char *c, size_t n)
212 while (current + n > bufsize) {
215 else if (bufsize <= SIZE_MAX/2) {
218 errx(1, "size overflow");
220 buffer = xrealloc(buffer, bufsize, NULL);
222 memcpy(buffer+current, c, n);
229 if (current +1 > bufsize) {
234 buffer = xrealloc(buffer, bufsize, NULL);
236 buffer[current++] = c;
249 exit_regerror(int er, regex_t *re, const char *source)
254 errlen = regerror(er, re, NULL, 0);
255 errbuf = xalloc(errlen,
256 "malloc in regerror: %lu", (unsigned long)errlen);
257 regerror(er, re, errbuf, errlen);
258 m4errx(1, "regular expression error in %s: %s.", source, errbuf);
261 /* warnx() plus check to see if we need to change exit code or exit .
262 * -E flag functionality.
265 m4_warnx(const char *fmt, ...)
280 add_sub(int n, const char *string, regex_t *re, regmatch_t *pm)
282 if (n > (int)re->re_nsub)
283 m4_warnx("No subexpression %d", n);
284 /* Subexpressions that did not match are
286 else if (pm[n].rm_so != -1 &&
288 addchars(string + pm[n].rm_so,
289 pm[n].rm_eo - pm[n].rm_so);
293 /* Add replacement string to the output buffer, recognizing special
294 * constructs and replacing them with substrings of the original string.
297 add_replace(const char *string, regex_t *re, const char *replace, regmatch_t *pm)
301 for (p = replace; *p != '\0'; p++) {
302 if (*p == '&' && !mimic_gnu) {
303 add_sub(0, string, re, pm);
314 add_sub(0, string, re, pm);
320 if (isdigit((unsigned char)p[1])) {
321 add_sub(*(++p) - '0', string, re, pm);
330 do_subst(const char *string, regex_t *re, const char *source,
331 const char *replace, regmatch_t *pm)
335 const char *last_match = NULL;
337 while ((error = regexec(re, string, re->re_nsub+1, pm, flags)) == 0) {
338 if (pm[0].rm_eo != 0) {
339 if (string[pm[0].rm_eo-1] == '\n')
345 /* NULL length matches are special... We use the `vi-mode'
346 * rule: don't allow a NULL-match at the last match
349 if (pm[0].rm_so == pm[0].rm_eo &&
350 string + pm[0].rm_so == last_match) {
354 if (*string++ == '\n')
360 last_match = string + pm[0].rm_so;
361 addchars(string, pm[0].rm_so);
362 add_replace(string, re, replace, pm);
363 string += pm[0].rm_eo;
365 if (error != REG_NOMATCH)
366 exit_regerror(error, re, source);
371 do_regexp(const char *string, regex_t *re, const char *source,
372 const char *replace, regmatch_t *pm)
376 switch(error = regexec(re, string, re->re_nsub+1, pm, 0)) {
378 add_replace(string, re, replace, pm);
384 exit_regerror(error, re, source);
389 do_regexpindex(const char *string, regex_t *re, const char *source,
394 switch(error = regexec(re, string, re->re_nsub+1, pm, 0)) {
396 pbunsigned(pm[0].rm_so);
402 exit_regerror(error, re, source);
406 /* In Gnu m4 mode, parentheses for backmatch don't work like POSIX 1003.2
407 * says. So we twiddle with the regexp before passing it to regcomp.
410 twiddle(const char *p)
412 /* + at start of regexp is a normal character for Gnu m4 */
420 /* This could use strcspn for speed... */
430 addconstantstring("[_a-zA-Z0-9]");
433 addconstantstring("[^_a-zA-Z0-9]");
436 addconstantstring("[[:<:]]");
439 addconstantstring("[[:>:]]");
448 if (*p == '(' || *p == ')' || *p == '|')
457 /* patsubst(string, regexp, opt replacement) */
463 dopatsubst(const char *argv[], int argc)
466 m4_warnx("Too few arguments to patsubst");
469 /* special case: empty regexp */
470 if (argv[3][0] == '\0') {
473 if (argc > 4 && argv[4])
474 len = strlen(argv[4]);
477 for (s = argv[2]; *s != '\0'; s++) {
478 addchars(argv[4], len);
485 int mode = REG_EXTENDED;
487 size_t l = strlen(argv[3]);
490 (argv[3][0] == '^') ||
491 (l > 0 && argv[3][l-1] == '$'))
494 source = mimic_gnu ? twiddle(argv[3]) : argv[3];
495 error = regcomp(&re, source, mode);
497 exit_regerror(error, &re, source);
499 pmatch = xreallocarray(NULL, re.re_nsub+1, sizeof(regmatch_t),
501 do_subst(argv[2], &re, source,
502 argc > 4 && argv[4] != NULL ? argv[4] : "", pmatch);
510 doregexp(const char *argv[], int argc)
518 m4_warnx("Too few arguments to regexp");
521 /* special gnu case */
522 if (argv[3][0] == '\0' && mimic_gnu) {
523 if (argc == 4 || argv[4] == NULL)
528 source = mimic_gnu ? twiddle(argv[3]) : argv[3];
529 error = regcomp(&re, source, REG_EXTENDED|REG_NEWLINE);
531 exit_regerror(error, &re, source);
533 pmatch = xreallocarray(NULL, re.re_nsub+1, sizeof(regmatch_t), NULL);
534 if (argc == 4 || argv[4] == NULL)
535 do_regexpindex(argv[2], &re, source, pmatch);
537 do_regexp(argv[2], &re, source, argv[4], pmatch);
543 doformat(const char *argv[], int argc)
545 const char *format = argv[2];
550 const char *thisarg = NULL;
554 while (*format != 0) {
555 if (*format != '%') {
561 if (*format == '%') {
570 if (*format == '*') {
574 "Format with too many format specifiers.");
575 width = strtol(argv[pos++], NULL, 10);
577 width = strtol(format, __DECONST(char **,&format), 10);
585 if (*format == '.') {
587 if (*format == '*') {
591 "Format with too many format specifiers.");
592 extra = strtol(argv[pos++], NULL, 10);
594 extra = strtol(format, __DECONST(char **, &format), 10);
600 m4errx(1, "Format with too many format specifiers.");
603 thisarg = argv[pos++];
606 temp[0] = strtoul(argv[pos++], NULL, 10);
611 m4errx(1, "Unsupported format specification: %s.",
619 while ((long)l < width--)
622 addchars(thisarg, l);
624 while ((long)l < width--)
632 doesyscmd(const char *cmd)
640 /* Follow gnu m4 documentation: first flush buffers. */
643 argv[0] = __DECONST(char *, "sh");
644 argv[1] = __DECONST(char *, "-c");
645 argv[2] = __DECONST(char *, cmd);
648 /* Just set up standard output, share stderr and stdin with m4 */
651 switch(cpid = fork()) {
657 (void) dup2(p[1], 1);
659 execv(_PATH_BSHELL, argv);
662 /* Read result in two stages, since m4's buffer is
666 char result[BUFSIZE];
667 cc = read(p[0], result, sizeof result);
669 addchars(result, cc);
670 } while (cc > 0 || (cc == -1 && errno == EINTR));
673 while (waitpid(cpid, &status, 0) == -1) {
682 getdivfile(const char *name)
687 f = fopen(name, "r");
691 while ((c = getc(f))!= EOF)