xref: /freebsd/usr.bin/hexdump/parse.c (revision a0ee8cc636cd5c2374ec44ca71226564ea0bca95)
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
32 static 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 
48 FU *endfu;					/* format at end-of-data */
49 
50 void
51 addfile(const 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 
75 void
76 add(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 
147 static const char *spec = ".#-+ 0123456789";
148 
149 int
150 size(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 
202 void
203 rewrite(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 	prec = 0;
214 
215 	for (fu = fs->nextfu; fu; fu = fu->nextfu) {
216 		/*
217 		 * Break each format unit into print units; each conversion
218 		 * character gets its own.
219 		 */
220 		nextpr = &fu->nextpr;
221 		for (nconv = 0, fmtp = fu->fmt; *fmtp; nextpr = &pr->nextpr) {
222 			if ((pr = calloc(1, sizeof(PR))) == NULL)
223 				err(1, NULL);
224 			*nextpr = pr;
225 
226 			/* Skip preceding text and up to the next % sign. */
227 			for (p1 = fmtp; *p1 && *p1 != '%'; ++p1);
228 
229 			/* Only text in the string. */
230 			if (!*p1) {
231 				pr->fmt = fmtp;
232 				pr->flags = F_TEXT;
233 				break;
234 			}
235 
236 			/*
237 			 * Get precision for %s -- if have a byte count, don't
238 			 * need it.
239 			 */
240 			if (fu->bcnt) {
241 				sokay = USEBCNT;
242 				/* Skip to conversion character. */
243 				for (++p1; strchr(spec, *p1); ++p1);
244 			} else {
245 				/* Skip any special chars, field width. */
246 				while (strchr(spec + 1, *++p1));
247 				if (*p1 == '.' && isdigit(*++p1)) {
248 					sokay = USEPREC;
249 					prec = atoi(p1);
250 					while (isdigit(*++p1));
251 				} else
252 					sokay = NOTOKAY;
253 			}
254 
255 			p2 = *p1 ? p1 + 1 : p1;	/* Set end pointer -- make sure
256 						 * that it's non-NUL/-NULL first
257 						 * though. */
258 			cs[0] = *p1;		/* Set conversion string. */
259 			cs[1] = '\0';
260 
261 			/*
262 			 * Figure out the byte count for each conversion;
263 			 * rewrite the format as necessary, set up blank-
264 			 * padding for end of data.
265 			 */
266 			switch(cs[0]) {
267 			case 'c':
268 				pr->flags = F_CHAR;
269 				switch(fu->bcnt) {
270 				case 0: case 1:
271 					pr->bcnt = 1;
272 					break;
273 				default:
274 					p1[1] = '\0';
275 					badcnt(p1);
276 				}
277 				break;
278 			case 'd': case 'i':
279 				pr->flags = F_INT;
280 				goto isint;
281 			case 'o': case 'u': case 'x': case 'X':
282 				pr->flags = F_UINT;
283 isint:				cs[2] = '\0';
284 				cs[1] = cs[0];
285 				cs[0] = 'q';
286 				switch(fu->bcnt) {
287 				case 0: case 4:
288 					pr->bcnt = 4;
289 					break;
290 				case 1:
291 					pr->bcnt = 1;
292 					break;
293 				case 2:
294 					pr->bcnt = 2;
295 					break;
296 				default:
297 					p1[1] = '\0';
298 					badcnt(p1);
299 				}
300 				break;
301 			case 'e': case 'E': case 'f': case 'g': case 'G':
302 				pr->flags = F_DBL;
303 				switch(fu->bcnt) {
304 				case 0: case 8:
305 					pr->bcnt = 8;
306 					break;
307 				case 4:
308 					pr->bcnt = 4;
309 					break;
310 				default:
311 					if (fu->bcnt == sizeof(long double)) {
312 						cs[2] = '\0';
313 						cs[1] = cs[0];
314 						cs[0] = 'L';
315 						pr->bcnt = sizeof(long double);
316 					} else {
317 						p1[1] = '\0';
318 						badcnt(p1);
319 					}
320 				}
321 				break;
322 			case 's':
323 				pr->flags = F_STR;
324 				switch(sokay) {
325 				case NOTOKAY:
326 					badsfmt();
327 				case USEBCNT:
328 					pr->bcnt = fu->bcnt;
329 					break;
330 				case USEPREC:
331 					pr->bcnt = prec;
332 					break;
333 				}
334 				break;
335 			case '_':
336 				++p2;
337 				switch(p1[1]) {
338 				case 'A':
339 					endfu = fu;
340 					fu->flags |= F_IGNORE;
341 					/* FALLTHROUGH */
342 				case 'a':
343 					pr->flags = F_ADDRESS;
344 					++p2;
345 					switch(p1[2]) {
346 					case 'd': case 'o': case'x':
347 						cs[0] = 'q';
348 						cs[1] = p1[2];
349 						cs[2] = '\0';
350 						break;
351 					default:
352 						p1[3] = '\0';
353 						badconv(p1);
354 					}
355 					break;
356 				case 'c':
357 					pr->flags = F_C;
358 					/* cs[0] = 'c';	set in conv_c */
359 					goto isint2;
360 				case 'p':
361 					pr->flags = F_P;
362 					cs[0] = 'c';
363 					goto isint2;
364 				case 'u':
365 					pr->flags = F_U;
366 					/* cs[0] = 'c';	set in conv_u */
367 isint2:					switch(fu->bcnt) {
368 					case 0: case 1:
369 						pr->bcnt = 1;
370 						break;
371 					default:
372 						p1[2] = '\0';
373 						badcnt(p1);
374 					}
375 					break;
376 				default:
377 					p1[2] = '\0';
378 					badconv(p1);
379 				}
380 				break;
381 			default:
382 				p1[1] = '\0';
383 				badconv(p1);
384 			}
385 
386 			/*
387 			 * Copy to PR format string, set conversion character
388 			 * pointer, update original.
389 			 */
390 			savech = *p2;
391 			p1[0] = '\0';
392 			len = strlen(fmtp) + strlen(cs) + 1;
393 			if ((pr->fmt = calloc(1, len)) == NULL)
394 				err(1, NULL);
395 			snprintf(pr->fmt, len, "%s%s", fmtp, cs);
396 			*p2 = savech;
397 			pr->cchar = pr->fmt + (p1 - fmtp);
398 			fmtp = p2;
399 
400 			/* Only one conversion character if byte count. */
401 			if (!(pr->flags&F_ADDRESS) && fu->bcnt && nconv++)
402 	    errx(1, "byte count with multiple conversion characters");
403 		}
404 		/*
405 		 * If format unit byte count not specified, figure it out
406 		 * so can adjust rep count later.
407 		 */
408 		if (!fu->bcnt)
409 			for (pr = fu->nextpr; pr; pr = pr->nextpr)
410 				fu->bcnt += pr->bcnt;
411 	}
412 	/*
413 	 * If the format string interprets any data at all, and it's
414 	 * not the same as the blocksize, and its last format unit
415 	 * interprets any data at all, and has no iteration count,
416 	 * repeat it as necessary.
417 	 *
418 	 * If, rep count is greater than 1, no trailing whitespace
419 	 * gets output from the last iteration of the format unit.
420 	 */
421 	for (fu = fs->nextfu; fu; fu = fu->nextfu) {
422 		if (!fu->nextfu && fs->bcnt < blocksize &&
423 		    !(fu->flags&F_SETREP) && fu->bcnt)
424 			fu->reps += (blocksize - fs->bcnt) / fu->bcnt;
425 		if (fu->reps > 1) {
426 			for (pr = fu->nextpr;; pr = pr->nextpr)
427 				if (!pr->nextpr)
428 					break;
429 			for (p1 = pr->fmt, p2 = NULL; *p1; ++p1)
430 				p2 = isspace(*p1) ? p1 : NULL;
431 			if (p2)
432 				pr->nospace = p2;
433 		}
434 	}
435 #ifdef DEBUG
436 	for (fu = fs->nextfu; fu; fu = fu->nextfu) {
437 		(void)printf("fmt:");
438 		for (pr = fu->nextpr; pr; pr = pr->nextpr)
439 			(void)printf(" {%s}", pr->fmt);
440 		(void)printf("\n");
441 	}
442 #endif
443 }
444 
445 void
446 escape(char *p1)
447 {
448 	char *p2;
449 
450 	/* alphabetic escape sequences have to be done in place */
451 	for (p2 = p1;; p1++, p2++) {
452 		if (*p1 == '\\') {
453 			p1++;
454 			switch(*p1) {
455 			case '\0':
456 				*p2 = '\\';
457 				*++p2 = '\0';
458 				return;
459 			case 'a':
460 			     /* *p2 = '\a'; */
461 				*p2 = '\007';
462 				break;
463 			case 'b':
464 				*p2 = '\b';
465 				break;
466 			case 'f':
467 				*p2 = '\f';
468 				break;
469 			case 'n':
470 				*p2 = '\n';
471 				break;
472 			case 'r':
473 				*p2 = '\r';
474 				break;
475 			case 't':
476 				*p2 = '\t';
477 				break;
478 			case 'v':
479 				*p2 = '\v';
480 				break;
481 			default:
482 				*p2 = *p1;
483 				break;
484 			}
485 		} else {
486 			*p2 = *p1;
487 			if (*p1 == '\0')
488 				return;
489 		}
490 	}
491 }
492 
493 void
494 badcnt(const char *s)
495 {
496 	errx(1, "%s: bad byte count", s);
497 }
498 
499 void
500 badsfmt(void)
501 {
502 	errx(1, "%%s: requires a precision or a byte count");
503 }
504 
505 void
506 badfmt(const char *fmt)
507 {
508 	errx(1, "\"%s\": bad format", fmt);
509 }
510 
511 void
512 badconv(const char *ch)
513 {
514 	errx(1, "%%%s: bad conversion character", ch);
515 }
516