xref: /freebsd/usr.bin/hexdump/parse.c (revision 884a2a699669ec61e2366e3e358342dbc94be24a)
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(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 = index(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 (index(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 	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; index(spec, *p1); ++p1);
247 			} else {
248 				/* Skip any special chars, field width. */
249 				while (index(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 + 1;		/* Set end pointer. */
259 			cs[0] = *p1;		/* Set conversion string. */
260 			cs[1] = '\0';
261 
262 			/*
263 			 * Figure out the byte count for each conversion;
264 			 * rewrite the format as necessary, set up blank-
265 			 * padding for end of data.
266 			 */
267 			switch(cs[0]) {
268 			case 'c':
269 				pr->flags = F_CHAR;
270 				switch(fu->bcnt) {
271 				case 0: case 1:
272 					pr->bcnt = 1;
273 					break;
274 				default:
275 					p1[1] = '\0';
276 					badcnt(p1);
277 				}
278 				break;
279 			case 'd': case 'i':
280 				pr->flags = F_INT;
281 				goto isint;
282 			case 'o': case 'u': case 'x': case 'X':
283 				pr->flags = F_UINT;
284 isint:				cs[2] = '\0';
285 				cs[1] = cs[0];
286 				cs[0] = 'q';
287 				switch(fu->bcnt) {
288 				case 0: case 4:
289 					pr->bcnt = 4;
290 					break;
291 				case 1:
292 					pr->bcnt = 1;
293 					break;
294 				case 2:
295 					pr->bcnt = 2;
296 					break;
297 				default:
298 					p1[1] = '\0';
299 					badcnt(p1);
300 				}
301 				break;
302 			case 'e': case 'E': case 'f': case 'g': case 'G':
303 				pr->flags = F_DBL;
304 				switch(fu->bcnt) {
305 				case 0: case 8:
306 					pr->bcnt = 8;
307 					break;
308 				case 4:
309 					pr->bcnt = 4;
310 					break;
311 				default:
312 					if (fu->bcnt == sizeof(long double)) {
313 						cs[2] = '\0';
314 						cs[1] = cs[0];
315 						cs[0] = 'L';
316 						pr->bcnt = sizeof(long double);
317 					} else {
318 						p1[1] = '\0';
319 						badcnt(p1);
320 					}
321 				}
322 				break;
323 			case 's':
324 				pr->flags = F_STR;
325 				switch(sokay) {
326 				case NOTOKAY:
327 					badsfmt();
328 				case USEBCNT:
329 					pr->bcnt = fu->bcnt;
330 					break;
331 				case USEPREC:
332 					pr->bcnt = prec;
333 					break;
334 				}
335 				break;
336 			case '_':
337 				++p2;
338 				switch(p1[1]) {
339 				case 'A':
340 					endfu = fu;
341 					fu->flags |= F_IGNORE;
342 					/* FALLTHROUGH */
343 				case 'a':
344 					pr->flags = F_ADDRESS;
345 					++p2;
346 					switch(p1[2]) {
347 					case 'd': case 'o': case'x':
348 						cs[0] = 'q';
349 						cs[1] = p1[2];
350 						cs[2] = '\0';
351 						break;
352 					default:
353 						p1[3] = '\0';
354 						badconv(p1);
355 					}
356 					break;
357 				case 'c':
358 					pr->flags = F_C;
359 					/* cs[0] = 'c';	set in conv_c */
360 					goto isint2;
361 				case 'p':
362 					pr->flags = F_P;
363 					cs[0] = 'c';
364 					goto isint2;
365 				case 'u':
366 					pr->flags = F_U;
367 					/* cs[0] = 'c';	set in conv_u */
368 isint2:					switch(fu->bcnt) {
369 					case 0: case 1:
370 						pr->bcnt = 1;
371 						break;
372 					default:
373 						p1[2] = '\0';
374 						badcnt(p1);
375 					}
376 					break;
377 				default:
378 					p1[2] = '\0';
379 					badconv(p1);
380 				}
381 				break;
382 			default:
383 				p1[1] = '\0';
384 				badconv(p1);
385 			}
386 
387 			/*
388 			 * Copy to PR format string, set conversion character
389 			 * pointer, update original.
390 			 */
391 			savech = *p2;
392 			p1[0] = '\0';
393 			len = strlen(fmtp) + strlen(cs) + 1;
394 			if ((pr->fmt = calloc(1, len)) == NULL)
395 				err(1, NULL);
396 			snprintf(pr->fmt, len, "%s%s", fmtp, cs);
397 			*p2 = savech;
398 			pr->cchar = pr->fmt + (p1 - fmtp);
399 			fmtp = p2;
400 
401 			/* Only one conversion character if byte count. */
402 			if (!(pr->flags&F_ADDRESS) && fu->bcnt && nconv++)
403 	    errx(1, "byte count with multiple conversion characters");
404 		}
405 		/*
406 		 * If format unit byte count not specified, figure it out
407 		 * so can adjust rep count later.
408 		 */
409 		if (!fu->bcnt)
410 			for (pr = fu->nextpr; pr; pr = pr->nextpr)
411 				fu->bcnt += pr->bcnt;
412 	}
413 	/*
414 	 * If the format string interprets any data at all, and it's
415 	 * not the same as the blocksize, and its last format unit
416 	 * interprets any data at all, and has no iteration count,
417 	 * repeat it as necessary.
418 	 *
419 	 * If, rep count is greater than 1, no trailing whitespace
420 	 * gets output from the last iteration of the format unit.
421 	 */
422 	for (fu = fs->nextfu; fu; fu = fu->nextfu) {
423 		if (!fu->nextfu && fs->bcnt < blocksize &&
424 		    !(fu->flags&F_SETREP) && fu->bcnt)
425 			fu->reps += (blocksize - fs->bcnt) / fu->bcnt;
426 		if (fu->reps > 1) {
427 			for (pr = fu->nextpr;; pr = pr->nextpr)
428 				if (!pr->nextpr)
429 					break;
430 			for (p1 = pr->fmt, p2 = NULL; *p1; ++p1)
431 				p2 = isspace(*p1) ? p1 : NULL;
432 			if (p2)
433 				pr->nospace = p2;
434 		}
435 	}
436 #ifdef DEBUG
437 	for (fu = fs->nextfu; fu; fu = fu->nextfu) {
438 		(void)printf("fmt:");
439 		for (pr = fu->nextpr; pr; pr = pr->nextpr)
440 			(void)printf(" {%s}", pr->fmt);
441 		(void)printf("\n");
442 	}
443 #endif
444 }
445 
446 void
447 escape(char *p1)
448 {
449 	char *p2;
450 
451 	/* alphabetic escape sequences have to be done in place */
452 	for (p2 = p1;; ++p1, ++p2) {
453 		if (!*p1) {
454 			*p2 = *p1;
455 			break;
456 		}
457 		if (*p1 == '\\')
458 			switch(*++p1) {
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 	}
486 }
487 
488 void
489 badcnt(char *s)
490 {
491 	errx(1, "%s: bad byte count", s);
492 }
493 
494 void
495 badsfmt(void)
496 {
497 	errx(1, "%%s: requires a precision or a byte count");
498 }
499 
500 void
501 badfmt(const char *fmt)
502 {
503 	errx(1, "\"%s\": bad format", fmt);
504 }
505 
506 void
507 badconv(char *ch)
508 {
509 	errx(1, "%%%s: bad conversion character", ch);
510 }
511