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