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