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