1/*
2 * Copyright (c) 1989, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 *    may be used to endorse or promote products derived from this software
15 *    without specific prior written permission.
16 *
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
27 * SUCH DAMAGE.
28 */
29
30#ifndef lint
31#if 0
32static char sccsid[] = "@(#)parse.c	8.1 (Berkeley) 6/6/93";
33#endif
34#endif /* not lint */
35#include <sys/cdefs.h>
36__FBSDID("$FreeBSD$");
37
38#include <sys/types.h>
39
40#include <err.h>
41#include <fcntl.h>
42#include <stdio.h>
43#include <stdlib.h>
44#include <ctype.h>
45#include <string.h>
46#include "hexdump.h"
47
48FU *endfu;					/* format at end-of-data */
49
50void
51addfile(char *name)
52{
53	unsigned char *p;
54	FILE *fp;
55	int ch;
56	char buf[2048 + 1];
57
58	if ((fp = fopen(name, "r")) == NULL)
59		err(1, "%s", name);
60	while (fgets(buf, sizeof(buf), fp)) {
61		if (!(p = strchr(buf, '\n'))) {
62			warnx("line too long");
63			while ((ch = getchar()) != '\n' && ch != EOF);
64			continue;
65		}
66		*p = '\0';
67		for (p = buf; *p && isspace(*p); ++p);
68		if (!*p || *p == '#')
69			continue;
70		add(p);
71	}
72	(void)fclose(fp);
73}
74
75void
76add(const char *fmt)
77{
78	unsigned const char *p, *savep;
79	static FS **nextfs;
80	FS *tfs;
81	FU *tfu, **nextfu;
82
83	/* start new linked list of format units */
84	if ((tfs = calloc(1, sizeof(FS))) == NULL)
85		err(1, NULL);
86	if (!fshead)
87		fshead = tfs;
88	else
89		*nextfs = tfs;
90	nextfs = &tfs->nextfs;
91	nextfu = &tfs->nextfu;
92
93	/* take the format string and break it up into format units */
94	for (p = fmt;;) {
95		/* skip leading white space */
96		for (; isspace(*p); ++p);
97		if (!*p)
98			break;
99
100		/* allocate a new format unit and link it in */
101		if ((tfu = calloc(1, sizeof(FU))) == NULL)
102			err(1, NULL);
103		*nextfu = tfu;
104		nextfu = &tfu->nextfu;
105		tfu->reps = 1;
106
107		/* if leading digit, repetition count */
108		if (isdigit(*p)) {
109			for (savep = p; isdigit(*p); ++p);
110			if (!isspace(*p) && *p != '/')
111				badfmt(fmt);
112			/* may overwrite either white space or slash */
113			tfu->reps = atoi(savep);
114			tfu->flags = F_SETREP;
115			/* skip trailing white space */
116			for (++p; isspace(*p); ++p);
117		}
118
119		/* skip slash and trailing white space */
120		if (*p == '/')
121			while (isspace(*++p));
122
123		/* byte count */
124		if (isdigit(*p)) {
125			for (savep = p; isdigit(*p); ++p);
126			if (!isspace(*p))
127				badfmt(fmt);
128			tfu->bcnt = atoi(savep);
129			/* skip trailing white space */
130			for (++p; isspace(*p); ++p);
131		}
132
133		/* format */
134		if (*p != '"')
135			badfmt(fmt);
136		for (savep = ++p; *p != '"';)
137			if (*p++ == 0)
138				badfmt(fmt);
139		if (!(tfu->fmt = malloc(p - savep + 1)))
140			err(1, NULL);
141		(void) strlcpy(tfu->fmt, savep, p - savep + 1);
142		escape(tfu->fmt);
143		p++;
144	}
145}
146
147static const char *spec = ".#-+ 0123456789";
148
149int
150size(FS *fs)
151{
152	FU *fu;
153	int bcnt, cursize;
154	unsigned char *fmt;
155	int prec;
156
157	/* figure out the data block size needed for each format unit */
158	for (cursize = 0, fu = fs->nextfu; fu; fu = fu->nextfu) {
159		if (fu->bcnt) {
160			cursize += fu->bcnt * fu->reps;
161			continue;
162		}
163		for (bcnt = prec = 0, fmt = fu->fmt; *fmt; ++fmt) {
164			if (*fmt != '%')
165				continue;
166			/*
167			 * skip any special chars -- save precision in
168			 * case it's a %s format.
169			 */
170			while (strchr(spec + 1, *++fmt));
171			if (*fmt == '.' && isdigit(*++fmt)) {
172				prec = atoi(fmt);
173				while (isdigit(*++fmt));
174			}
175			switch(*fmt) {
176			case 'c':
177				bcnt += 1;
178				break;
179			case 'd': case 'i': case 'o': case 'u':
180			case 'x': case 'X':
181				bcnt += 4;
182				break;
183			case 'e': case 'E': case 'f': case 'g': case 'G':
184				bcnt += 8;
185				break;
186			case 's':
187				bcnt += prec;
188				break;
189			case '_':
190				switch(*++fmt) {
191				case 'c': case 'p': case 'u':
192					bcnt += 1;
193					break;
194				}
195			}
196		}
197		cursize += bcnt * fu->reps;
198	}
199	return (cursize);
200}
201
202void
203rewrite(FS *fs)
204{
205	enum { NOTOKAY, USEBCNT, USEPREC } sokay;
206	PR *pr, **nextpr;
207	FU *fu;
208	unsigned char *p1, *p2, *fmtp;
209	char savech, cs[3];
210	int nconv, prec;
211	size_t len;
212
213	nextpr = NULL;
214	prec = 0;
215
216	for (fu = fs->nextfu; fu; fu = fu->nextfu) {
217		/*
218		 * Break each format unit into print units; each conversion
219		 * character gets its own.
220		 */
221		for (nconv = 0, fmtp = fu->fmt; *fmtp; nextpr = &pr->nextpr) {
222			if ((pr = calloc(1, sizeof(PR))) == NULL)
223				err(1, NULL);
224			if (!fu->nextpr)
225				fu->nextpr = pr;
226			else
227				*nextpr = pr;
228
229			/* Skip preceding text and up to the next % sign. */
230			for (p1 = fmtp; *p1 && *p1 != '%'; ++p1);
231
232			/* Only text in the string. */
233			if (!*p1) {
234				pr->fmt = fmtp;
235				pr->flags = F_TEXT;
236				break;
237			}
238
239			/*
240			 * Get precision for %s -- if have a byte count, don't
241			 * need it.
242			 */
243			if (fu->bcnt) {
244				sokay = USEBCNT;
245				/* Skip to conversion character. */
246				for (++p1; strchr(spec, *p1); ++p1);
247			} else {
248				/* Skip any special chars, field width. */
249				while (strchr(spec + 1, *++p1));
250				if (*p1 == '.' && isdigit(*++p1)) {
251					sokay = USEPREC;
252					prec = atoi(p1);
253					while (isdigit(*++p1));
254				} else
255					sokay = NOTOKAY;
256			}
257
258			p2 = *p1 ? p1 + 1 : p1;	/* Set end pointer -- make sure
259						 * that it's non-NUL/-NULL first
260						 * though. */
261			cs[0] = *p1;		/* Set conversion string. */
262			cs[1] = '\0';
263
264			/*
265			 * Figure out the byte count for each conversion;
266			 * rewrite the format as necessary, set up blank-
267			 * padding for end of data.
268			 */
269			switch(cs[0]) {
270			case 'c':
271				pr->flags = F_CHAR;
272				switch(fu->bcnt) {
273				case 0: case 1:
274					pr->bcnt = 1;
275					break;
276				default:
277					p1[1] = '\0';
278					badcnt(p1);
279				}
280				break;
281			case 'd': case 'i':
282				pr->flags = F_INT;
283				goto isint;
284			case 'o': case 'u': case 'x': case 'X':
285				pr->flags = F_UINT;
286isint:				cs[2] = '\0';
287				cs[1] = cs[0];
288				cs[0] = 'q';
289				switch(fu->bcnt) {
290				case 0: case 4:
291					pr->bcnt = 4;
292					break;
293				case 1:
294					pr->bcnt = 1;
295					break;
296				case 2:
297					pr->bcnt = 2;
298					break;
299				default:
300					p1[1] = '\0';
301					badcnt(p1);
302				}
303				break;
304			case 'e': case 'E': case 'f': case 'g': case 'G':
305				pr->flags = F_DBL;
306				switch(fu->bcnt) {
307				case 0: case 8:
308					pr->bcnt = 8;
309					break;
310				case 4:
311					pr->bcnt = 4;
312					break;
313				default:
314					if (fu->bcnt == sizeof(long double)) {
315						cs[2] = '\0';
316						cs[1] = cs[0];
317						cs[0] = 'L';
318						pr->bcnt = sizeof(long double);
319					} else {
320						p1[1] = '\0';
321						badcnt(p1);
322					}
323				}
324				break;
325			case 's':
326				pr->flags = F_STR;
327				switch(sokay) {
328				case NOTOKAY:
329					badsfmt();
330				case USEBCNT:
331					pr->bcnt = fu->bcnt;
332					break;
333				case USEPREC:
334					pr->bcnt = prec;
335					break;
336				}
337				break;
338			case '_':
339				++p2;
340				switch(p1[1]) {
341				case 'A':
342					endfu = fu;
343					fu->flags |= F_IGNORE;
344					/* FALLTHROUGH */
345				case 'a':
346					pr->flags = F_ADDRESS;
347					++p2;
348					switch(p1[2]) {
349					case 'd': case 'o': case'x':
350						cs[0] = 'q';
351						cs[1] = p1[2];
352						cs[2] = '\0';
353						break;
354					default:
355						p1[3] = '\0';
356						badconv(p1);
357					}
358					break;
359				case 'c':
360					pr->flags = F_C;
361					/* cs[0] = 'c';	set in conv_c */
362					goto isint2;
363				case 'p':
364					pr->flags = F_P;
365					cs[0] = 'c';
366					goto isint2;
367				case 'u':
368					pr->flags = F_U;
369					/* cs[0] = 'c';	set in conv_u */
370isint2:					switch(fu->bcnt) {
371					case 0: case 1:
372						pr->bcnt = 1;
373						break;
374					default:
375						p1[2] = '\0';
376						badcnt(p1);
377					}
378					break;
379				default:
380					p1[2] = '\0';
381					badconv(p1);
382				}
383				break;
384			default:
385				p1[1] = '\0';
386				badconv(p1);
387			}
388
389			/*
390			 * Copy to PR format string, set conversion character
391			 * pointer, update original.
392			 */
393			savech = *p2;
394			p1[0] = '\0';
395			len = strlen(fmtp) + strlen(cs) + 1;
396			if ((pr->fmt = calloc(1, len)) == NULL)
397				err(1, NULL);
398			snprintf(pr->fmt, len, "%s%s", fmtp, cs);
399			*p2 = savech;
400			pr->cchar = pr->fmt + (p1 - fmtp);
401			fmtp = p2;
402
403			/* Only one conversion character if byte count. */
404			if (!(pr->flags&F_ADDRESS) && fu->bcnt && nconv++)
405	    errx(1, "byte count with multiple conversion characters");
406		}
407		/*
408		 * If format unit byte count not specified, figure it out
409		 * so can adjust rep count later.
410		 */
411		if (!fu->bcnt)
412			for (pr = fu->nextpr; pr; pr = pr->nextpr)
413				fu->bcnt += pr->bcnt;
414	}
415	/*
416	 * If the format string interprets any data at all, and it's
417	 * not the same as the blocksize, and its last format unit
418	 * interprets any data at all, and has no iteration count,
419	 * repeat it as necessary.
420	 *
421	 * If, rep count is greater than 1, no trailing whitespace
422	 * gets output from the last iteration of the format unit.
423	 */
424	for (fu = fs->nextfu; fu; fu = fu->nextfu) {
425		if (!fu->nextfu && fs->bcnt < blocksize &&
426		    !(fu->flags&F_SETREP) && fu->bcnt)
427			fu->reps += (blocksize - fs->bcnt) / fu->bcnt;
428		if (fu->reps > 1) {
429			for (pr = fu->nextpr;; pr = pr->nextpr)
430				if (!pr->nextpr)
431					break;
432			for (p1 = pr->fmt, p2 = NULL; *p1; ++p1)
433				p2 = isspace(*p1) ? p1 : NULL;
434			if (p2)
435				pr->nospace = p2;
436		}
437	}
438#ifdef DEBUG
439	for (fu = fs->nextfu; fu; fu = fu->nextfu) {
440		(void)printf("fmt:");
441		for (pr = fu->nextpr; pr; pr = pr->nextpr)
442			(void)printf(" {%s}", pr->fmt);
443		(void)printf("\n");
444	}
445#endif
446}
447
448void
449escape(char *p1)
450{
451	char *p2;
452
453	/* alphabetic escape sequences have to be done in place */
454	for (p2 = p1;; p1++, p2++) {
455		if (*p1 == '\\') {
456			p1++;
457			switch(*p1) {
458			case '\0':
459				*p2 = '\\';
460				*++p2 = '\0';
461				return;
462			case 'a':
463			     /* *p2 = '\a'; */
464				*p2 = '\007';
465				break;
466			case 'b':
467				*p2 = '\b';
468				break;
469			case 'f':
470				*p2 = '\f';
471				break;
472			case 'n':
473				*p2 = '\n';
474				break;
475			case 'r':
476				*p2 = '\r';
477				break;
478			case 't':
479				*p2 = '\t';
480				break;
481			case 'v':
482				*p2 = '\v';
483				break;
484			default:
485				*p2 = *p1;
486				break;
487			}
488		} else {
489			*p2 = *p1;
490			if (*p1 == '\0')
491				return;
492		}
493	}
494}
495
496void
497badcnt(char *s)
498{
499	errx(1, "%s: bad byte count", s);
500}
501
502void
503badsfmt(void)
504{
505	errx(1, "%%s: requires a precision or a byte count");
506}
507
508void
509badfmt(const char *fmt)
510{
511	errx(1, "\"%s\": bad format", fmt);
512}
513
514void
515badconv(char *ch)
516{
517	errx(1, "%%%s: bad conversion character", ch);
518}
519