xref: /freebsd/usr.bin/hexdump/parse.c (revision 7ef62cebc2f965b0f640263e179276928885e33d)
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 				case 8:
307 					pr->bcnt = 8;
308 					break;
309 				default:
310 					p1[1] = '\0';
311 					badcnt(p1);
312 				}
313 				break;
314 			case 'e': case 'E': case 'f': case 'g': case 'G':
315 				pr->flags = F_DBL;
316 				switch(fu->bcnt) {
317 				case 0: case 8:
318 					pr->bcnt = 8;
319 					break;
320 				case 4:
321 					pr->bcnt = 4;
322 					break;
323 				default:
324 					if (fu->bcnt == sizeof(long double)) {
325 						cs[2] = '\0';
326 						cs[1] = cs[0];
327 						cs[0] = 'L';
328 						pr->bcnt = sizeof(long double);
329 					} else {
330 						p1[1] = '\0';
331 						badcnt(p1);
332 					}
333 				}
334 				break;
335 			case 's':
336 				pr->flags = F_STR;
337 				switch(sokay) {
338 				case NOTOKAY:
339 					badsfmt();
340 				case USEBCNT:
341 					pr->bcnt = fu->bcnt;
342 					break;
343 				case USEPREC:
344 					pr->bcnt = prec;
345 					break;
346 				}
347 				break;
348 			case '_':
349 				++p2;
350 				switch(p1[1]) {
351 				case 'A':
352 					endfu = fu;
353 					fu->flags |= F_IGNORE;
354 					/* FALLTHROUGH */
355 				case 'a':
356 					pr->flags = F_ADDRESS;
357 					++p2;
358 					switch(p1[2]) {
359 					case 'd': case 'o': case'x':
360 						cs[0] = 'q';
361 						cs[1] = p1[2];
362 						cs[2] = '\0';
363 						break;
364 					default:
365 						p1[3] = '\0';
366 						badconv(p1);
367 					}
368 					break;
369 				case 'c':
370 					pr->flags = F_C;
371 					/* cs[0] = 'c';	set in conv_c */
372 					goto isint2;
373 				case 'p':
374 					pr->flags = F_P;
375 					cs[0] = 'c';
376 					goto isint2;
377 				case 'u':
378 					pr->flags = F_U;
379 					/* cs[0] = 'c';	set in conv_u */
380 isint2:					switch(fu->bcnt) {
381 					case 0: case 1:
382 						pr->bcnt = 1;
383 						break;
384 					default:
385 						p1[2] = '\0';
386 						badcnt(p1);
387 					}
388 					break;
389 				default:
390 					p1[2] = '\0';
391 					badconv(p1);
392 				}
393 				break;
394 			default:
395 				p1[1] = '\0';
396 				badconv(p1);
397 			}
398 
399 			/*
400 			 * Copy to PR format string, set conversion character
401 			 * pointer, update original.
402 			 */
403 			savech = *p2;
404 			p1[0] = '\0';
405 			if (asprintf(&pr->fmt, "%s%s", fmtp, cs) == -1)
406 				err(1, NULL);
407 			*p2 = savech;
408 			pr->cchar = pr->fmt + (p1 - fmtp);
409 			fmtp = p2;
410 
411 			/* Only one conversion character if byte count. */
412 			if (!(pr->flags&F_ADDRESS) && fu->bcnt && nconv++)
413 	    errx(1, "byte count with multiple conversion characters");
414 		}
415 		/*
416 		 * If format unit byte count not specified, figure it out
417 		 * so can adjust rep count later.
418 		 */
419 		if (!fu->bcnt)
420 			for (pr = fu->nextpr; pr; pr = pr->nextpr)
421 				fu->bcnt += pr->bcnt;
422 	}
423 	/*
424 	 * If the format string interprets any data at all, and it's
425 	 * not the same as the blocksize, and its last format unit
426 	 * interprets any data at all, and has no iteration count,
427 	 * repeat it as necessary.
428 	 *
429 	 * If, rep count is greater than 1, no trailing whitespace
430 	 * gets output from the last iteration of the format unit.
431 	 */
432 	for (fu = fs->nextfu; fu; fu = fu->nextfu) {
433 		if (!fu->nextfu && fs->bcnt < blocksize &&
434 		    !(fu->flags&F_SETREP) && fu->bcnt)
435 			fu->reps += (blocksize - fs->bcnt) / fu->bcnt;
436 		if (fu->reps > 1) {
437 			for (pr = fu->nextpr;; pr = pr->nextpr)
438 				if (!pr->nextpr)
439 					break;
440 			for (p1 = pr->fmt, p2 = NULL; *p1; ++p1)
441 				p2 = isspace(*p1) ? p1 : NULL;
442 			if (p2)
443 				pr->nospace = p2;
444 		}
445 	}
446 #ifdef DEBUG
447 	for (fu = fs->nextfu; fu; fu = fu->nextfu) {
448 		(void)printf("fmt:");
449 		for (pr = fu->nextpr; pr; pr = pr->nextpr)
450 			(void)printf(" {%s}", pr->fmt);
451 		(void)printf("\n");
452 	}
453 #endif
454 }
455 
456 void
457 escape(char *p1)
458 {
459 	char *p2;
460 
461 	/* alphabetic escape sequences have to be done in place */
462 	for (p2 = p1;; p1++, p2++) {
463 		if (*p1 == '\\') {
464 			p1++;
465 			switch(*p1) {
466 			case '\0':
467 				*p2 = '\\';
468 				*++p2 = '\0';
469 				return;
470 			case 'a':
471 			     /* *p2 = '\a'; */
472 				*p2 = '\007';
473 				break;
474 			case 'b':
475 				*p2 = '\b';
476 				break;
477 			case 'f':
478 				*p2 = '\f';
479 				break;
480 			case 'n':
481 				*p2 = '\n';
482 				break;
483 			case 'r':
484 				*p2 = '\r';
485 				break;
486 			case 't':
487 				*p2 = '\t';
488 				break;
489 			case 'v':
490 				*p2 = '\v';
491 				break;
492 			default:
493 				*p2 = *p1;
494 				break;
495 			}
496 		} else {
497 			*p2 = *p1;
498 			if (*p1 == '\0')
499 				return;
500 		}
501 	}
502 }
503 
504 void
505 badcnt(const char *s)
506 {
507 	errx(1, "%s: bad byte count", s);
508 }
509 
510 void
511 badsfmt(void)
512 {
513 	errx(1, "%%s: requires a precision or a byte count");
514 }
515 
516 void
517 badfmt(const char *fmt)
518 {
519 	errx(1, "\"%s\": bad format", fmt);
520 }
521 
522 void
523 badconv(const char *ch)
524 {
525 	errx(1, "%%%s: bad conversion character", ch);
526 }
527 
528 void
529 badnoconv(void)
530 {
531 	errx(1, "missing conversion character");
532 }
533