xref: /freebsd/usr.bin/hexdump/parse.c (revision 56e53cb8ef000c3ef72337a4095987a932cdedef)
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 (strchr(spec + 1, *++fmt));
173 			if (*fmt == '.' && isdigit(*++fmt)) {
174 				prec = atoi(fmt);
175 				while (isdigit(*++fmt));
176 			}
177 			switch(*fmt) {
178 			case 'c':
179 				bcnt += 1;
180 				break;
181 			case 'd': case 'i': case 'o': case 'u':
182 			case 'x': case 'X':
183 				bcnt += 4;
184 				break;
185 			case 'e': case 'E': case 'f': case 'g': case 'G':
186 				bcnt += 8;
187 				break;
188 			case 's':
189 				bcnt += prec;
190 				break;
191 			case '_':
192 				switch(*++fmt) {
193 				case 'c': case 'p': case 'u':
194 					bcnt += 1;
195 					break;
196 				}
197 			}
198 		}
199 		cursize += bcnt * fu->reps;
200 	}
201 	return (cursize);
202 }
203 
204 void
205 rewrite(FS *fs)
206 {
207 	enum { NOTOKAY, USEBCNT, USEPREC } sokay;
208 	PR *pr, **nextpr;
209 	FU *fu;
210 	unsigned char *p1, *p2, *fmtp;
211 	char savech, cs[3];
212 	int nconv, prec;
213 
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 		nextpr = &fu->nextpr;
222 		for (nconv = 0, fmtp = fu->fmt; *fmtp; nextpr = &pr->nextpr) {
223 			if ((pr = calloc(1, sizeof(PR))) == NULL)
224 				err(1, NULL);
225 			*nextpr = pr;
226 
227 			/* Skip preceding text and up to the next % sign. */
228 			for (p1 = fmtp; *p1 && *p1 != '%'; ++p1);
229 
230 			/* Only text in the string. */
231 			if (!*p1) {
232 				pr->fmt = fmtp;
233 				pr->flags = F_TEXT;
234 				break;
235 			}
236 
237 			/*
238 			 * Get precision for %s -- if have a byte count, don't
239 			 * need it.
240 			 */
241 			if (fu->bcnt) {
242 				sokay = USEBCNT;
243 				/* Skip to conversion character. */
244 				for (++p1; strchr(spec, *p1); ++p1);
245 			} else {
246 				/* Skip any special chars, field width. */
247 				while (strchr(spec + 1, *++p1));
248 				if (*p1 == '.' && isdigit(*++p1)) {
249 					sokay = USEPREC;
250 					prec = atoi(p1);
251 					while (isdigit(*++p1));
252 				} else
253 					sokay = NOTOKAY;
254 			}
255 
256 			p2 = *p1 ? p1 + 1 : p1;	/* Set end pointer -- make sure
257 						 * that it's non-NUL/-NULL first
258 						 * though. */
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 			if (asprintf(&pr->fmt, "%s%s", fmtp, cs) == -1)
394 				err(1, NULL);
395 			*p2 = savech;
396 			pr->cchar = pr->fmt + (p1 - fmtp);
397 			fmtp = p2;
398 
399 			/* Only one conversion character if byte count. */
400 			if (!(pr->flags&F_ADDRESS) && fu->bcnt && nconv++)
401 	    errx(1, "byte count with multiple conversion characters");
402 		}
403 		/*
404 		 * If format unit byte count not specified, figure it out
405 		 * so can adjust rep count later.
406 		 */
407 		if (!fu->bcnt)
408 			for (pr = fu->nextpr; pr; pr = pr->nextpr)
409 				fu->bcnt += pr->bcnt;
410 	}
411 	/*
412 	 * If the format string interprets any data at all, and it's
413 	 * not the same as the blocksize, and its last format unit
414 	 * interprets any data at all, and has no iteration count,
415 	 * repeat it as necessary.
416 	 *
417 	 * If, rep count is greater than 1, no trailing whitespace
418 	 * gets output from the last iteration of the format unit.
419 	 */
420 	for (fu = fs->nextfu; fu; fu = fu->nextfu) {
421 		if (!fu->nextfu && fs->bcnt < blocksize &&
422 		    !(fu->flags&F_SETREP) && fu->bcnt)
423 			fu->reps += (blocksize - fs->bcnt) / fu->bcnt;
424 		if (fu->reps > 1) {
425 			for (pr = fu->nextpr;; pr = pr->nextpr)
426 				if (!pr->nextpr)
427 					break;
428 			for (p1 = pr->fmt, p2 = NULL; *p1; ++p1)
429 				p2 = isspace(*p1) ? p1 : NULL;
430 			if (p2)
431 				pr->nospace = p2;
432 		}
433 	}
434 #ifdef DEBUG
435 	for (fu = fs->nextfu; fu; fu = fu->nextfu) {
436 		(void)printf("fmt:");
437 		for (pr = fu->nextpr; pr; pr = pr->nextpr)
438 			(void)printf(" {%s}", pr->fmt);
439 		(void)printf("\n");
440 	}
441 #endif
442 }
443 
444 void
445 escape(char *p1)
446 {
447 	char *p2;
448 
449 	/* alphabetic escape sequences have to be done in place */
450 	for (p2 = p1;; p1++, p2++) {
451 		if (*p1 == '\\') {
452 			p1++;
453 			switch(*p1) {
454 			case '\0':
455 				*p2 = '\\';
456 				*++p2 = '\0';
457 				return;
458 			case 'a':
459 			     /* *p2 = '\a'; */
460 				*p2 = '\007';
461 				break;
462 			case 'b':
463 				*p2 = '\b';
464 				break;
465 			case 'f':
466 				*p2 = '\f';
467 				break;
468 			case 'n':
469 				*p2 = '\n';
470 				break;
471 			case 'r':
472 				*p2 = '\r';
473 				break;
474 			case 't':
475 				*p2 = '\t';
476 				break;
477 			case 'v':
478 				*p2 = '\v';
479 				break;
480 			default:
481 				*p2 = *p1;
482 				break;
483 			}
484 		} else {
485 			*p2 = *p1;
486 			if (*p1 == '\0')
487 				return;
488 		}
489 	}
490 }
491 
492 void
493 badcnt(const char *s)
494 {
495 	errx(1, "%s: bad byte count", s);
496 }
497 
498 void
499 badsfmt(void)
500 {
501 	errx(1, "%%s: requires a precision or a byte count");
502 }
503 
504 void
505 badfmt(const char *fmt)
506 {
507 	errx(1, "\"%s\": bad format", fmt);
508 }
509 
510 void
511 badconv(const char *ch)
512 {
513 	errx(1, "%%%s: bad conversion character", ch);
514 }
515