xref: /freebsd/usr.bin/m4/misc.c (revision 32cd3ee5901ea33d41ff550e5f40ce743c8d4165)
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
71 indx(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
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
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
115 pbnum(int n)
116 {
117 	pbnumbase(n, 10, 0);
118 }
119 
120 void
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 	}
139 	while ((num /= base) > 0);
140 
141 	while (printed++ < d)
142 		pushback('0');
143 
144 	if (n < 0)
145 		pushback('-');
146 }
147 
148 /*
149  *  pbunsigned - convert unsigned long to string, push back on input.
150  */
151 void
152 pbunsigned(unsigned long n)
153 {
154 	do {
155 		pushback(n % 10 + '0');
156 	}
157 	while ((n /= 10) > 0);
158 }
159 
160 void
161 initspaces(void)
162 {
163 	int i;
164 
165 	strspace = xalloc(strsize+1, NULL);
166 	ep = strspace;
167 	endest = strspace+strsize;
168 	buf = xalloc(bufsize, NULL);
169 	bufbase = buf;
170 	bp = buf;
171 	endpbb = buf + bufsize;
172 	for (i = 0; i < MAXINP; i++)
173 		bbase[i] = buf;
174 }
175 
176 void
177 enlarge_strspace(void)
178 {
179 	char *newstrspace;
180 	int i;
181 
182 	strsize *= 2;
183 	newstrspace = malloc(strsize + 1);
184 	if (!newstrspace)
185 		errx(1, "string space overflow");
186 	memcpy(newstrspace, strspace, strsize/2);
187 	for (i = 0; i <= sp; i++)
188 		if (sstack[i] == STORAGE_STRSPACE)
189 			mstack[i].sstr = (mstack[i].sstr - strspace)
190 			    + newstrspace;
191 	ep = (ep-strspace) + newstrspace;
192 	free(strspace);
193 	strspace = newstrspace;
194 	endest = strspace + strsize;
195 }
196 
197 void
198 enlarge_bufspace(void)
199 {
200 	unsigned char *newbuf;
201 	int i;
202 
203 	bufsize += bufsize/2;
204 	newbuf = xrealloc(buf, bufsize, "too many characters pushed back");
205 	for (i = 0; i < MAXINP; i++)
206 		bbase[i] = (bbase[i]-buf)+newbuf;
207 	bp = (bp-buf)+newbuf;
208 	bufbase = (bufbase-buf)+newbuf;
209 	buf = newbuf;
210 	endpbb = buf+bufsize;
211 }
212 
213 /*
214  *  chrsave - put single char on string space
215  */
216 void
217 chrsave(int c)
218 {
219 	if (ep >= endest)
220 		enlarge_strspace();
221 	*ep++ = c;
222 }
223 
224 /*
225  * read in a diversion file, and dispose it.
226  */
227 void
228 getdiv(int n)
229 {
230 	int c;
231 
232 	if (active == outfile[n])
233 		m4errx(1, "undivert: diversion still active.");
234 	rewind(outfile[n]);
235 	while ((c = getc(outfile[n])) != EOF)
236 		putc(c, active);
237 	(void) fclose(outfile[n]);
238 	outfile[n] = NULL;
239 }
240 
241 void
242 onintr(int signo __unused)
243 {
244 #define intrmessage	"m4: interrupted.\n"
245 	write(STDERR_FILENO, intrmessage, sizeof(intrmessage)-1);
246 	_exit(1);
247 }
248 
249 /*
250  * killdiv - get rid of the diversion files
251  */
252 void
253 killdiv(void)
254 {
255 	int n;
256 
257 	for (n = 0; n < maxout; n++)
258 		if (outfile[n] != NULL) {
259 			(void) fclose(outfile[n]);
260 		}
261 }
262 
263 extern char *__progname;
264 
265 void
266 m4errx(int eval, const char *fmt, ...)
267 {
268 	fprintf(stderr, "%s: ", __progname);
269 	fprintf(stderr, "%s at line %lu: ", CURRENT_NAME, CURRENT_LINE);
270 	if (fmt != NULL) {
271 		va_list ap;
272 
273 		va_start(ap, fmt);
274 		vfprintf(stderr, fmt, ap);
275 		va_end(ap);
276 	}
277 	fprintf(stderr, "\n");
278 	exit(eval);
279 }
280 
281 /*
282  * resizedivs: allocate more diversion files */
283 void
284 resizedivs(int n)
285 {
286 	int i;
287 
288 	outfile = xreallocarray(outfile, n, sizeof(FILE *),
289 	    "too many diverts %d", n);
290 	for (i = maxout; i < n; i++)
291 		outfile[i] = NULL;
292 	maxout = n;
293 }
294 
295 void *
296 xalloc(size_t n, const char *fmt, ...)
297 {
298 	void *p = malloc(n);
299 
300 	if (p == NULL) {
301 		if (fmt == NULL)
302 			err(1, "malloc");
303 		else {
304 			va_list va;
305 
306 			va_start(va, fmt);
307 			verr(1, fmt, va);
308 			va_end(va);
309 		}
310 	}
311 	return p;
312 }
313 
314 void *
315 xcalloc(size_t n, size_t s, const char *fmt, ...)
316 {
317 	void *p = calloc(n, s);
318 
319 	if (p == NULL) {
320 		if (fmt == NULL)
321 			err(1, "calloc");
322 		else {
323 			va_list va;
324 
325 			va_start(va, fmt);
326 			verr(1, fmt, va);
327 			va_end(va);
328 		}
329 	}
330 	return p;
331 }
332 
333 void *
334 xrealloc(void *old, size_t n, const char *fmt, ...)
335 {
336 	char *p = realloc(old, n);
337 
338 	if (p == NULL) {
339 		free(old);
340 		if (fmt == NULL)
341 			err(1, "realloc");
342 		else {
343 			va_list va;
344 
345 			va_start(va, fmt);
346 			verr(1, fmt, va);
347 			va_end(va);
348 		}
349 	}
350 	return p;
351 }
352 
353 void *
354 xreallocarray(void *old, size_t s1, size_t s2, const char *fmt, ...)
355 {
356 	void *p = reallocarray(old, s1, s2);
357 
358 	if (p == NULL) {
359 		free(old);
360 		if (fmt == NULL)
361 			err(1, "reallocarray");
362 		else {
363 			va_list va;
364 
365 			va_start(va, fmt);
366 			verr(1, fmt, va);
367 			va_end(va);
368 		}
369 	}
370 	return p;
371 }
372 
373 char *
374 xstrdup(const char *s)
375 {
376 	char *p = strdup(s);
377 	if (p == NULL)
378 		err(1, "strdup");
379 	return p;
380 }
381 
382 void
383 usage(void)
384 {
385 	fprintf(stderr, "usage: m4 [-EgPs] [-Dname[=value]] [-d flags] "
386 			"[-I dirname] [-o filename]\n"
387 			"\t[-t macro] [-Uname] [file ...]\n");
388 	exit(1);
389 }
390 
391 int
392 obtain_char(struct input_file *f)
393 {
394 	if (f->c == EOF)
395 		return EOF;
396 
397 	f->c = fgetc(f->file);
398 	if (f->c == '\n')
399 		f->lineno++;
400 
401 	return f->c;
402 }
403 
404 void
405 set_input(struct input_file *f, FILE *real, const char *name)
406 {
407 	f->file = real;
408 	f->lineno = 1;
409 	f->c = 0;
410 	f->name = xstrdup(name);
411 	emit_synchline();
412 }
413 
414 void
415 do_emit_synchline(void)
416 {
417 	fprintf(active, "#line %lu \"%s\"\n",
418 	    infile[ilevel].lineno, infile[ilevel].name);
419 	infile[ilevel].synch_lineno = infile[ilevel].lineno;
420 }
421 
422 void
423 release_input(struct input_file *f)
424 {
425 	if (ferror(f->file))
426 		errx(1, "Fatal error reading from %s\n", f->name);
427 	if (f->file != stdin)
428 	    fclose(f->file);
429 	f->c = EOF;
430 	/*
431 	 * XXX can't free filename, as there might still be
432 	 * error information pointing to it.
433 	 */
434 }
435 
436 void
437 doprintlineno(struct input_file *f)
438 {
439 	pbunsigned(f->lineno);
440 }
441 
442 void
443 doprintfilename(struct input_file *f)
444 {
445 	pbstr(rquote);
446 	pbstr(f->name);
447 	pbstr(lquote);
448 }
449 
450 /*
451  * buffer_mark/dump_buffer: allows one to save a mark in a buffer,
452  * and later dump everything that was added since then to a file.
453  */
454 size_t
455 buffer_mark(void)
456 {
457 	return bp - buf;
458 }
459 
460 
461 void
462 dump_buffer(FILE *f, size_t m)
463 {
464 	unsigned char *s;
465 
466 	for (s = bp; s-buf > (long)m;)
467 		fputc(*--s, f);
468 }
469