xref: /netbsd-src/usr.bin/hexdump/parse.c (revision d48f14661dda8638fee055ba15d35bdfb29b9fa8)
1 /*	$NetBSD: parse.c,v 1.19 2006/03/30 19:53:58 dsl Exp $	*/
2 
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 #if HAVE_NBTOOL_CONFIG_H
33 #include "nbtool_config.h"
34 #endif
35 
36 #include <sys/cdefs.h>
37 #if !defined(lint)
38 #if 0
39 static char sccsid[] = "@(#)parse.c	8.1 (Berkeley) 6/6/93";
40 #else
41 __RCSID("$NetBSD: parse.c,v 1.19 2006/03/30 19:53:58 dsl Exp $");
42 #endif
43 #endif /* not lint */
44 
45 #include <sys/types.h>
46 #include <sys/file.h>
47 
48 #include <ctype.h>
49 #include <err.h>
50 #include <errno.h>
51 #include <fcntl.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 
56 #include "hexdump.h"
57 
58 FU *endfu;					/* format at end-of-data */
59 
60 void
61 addfile(char *name)
62 {
63 	char *p;
64 	FILE *fp;
65 	int ch;
66 	char buf[2048 + 1];
67 
68 	if ((fp = fopen(name, "r")) == NULL)
69 		err(1, "fopen %s", name);
70 	while (fgets(buf, sizeof(buf), fp)) {
71 		if (!(p = strchr(buf, '\n'))) {
72 			warnx("line too long.");
73 			while ((ch = getchar()) != '\n' && ch != EOF);
74 			continue;
75 		}
76 		*p = '\0';
77 		for (p = buf; *p && isspace((unsigned char)*p); ++p);
78 		if (!*p || *p == '#')
79 			continue;
80 		add(p);
81 	}
82 	(void)fclose(fp);
83 }
84 
85 void
86 add(const char *fmt)
87 {
88 	const char *p;
89 	static FS **nextfs;
90 	FS *tfs;
91 	FU *tfu, **nextfu;
92 	const char *savep;
93 
94 	/* start new linked list of format units */
95 	tfs = emalloc(sizeof(FS));
96 	if (!fshead)
97 		fshead = tfs;
98 	else
99 		*nextfs = tfs;
100 	nextfs = &tfs->nextfs;
101 	nextfu = &tfs->nextfu;
102 
103 	/* take the format string and break it up into format units */
104 	for (p = fmt;;) {
105 		/* skip leading white space */
106 		for (; isspace((unsigned char)*p); ++p);
107 		if (!*p)
108 			break;
109 
110 		/* allocate a new format unit and link it in */
111 		tfu = emalloc(sizeof(FU));
112 		*nextfu = tfu;
113 		nextfu = &tfu->nextfu;
114 		tfu->reps = 1;
115 
116 		/* if leading digit, repetition count */
117 		if (isdigit((unsigned char)*p)) {
118 			for (savep = p; isdigit((unsigned char)*p); ++p);
119 			if (!isspace((unsigned char)*p) && *p != '/')
120 				badfmt(fmt);
121 			/* may overwrite either white space or slash */
122 			tfu->reps = atoi(savep);
123 			tfu->flags = F_SETREP;
124 			/* skip trailing white space */
125 			for (++p; isspace((unsigned char)*p); ++p);
126 		}
127 
128 		/* skip slash and trailing white space */
129 		if (*p == '/')
130 			while (isspace((unsigned char)*++p));
131 
132 		/* byte count */
133 		if (isdigit((unsigned char)*p)) {
134 			for (savep = p; isdigit((unsigned char)*p); ++p);
135 			if (!isspace((unsigned char)*p))
136 				badfmt(fmt);
137 			tfu->bcnt = atoi(savep);
138 			/* skip trailing white space */
139 			for (++p; isspace((unsigned char)*p); ++p);
140 		}
141 
142 		/* format */
143 		if (*p != '"')
144 			badfmt(fmt);
145 		for (savep = ++p; *p != '"';)
146 			if (*p++ == 0)
147 				badfmt(fmt);
148 		if (!(tfu->fmt = malloc(p - savep + 1)))
149 			nomem();
150 		(void) strncpy(tfu->fmt, savep, p - savep);
151 		tfu->fmt[p - savep] = '\0';
152 		escape(tfu->fmt);
153 		p++;
154 	}
155 }
156 
157 static const char *spec = ".#-+ 0123456789";
158 
159 int
160 size(FS *fs)
161 {
162 	FU *fu;
163 	int bcnt, cursize;
164 	char *fmt;
165 	int prec;
166 
167 	/* figure out the data block size needed for each format unit */
168 	for (cursize = 0, fu = fs->nextfu; fu; fu = fu->nextfu) {
169 		if (fu->bcnt) {
170 			cursize += fu->bcnt * fu->reps;
171 			continue;
172 		}
173 		for (bcnt = prec = 0, fmt = fu->fmt; *fmt; ++fmt) {
174 			if (*fmt != '%')
175 				continue;
176 			/*
177 			 * skip any special chars -- save precision in
178 			 * case it's a %s format.
179 			 */
180 			while (strchr(spec + 1, *++fmt));
181 			if (*fmt == '.' && isdigit((unsigned char)*++fmt)) {
182 				prec = atoi(fmt);
183 				while (isdigit((unsigned char)*++fmt));
184 			}
185 			switch(*fmt) {
186 			case 'c':
187 				bcnt += 1;
188 				break;
189 			case 'd': case 'i': case 'o': case 'u':
190 			case 'x': case 'X':
191 				bcnt += 4;
192 				break;
193 			case 'e': case 'E': case 'f': case 'g': case 'G':
194 				bcnt += 8;
195 				break;
196 			case 's':
197 				bcnt += prec;
198 				break;
199 			case '_':
200 				switch(*++fmt) {
201 				case 'c': case 'p': case 'u':
202 					bcnt += 1;
203 					break;
204 				}
205 			}
206 		}
207 		cursize += bcnt * fu->reps;
208 	}
209 	return (cursize);
210 }
211 
212 void
213 rewrite(FS *fs)
214 {
215 	enum { NOTOKAY, USEBCNT, USEPREC } sokay;
216 	PR *pr, **nextpr;
217 	FU *fu;
218 	char *p1, *p2;
219 	char savech, *fmtp, cs[3];
220 	int nconv, prec;
221 
222 	prec = 0;
223 	for (fu = fs->nextfu; fu; fu = fu->nextfu) {
224 		/*
225 		 * Break each format unit into print units; each conversion
226 		 * character gets its own.
227 		 */
228 		nextpr = &fu->nextpr;
229 		for (nconv = 0, fmtp = fu->fmt; *fmtp; nextpr = &pr->nextpr) {
230 			pr = emalloc(sizeof(PR));
231 			*nextpr = pr;
232 
233 			/* Skip preceding text and up to the next % sign. */
234 			for (p1 = fmtp; *p1 && *p1 != '%'; ++p1);
235 
236 			/* Only text in the string. */
237 			if (!*p1) {
238 				pr->fmt = fmtp;
239 				pr->flags = F_TEXT;
240 				break;
241 			}
242 
243 			/*
244 			 * Get precision for %s -- if have a byte count, don't
245 			 * need it.
246 			 */
247 			if (fu->bcnt) {
248 				sokay = USEBCNT;
249 				/* Skip to conversion character. */
250 				for (++p1; strchr(spec, *p1); ++p1);
251 			} else {
252 				/* Skip any special chars, field width. */
253 				while (strchr(spec + 1, *++p1));
254 				if (*p1 == '.' &&
255 				    isdigit((unsigned char)*++p1)) {
256 					sokay = USEPREC;
257 					prec = atoi(p1);
258 					while (isdigit((unsigned char)*++p1))
259 						continue;
260 				} else
261 					sokay = NOTOKAY;
262 			}
263 
264 			p2 = p1 + 1;		/* Set end pointer. */
265 			cs[0] = *p1;		/* Set conversion string. */
266 			cs[1] = '\0';
267 
268 			/*
269 			 * Figure out the byte count for each conversion;
270 			 * rewrite the format as necessary, set up blank-
271 			 * padding for end of data.
272 			 */
273 			switch(cs[0]) {
274 			case 'c':
275 				pr->flags = F_CHAR;
276 				switch(fu->bcnt) {
277 				case 0: case 1:
278 					pr->bcnt = 1;
279 					break;
280 				default:
281 					p1[1] = '\0';
282 					badcnt(p1);
283 				}
284 				break;
285 			case 'd': case 'i':
286 				pr->flags = F_INT;
287 				goto isint;
288 			case 'o': case 'u': case 'x': case 'X':
289 				pr->flags = F_UINT;
290 isint:				cs[2] = '\0';
291 				cs[1] = cs[0];
292 				cs[0] = 'q';
293 				switch(fu->bcnt) {
294 				case 0: case 4:
295 					pr->bcnt = 4;
296 					break;
297 				case 1:
298 					pr->bcnt = 1;
299 					break;
300 				case 2:
301 					pr->bcnt = 2;
302 					break;
303 				case 8:
304 					pr->bcnt = 8;
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 					p1[1] = '\0';
322 					badcnt(p1);
323 				}
324 				break;
325 			case 's':
326 				pr->flags = F_STR;
327 				switch(sokay) {
328 				case NOTOKAY:
329 					badsfmt();
330 				case USEBCNT:
331 					pr->bcnt = fu->bcnt;
332 					break;
333 				case USEPREC:
334 					pr->bcnt = prec;
335 					break;
336 				}
337 				break;
338 			case '_':
339 				++p2;
340 				switch(p1[1]) {
341 				case 'A':
342 					endfu = fu;
343 					fu->flags |= F_IGNORE;
344 					/* FALLTHROUGH */
345 				case 'a':
346 					pr->flags = F_ADDRESS;
347 					++p2;
348 					switch(p1[2]) {
349 					case 'd': case 'o': case'x':
350 						cs[0] = 'q';
351 						cs[1] = p1[2];
352 						cs[2] = '\0';
353 						break;
354 					default:
355 						p1[3] = '\0';
356 						badconv(p1);
357 					}
358 					break;
359 				case 'c':
360 					pr->flags = F_C;
361 					/* cs[0] = 'c';	set in conv_c */
362 					goto isint2;
363 				case 'p':
364 					pr->flags = F_P;
365 					cs[0] = 'c';
366 					goto isint2;
367 				case 'u':
368 					pr->flags = F_U;
369 					/* cs[0] = 'c';	set in conv_u */
370 isint2:					switch(fu->bcnt) {
371 					case 0: case 1:
372 						pr->bcnt = 1;
373 						break;
374 					default:
375 						p1[2] = '\0';
376 						badcnt(p1);
377 					}
378 					break;
379 				default:
380 					p1[2] = '\0';
381 					badconv(p1);
382 				}
383 				break;
384 			default:
385 				p1[1] = '\0';
386 				badconv(p1);
387 			}
388 
389 			/*
390 			 * Copy to PR format string, set conversion character
391 			 * pointer, update original.
392 			 */
393 			savech = *p2;
394 			p1[0] = '\0';
395 			pr->fmt = emalloc(strlen(fmtp) + strlen(cs) + 1);
396 			(void)strcpy(pr->fmt, fmtp);
397 			(void)strcat(pr->fmt, cs);
398 			*p2 = savech;
399 			pr->cchar = pr->fmt + (p1 - fmtp);
400 			fmtp = p2;
401 
402 			/* Only one conversion character if byte count. */
403 			if (!(pr->flags&F_ADDRESS) && fu->bcnt && nconv++)
404 				errx(1,
405 			    "byte count with multiple conversion characters");
406 		}
407 		/*
408 		 * If format unit byte count not specified, figure it out
409 		 * so can adjust rep count later.
410 		 */
411 		if (!fu->bcnt)
412 			for (pr = fu->nextpr; pr; pr = pr->nextpr)
413 				fu->bcnt += pr->bcnt;
414 	}
415 	/*
416 	 * If the format string interprets any data at all, and it's
417 	 * not the same as the blocksize, and its last format unit
418 	 * interprets any data at all, and has no iteration count,
419 	 * repeat it as necessary.
420 	 *
421 	 * If, rep count is greater than 1, no trailing whitespace
422 	 * gets output from the last iteration of the format unit.
423 	 */
424 	for (fu = fs->nextfu; fu; fu = fu->nextfu) {
425 		if (!fu->nextfu && fs->bcnt < blocksize &&
426 		    !(fu->flags&F_SETREP) && fu->bcnt)
427 			fu->reps += (blocksize - fs->bcnt) / fu->bcnt;
428 		if (fu->reps > 1) {
429 			for (pr = fu->nextpr;; pr = pr->nextpr)
430 				if (!pr->nextpr)
431 					break;
432 			for (p1 = pr->fmt, p2 = NULL; *p1; ++p1)
433 				p2 = isspace((unsigned char)*p1) ? p1 : NULL;
434 			if (p2)
435 				pr->nospace = p2;
436 		}
437 	}
438 #ifdef DEBUG
439 	for (fu = fs->nextfu; fu; fu = fu->nextfu) {
440 		(void)printf("fmt:");
441 		for (pr = fu->nextpr; pr; pr = pr->nextpr)
442 			(void)printf(" {%s}", pr->fmt);
443 		(void)printf("\n");
444 	}
445 #endif
446 }
447 
448 void
449 escape(char *p1)
450 {
451 	char *p2;
452 
453 	/* alphabetic escape sequences have to be done in place */
454 	for (p2 = p1;; ++p1, ++p2) {
455 		if (!*p1) {
456 			*p2 = *p1;
457 			break;
458 		}
459 		if (*p1 == '\\')
460 			switch(*++p1) {
461 			case 'a':
462 			     /* *p2 = '\a'; */
463 				*p2 = '\007';
464 				break;
465 			case 'b':
466 				*p2 = '\b';
467 				break;
468 			case 'f':
469 				*p2 = '\f';
470 				break;
471 			case 'n':
472 				*p2 = '\n';
473 				break;
474 			case 'r':
475 				*p2 = '\r';
476 				break;
477 			case 't':
478 				*p2 = '\t';
479 				break;
480 			case 'v':
481 				*p2 = '\v';
482 				break;
483 			default:
484 				*p2 = *p1;
485 				break;
486 			}
487 	}
488 }
489 
490 void
491 badcnt(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(char *ch)
510 {
511 	errx(1, "%%%s: bad conversion character", ch);
512 }
513