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>
30 __FBSDID("$FreeBSD$");
33 * functions needed to support gnu-m4 extensions, including a fake freezing
36 #include <sys/types.h>
59 * Support for include path search
60 * First search in the current directory.
61 * If not found, and the path is not absolute, include path kicks in.
62 * First, -I options, in the order found on the command line.
63 * Then M4PATH env variable
66 static struct path_entry {
68 struct path_entry *next;
71 static struct path_entry *new_path_entry(const char *);
72 static void ensure_m4path(void);
73 static struct input_file *dopath(struct input_file *, const char *);
75 static struct path_entry *
76 new_path_entry(const char *dirname)
80 n = malloc(sizeof(struct path_entry));
82 errx(1, "out of memory");
83 n->name = xstrdup(dirname);
89 addtoincludepath(const char *dirname)
93 n = new_path_entry(dirname);
106 static int envpathdone = 0;
114 envpath = getenv("M4PATH");
117 /* for portability: getenv result is read-only */
118 envpath = xstrdup(envpath);
119 for (sweep = envpath;
120 (path = strsep(&sweep, ":")) != NULL;)
121 addtoincludepath(path);
127 dopath(struct input_file *i, const char *filename)
130 struct path_entry *pe;
133 for (pe = first; pe; pe = pe->next) {
134 snprintf(path, sizeof(path), "%s/%s", pe->name, filename);
135 if ((f = fopen(path, "r")) != NULL) {
136 set_input(i, f, path);
144 fopen_trypath(struct input_file *i, const char *filename)
148 f = fopen(filename, "r");
150 set_input(i, f, filename);
153 if (filename[0] == '/')
158 return dopath(i, filename);
162 doindir(const char *argv[], int argc)
165 struct macro_definition *p = NULL;
168 if (n == NULL || (p = macro_getdef(n)) == NULL)
169 m4errx(1, "indir: undefined macro %s.", argv[2]);
172 eval(argv+1, argc-1, p->type, is_traced(n));
176 dobuiltin(const char *argv[], int argc)
181 p = macro_getbuiltin(argv[2]);
183 eval(argv+1, argc-1, macro_builtin_type(p), is_traced(p));
185 m4errx(1, "unknown builtin %s.", argv[2]);
189 /* We need some temporary buffer space, as pb pushes BACK and substitution
190 * proceeds forward... */
192 static size_t bufsize = 0;
193 static size_t current = 0;
195 static void addchars(const char *, size_t);
196 static void addchar(int);
197 static char *twiddle(const char *);
198 static char *getstring(void);
199 static void exit_regerror(int, regex_t *, const char *);
200 static void do_subst(const char *, regex_t *, const char *, const char *,
202 static void do_regexpindex(const char *, regex_t *, const char *, regmatch_t *);
203 static void do_regexp(const char *, regex_t *, const char *, const char *,
205 static void add_sub(int, const char *, regex_t *, regmatch_t *);
206 static void add_replace(const char *, regex_t *, const char *, regmatch_t *);
207 #define addconstantstring(s) addchars((s), sizeof(s)-1)
210 addchars(const char *c, size_t n)
214 while (current + n > bufsize) {
217 else if (bufsize <= SIZE_MAX/2) {
220 errx(1, "size overflow");
222 buffer = xrealloc(buffer, bufsize, NULL);
224 memcpy(buffer+current, c, n);
231 if (current +1 > bufsize) {
236 buffer = xrealloc(buffer, bufsize, NULL);
238 buffer[current++] = c;
251 exit_regerror(int er, regex_t *re, const char *source)
256 errlen = regerror(er, re, NULL, 0);
257 errbuf = xalloc(errlen,
258 "malloc in regerror: %lu", (unsigned long)errlen);
259 regerror(er, re, errbuf, errlen);
260 m4errx(1, "regular expression error in %s: %s.", source, errbuf);
263 /* warnx() plus check to see if we need to change exit code or exit .
264 * -E flag functionality.
267 m4_warnx(const char *fmt, ...)
282 add_sub(int n, const char *string, regex_t *re, regmatch_t *pm)
284 if (n > (int)re->re_nsub)
285 m4_warnx("No subexpression %d", n);
286 /* Subexpressions that did not match are
288 else if (pm[n].rm_so != -1 &&
290 addchars(string + pm[n].rm_so,
291 pm[n].rm_eo - pm[n].rm_so);
295 /* Add replacement string to the output buffer, recognizing special
296 * constructs and replacing them with substrings of the original string.
299 add_replace(const char *string, regex_t *re, const char *replace, regmatch_t *pm)
303 for (p = replace; *p != '\0'; p++) {
304 if (*p == '&' && !mimic_gnu) {
305 add_sub(0, string, re, pm);
316 add_sub(0, string, re, pm);
322 if (isdigit((unsigned char)p[1])) {
323 add_sub(*(++p) - '0', string, re, pm);
332 do_subst(const char *string, regex_t *re, const char *source,
333 const char *replace, regmatch_t *pm)
337 const char *last_match = NULL;
339 while ((error = regexec(re, string, re->re_nsub+1, pm, flags)) == 0) {
340 if (pm[0].rm_eo != 0) {
341 if (string[pm[0].rm_eo-1] == '\n')
347 /* NULL length matches are special... We use the `vi-mode'
348 * rule: don't allow a NULL-match at the last match
351 if (pm[0].rm_so == pm[0].rm_eo &&
352 string + pm[0].rm_so == last_match) {
356 if (*string++ == '\n')
362 last_match = string + pm[0].rm_so;
363 addchars(string, pm[0].rm_so);
364 add_replace(string, re, replace, pm);
365 string += pm[0].rm_eo;
367 if (error != REG_NOMATCH)
368 exit_regerror(error, re, source);
373 do_regexp(const char *string, regex_t *re, const char *source,
374 const char *replace, regmatch_t *pm)
378 switch(error = regexec(re, string, re->re_nsub+1, pm, 0)) {
380 add_replace(string, re, replace, pm);
386 exit_regerror(error, re, source);
391 do_regexpindex(const char *string, regex_t *re, const char *source,
396 switch(error = regexec(re, string, re->re_nsub+1, pm, 0)) {
398 pbunsigned(pm[0].rm_so);
404 exit_regerror(error, re, source);
408 /* In Gnu m4 mode, parentheses for backmatch don't work like POSIX 1003.2
409 * says. So we twiddle with the regexp before passing it to regcomp.
412 twiddle(const char *p)
414 /* + at start of regexp is a normal character for Gnu m4 */
422 /* This could use strcspn for speed... */
432 addconstantstring("[_a-zA-Z0-9]");
435 addconstantstring("[^_a-zA-Z0-9]");
438 addconstantstring("[[:<:]]");
441 addconstantstring("[[:>:]]");
450 if (*p == '(' || *p == ')' || *p == '|')
459 /* patsubst(string, regexp, opt replacement) */
465 dopatsubst(const char *argv[], int argc)
468 m4_warnx("Too few arguments to patsubst");
471 /* special case: empty regexp */
472 if (argv[3][0] == '\0') {
475 if (argc > 4 && argv[4])
476 len = strlen(argv[4]);
479 for (s = argv[2]; *s != '\0'; s++) {
480 addchars(argv[4], len);
487 int mode = REG_EXTENDED;
489 size_t l = strlen(argv[3]);
492 (argv[3][0] == '^') ||
493 (l > 0 && argv[3][l-1] == '$'))
496 source = mimic_gnu ? twiddle(argv[3]) : argv[3];
497 error = regcomp(&re, source, mode);
499 exit_regerror(error, &re, source);
501 pmatch = xreallocarray(NULL, re.re_nsub+1, sizeof(regmatch_t),
503 do_subst(argv[2], &re, source,
504 argc > 4 && argv[4] != NULL ? argv[4] : "", pmatch);
512 doregexp(const char *argv[], int argc)
520 m4_warnx("Too few arguments to regexp");
523 /* special gnu case */
524 if (argv[3][0] == '\0' && mimic_gnu) {
525 if (argc == 4 || argv[4] == NULL)
530 source = mimic_gnu ? twiddle(argv[3]) : argv[3];
531 error = regcomp(&re, source, REG_EXTENDED|REG_NEWLINE);
533 exit_regerror(error, &re, source);
535 pmatch = xreallocarray(NULL, re.re_nsub+1, sizeof(regmatch_t), NULL);
536 if (argc == 4 || argv[4] == NULL)
537 do_regexpindex(argv[2], &re, source, pmatch);
539 do_regexp(argv[2], &re, source, argv[4], pmatch);
545 doformat(const char *argv[], int argc)
547 const char *format = argv[2];
552 const char *thisarg = NULL;
556 while (*format != 0) {
557 if (*format != '%') {
563 if (*format == '%') {
572 if (*format == '*') {
576 "Format with too many format specifiers.");
577 width = strtol(argv[pos++], NULL, 10);
579 width = strtol(format, __DECONST(char **,&format), 10);
587 if (*format == '.') {
589 if (*format == '*') {
593 "Format with too many format specifiers.");
594 extra = strtol(argv[pos++], NULL, 10);
596 extra = strtol(format, __DECONST(char **, &format), 10);
602 m4errx(1, "Format with too many format specifiers.");
605 thisarg = argv[pos++];
608 temp[0] = strtoul(argv[pos++], NULL, 10);
613 m4errx(1, "Unsupported format specification: %s.",
621 while ((long)l < width--)
624 addchars(thisarg, l);
626 while ((long)l < width--)
634 doesyscmd(const char *cmd)
642 /* Follow gnu m4 documentation: first flush buffers. */
645 argv[0] = __DECONST(char *, "sh");
646 argv[1] = __DECONST(char *, "-c");
647 argv[2] = __DECONST(char *, cmd);
650 /* Just set up standard output, share stderr and stdin with m4 */
653 switch(cpid = fork()) {
659 (void) dup2(p[1], 1);
661 execv(_PATH_BSHELL, argv);
664 /* Read result in two stages, since m4's buffer is
668 char result[BUFSIZE];
669 cc = read(p[0], result, sizeof result);
671 addchars(result, cc);
672 } while (cc > 0 || (cc == -1 && errno == EINTR));
675 while (waitpid(cpid, &status, 0) == -1) {
684 getdivfile(const char *name)
689 f = fopen(name, "r");
693 while ((c = getc(f))!= EOF)