xref: /src/usr.bin/m4/misc.c (revision 41474e78c493184f023723d1f86539e07bb01b92)
1 /*	$OpenBSD: misc.c,v 1.47 2017/06/15 13:48:42 bcallah Exp $	*/
2 /*	$NetBSD: misc.c,v 1.6 1995/09/28 05:37:41 tls Exp $	*/
3 
4 /*-
5  * SPDX-License-Identifier: BSD-3-Clause
6  *
7  * Copyright (c) 1989, 1993
8  *	The Regents of the University of California.  All rights reserved.
9  *
10  * This code is derived from software contributed to Berkeley by
11  * Ozan Yigit at York University.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  */
37 
38 #include <sys/types.h>
39 #include <errno.h>
40 #include <unistd.h>
41 #include <stdarg.h>
42 #include <stdio.h>
43 #include <stdint.h>
44 #include <stdlib.h>
45 #include <stddef.h>
46 #include <string.h>
47 #include <err.h>
48 #include "mdef.h"
49 #include "stdd.h"
50 #include "extern.h"
51 #include "pathnames.h"
52 
53 
54 char *ep;		/* first free char in strspace */
55 static char *strspace;	/* string space for evaluation */
56 char *endest;		/* end of string space	       */
57 static size_t strsize = STRSPMAX;
58 static size_t bufsize = BUFSIZE;
59 
60 unsigned char *buf;			/* push-back buffer	       */
61 unsigned char *bufbase;			/* the base for current ilevel */
62 unsigned char *bbase[MAXINP];		/* the base for each ilevel    */
63 unsigned char *bp;			/* first available character   */
64 unsigned char *endpbb;			/* end of push-back buffer     */
65 
66 
67 /*
68  * find the index of second str in the first str.
69  */
70 ptrdiff_t
doindex(const char * s1,const char * s2)71 doindex(const char *s1, const char *s2)
72 {
73 	char *t;
74 
75 	t = strstr(s1, s2);
76 	if (t == NULL)
77 		return (-1);
78 	else
79 		return (t - s1);
80 }
81 /*
82  *  pushback - push character back onto input
83  */
84 void
pushback(int c)85 pushback(int c)
86 {
87 	if (c == EOF)
88 		return;
89 	if (bp >= endpbb)
90 		enlarge_bufspace();
91 	*bp++ = c;
92 }
93 
94 /*
95  *  pbstr - push string back onto input
96  *          pushback is replicated to improve
97  *          performance.
98  */
99 void
pbstr(const char * s)100 pbstr(const char *s)
101 {
102 	size_t n;
103 
104 	n = strlen(s);
105 	while (endpbb - bp <= (long)n)
106 		enlarge_bufspace();
107 	while (n > 0)
108 		*bp++ = s[--n];
109 }
110 
111 /*
112  *  pbnum - convert number to string, push back on input.
113  */
114 void
pbnum(int n)115 pbnum(int n)
116 {
117 	pbnumbase(n, 10, 0);
118 }
119 
120 void
pbnumbase(int n,int base,int d)121 pbnumbase(int n, int base, int d)
122 {
123 	static char digits[36] __nonstring =
124 	    "0123456789abcdefghijklmnopqrstuvwxyz";
125 	unsigned int num;
126 	int printed = 0;
127 
128 	if (base > 36)
129 		m4errx(1, "base %d > 36: not supported.", base);
130 
131 	if (base < 2)
132 		m4errx(1, "bad base %d for conversion.", base);
133 
134 	num = (n < 0) ? -n : n;
135 	do {
136 		pushback(digits[num % base]);
137 		printed++;
138 	} while ((num /= base) > 0);
139 
140 	while (printed++ < d)
141 		pushback('0');
142 
143 	if (n < 0)
144 		pushback('-');
145 }
146 
147 /*
148  *  pbunsigned - convert unsigned long to string, push back on input.
149  */
150 void
pbunsigned(unsigned long n)151 pbunsigned(unsigned long n)
152 {
153 	do {
154 		pushback(n % 10 + '0');
155 	} while ((n /= 10) > 0);
156 }
157 
158 void
initspaces(void)159 initspaces(void)
160 {
161 	int i;
162 
163 	strspace = xalloc(strsize+1, NULL);
164 	ep = strspace;
165 	endest = strspace+strsize;
166 	buf = xalloc(bufsize, NULL);
167 	bufbase = buf;
168 	bp = buf;
169 	endpbb = buf + bufsize;
170 	for (i = 0; i < MAXINP; i++)
171 		bbase[i] = buf;
172 }
173 
174 void
enlarge_strspace(void)175 enlarge_strspace(void)
176 {
177 	char *newstrspace;
178 	int i;
179 
180 	strsize *= 2;
181 	newstrspace = malloc(strsize + 1);
182 	if (!newstrspace)
183 		errx(1, "string space overflow");
184 	memcpy(newstrspace, strspace, strsize/2);
185 	for (i = 0; i <= sp; i++)
186 		if (sstack[i] == STORAGE_STRSPACE)
187 			mstack[i].sstr = (mstack[i].sstr - strspace) +
188 			    newstrspace;
189 	ep = (ep - strspace) + newstrspace;
190 	free(strspace);
191 	strspace = newstrspace;
192 	endest = strspace + strsize;
193 }
194 
195 void
enlarge_bufspace(void)196 enlarge_bufspace(void)
197 {
198 	unsigned char *newbuf;
199 	int i;
200 
201 	bufsize += bufsize/2;
202 	newbuf = xrealloc(buf, bufsize, "too many characters pushed back");
203 	for (i = 0; i < MAXINP; i++)
204 		bbase[i] = (bbase[i]-buf)+newbuf;
205 	bp = (bp-buf)+newbuf;
206 	bufbase = (bufbase-buf)+newbuf;
207 	buf = newbuf;
208 	endpbb = buf+bufsize;
209 }
210 
211 /*
212  *  chrsave - put single char on string space
213  */
214 void
chrsave(int c)215 chrsave(int c)
216 {
217 	if (ep >= endest)
218 		enlarge_strspace();
219 	*ep++ = c;
220 }
221 
222 /*
223  * read in a diversion file, and dispose it.
224  */
225 void
getdiv(int n)226 getdiv(int n)
227 {
228 	int c;
229 
230 	if (active == outfile[n])
231 		m4errx(1, "undivert: diversion still active.");
232 	rewind(outfile[n]);
233 	while ((c = getc(outfile[n])) != EOF)
234 		putc(c, active);
235 	(void) fclose(outfile[n]);
236 	outfile[n] = NULL;
237 }
238 
239 void
onintr(int signo __unused)240 onintr(int signo __unused)
241 {
242 #define intrmessage	"m4: interrupted.\n"
243 	write(STDERR_FILENO, intrmessage, sizeof(intrmessage)-1);
244 	_exit(1);
245 }
246 
247 /*
248  * killdiv - get rid of the diversion files
249  */
250 void
killdiv(void)251 killdiv(void)
252 {
253 	int n;
254 
255 	for (n = 0; n < maxout; n++)
256 		if (outfile[n] != NULL) {
257 			(void) fclose(outfile[n]);
258 		}
259 }
260 
261 extern char *__progname;
262 
263 void
m4errx(int eval,const char * fmt,...)264 m4errx(int eval, const char *fmt, ...)
265 {
266 	fprintf(stderr, "%s: ", __progname);
267 	fprintf(stderr, "%s at line %lu: ", CURRENT_NAME, CURRENT_LINE);
268 	if (fmt != NULL) {
269 		va_list ap;
270 
271 		va_start(ap, fmt);
272 		vfprintf(stderr, fmt, ap);
273 		va_end(ap);
274 	}
275 	fprintf(stderr, "\n");
276 	exit(eval);
277 }
278 
279 /*
280  * resizedivs: allocate more diversion files */
281 void
resizedivs(int n)282 resizedivs(int n)
283 {
284 	int i;
285 
286 	outfile = xreallocarray(outfile, n, sizeof(FILE *),
287 	    "too many diverts %d", n);
288 	for (i = maxout; i < n; i++)
289 		outfile[i] = NULL;
290 	maxout = n;
291 }
292 
293 void *
xalloc(size_t n,const char * fmt,...)294 xalloc(size_t n, const char *fmt, ...)
295 {
296 	void *p = malloc(n);
297 
298 	if (p == NULL) {
299 		if (fmt == NULL)
300 			err(1, "malloc");
301 		else {
302 			va_list va;
303 
304 			va_start(va, fmt);
305 			verr(1, fmt, va);
306 			va_end(va);
307 		}
308 	}
309 	return p;
310 }
311 
312 void *
xcalloc(size_t n,size_t s,const char * fmt,...)313 xcalloc(size_t n, size_t s, const char *fmt, ...)
314 {
315 	void *p = calloc(n, s);
316 
317 	if (p == NULL) {
318 		if (fmt == NULL)
319 			err(1, "calloc");
320 		else {
321 			va_list va;
322 
323 			va_start(va, fmt);
324 			verr(1, fmt, va);
325 			va_end(va);
326 		}
327 	}
328 	return p;
329 }
330 
331 void *
xrealloc(void * old,size_t n,const char * fmt,...)332 xrealloc(void *old, size_t n, const char *fmt, ...)
333 {
334 	char *p = realloc(old, n);
335 
336 	if (p == NULL) {
337 		free(old);
338 		if (fmt == NULL)
339 			err(1, "realloc");
340 		else {
341 			va_list va;
342 
343 			va_start(va, fmt);
344 			verr(1, fmt, va);
345 			va_end(va);
346 		}
347 	}
348 	return p;
349 }
350 
351 void *
xreallocarray(void * old,size_t s1,size_t s2,const char * fmt,...)352 xreallocarray(void *old, size_t s1, size_t s2, const char *fmt, ...)
353 {
354 	void *p = reallocarray(old, s1, s2);
355 
356 	if (p == NULL) {
357 		free(old);
358 		if (fmt == NULL)
359 			err(1, "reallocarray");
360 		else {
361 			va_list va;
362 
363 			va_start(va, fmt);
364 			verr(1, fmt, va);
365 			va_end(va);
366 		}
367 	}
368 	return p;
369 }
370 
371 char *
xstrdup(const char * s)372 xstrdup(const char *s)
373 {
374 	char *p = strdup(s);
375 	if (p == NULL)
376 		err(1, "strdup");
377 	return p;
378 }
379 
380 void
usage(void)381 usage(void)
382 {
383 	fprintf(stderr, "usage: m4 [-EgPs] [-Dname[=value]] [-d flags] "
384 			"[-I dirname] [-o filename]\n"
385 			"\t[-t macro] [-Uname] [file ...]\n");
386 	exit(1);
387 }
388 
389 int
obtain_char(struct input_file * f)390 obtain_char(struct input_file *f)
391 {
392 	if (f->c == EOF)
393 		return EOF;
394 
395 	f->c = fgetc(f->file);
396 	if (f->c == '\n')
397 		f->lineno++;
398 
399 	return f->c;
400 }
401 
402 void
set_input(struct input_file * f,FILE * real,const char * name)403 set_input(struct input_file *f, FILE *real, const char *name)
404 {
405 	f->file = real;
406 	f->lineno = 1;
407 	f->c = 0;
408 	f->name = xstrdup(name);
409 	emit_synchline();
410 }
411 
412 void
do_emit_synchline(void)413 do_emit_synchline(void)
414 {
415 	fprintf(active, "#line %lu \"%s\"\n",
416 	    infile[ilevel].lineno, infile[ilevel].name);
417 	infile[ilevel].synch_lineno = infile[ilevel].lineno;
418 }
419 
420 void
release_input(struct input_file * f)421 release_input(struct input_file *f)
422 {
423 	if (ferror(f->file))
424 		errx(1, "Fatal error reading from %s\n", f->name);
425 	if (f->file != stdin)
426 	    fclose(f->file);
427 	f->c = EOF;
428 	/*
429 	 * XXX can't free filename, as there might still be
430 	 * error information pointing to it.
431 	 */
432 }
433 
434 void
doprintlineno(struct input_file * f)435 doprintlineno(struct input_file *f)
436 {
437 	pbunsigned(f->lineno);
438 }
439 
440 void
doprintfilename(struct input_file * f)441 doprintfilename(struct input_file *f)
442 {
443 	pbstr(rquote);
444 	pbstr(f->name);
445 	pbstr(lquote);
446 }
447 
448 /*
449  * buffer_mark/dump_buffer: allows one to save a mark in a buffer,
450  * and later dump everything that was added since then to a file.
451  */
452 size_t
buffer_mark(void)453 buffer_mark(void)
454 {
455 	return bp - buf;
456 }
457 
458 
459 void
dump_buffer(FILE * f,size_t m)460 dump_buffer(FILE *f, size_t m)
461 {
462 	unsigned char *s;
463 
464 	for (s = bp; s-buf > (long)m;)
465 		fputc(*--s, f);
466 }
467