xref: /openbsd-src/usr.bin/hexdump/parse.c (revision 8500990981f885cbe5e6a4958549cacc238b5ae6)
1 /*	$OpenBSD: parse.c,v 1.13 2003/06/12 20:58:09 deraadt Exp $	*/
2 /*	$NetBSD: parse.c,v 1.12 2001/12/07 13:37:39 bjh21 Exp $	*/
3 
4 /*
5  * Copyright (c) 1989, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #ifndef lint
34 /*static char sccsid[] = "from: @(#)parse.c	5.6 (Berkeley) 3/9/91";*/
35 static char rcsid[] = "$OpenBSD: parse.c,v 1.13 2003/06/12 20:58:09 deraadt Exp $";
36 #endif /* not lint */
37 
38 #include <sys/types.h>
39 #include <sys/file.h>
40 
41 #include <ctype.h>
42 #include <err.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 
49 #include "hexdump.h"
50 
51 FU *endfu;					/* format at end-of-data */
52 
53 void
54 addfile(char *name)
55 {
56 	char *p;
57 	FILE *fp;
58 	int ch;
59 	char buf[2048 + 1];
60 
61 	if ((fp = fopen(name, "r")) == NULL)
62 		err(1, "fopen %s", name);
63 	while (fgets(buf, sizeof(buf), fp)) {
64 		if (!(p = strchr(buf, '\n'))) {
65 			warnx("line too long.");
66 			while ((ch = getchar()) != '\n' && ch != EOF);
67 			continue;
68 		}
69 		*p = '\0';
70 		for (p = buf; *p && isspace((unsigned char)*p); ++p);
71 		if (!*p || *p == '#')
72 			continue;
73 		add(p);
74 	}
75 	(void)fclose(fp);
76 }
77 
78 void
79 add(const char *fmt)
80 {
81 	const char *p;
82 	static FS **nextfs;
83 	FS *tfs;
84 	FU *tfu, **nextfu;
85 	const char *savep;
86 
87 	/* start new linked list of format units */
88 	tfs = emalloc(sizeof(FS));
89 	if (!fshead)
90 		fshead = tfs;
91 	else
92 		*nextfs = tfs;
93 	nextfs = &tfs->nextfs;
94 	nextfu = &tfs->nextfu;
95 
96 	/* take the format string and break it up into format units */
97 	for (p = fmt;;) {
98 		/* skip leading white space */
99 		for (; isspace((unsigned char)*p); ++p);
100 		if (!*p)
101 			break;
102 
103 		/* allocate a new format unit and link it in */
104 		tfu = emalloc(sizeof(FU));
105 		*nextfu = tfu;
106 		nextfu = &tfu->nextfu;
107 		tfu->reps = 1;
108 
109 		/* if leading digit, repetition count */
110 		if (isdigit((unsigned char)*p)) {
111 			for (savep = p; isdigit((unsigned char)*p); ++p);
112 			if (!isspace((unsigned char)*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((unsigned char)*p); ++p);
119 		}
120 
121 		/* skip slash and trailing white space */
122 		if (*p == '/')
123 			while (isspace((unsigned char)*++p));
124 
125 		/* byte count */
126 		if (isdigit((unsigned char)*p)) {
127 			for (savep = p; isdigit((unsigned char)*p); ++p);
128 			if (!isspace((unsigned char)*p))
129 				badfmt(fmt);
130 			tfu->bcnt = atoi(savep);
131 			/* skip trailing white space */
132 			for (++p; isspace((unsigned char)*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 			nomem();
143 		(void) strncpy(tfu->fmt, savep, p - savep);
144 		tfu->fmt[p - savep] = '\0';
145 		escape(tfu->fmt);
146 		p++;
147 	}
148 }
149 
150 static const char *spec = ".#-+ 0123456789";
151 
152 int
153 size(FS *fs)
154 {
155 	FU *fu;
156 	int bcnt, cursize;
157 	char *fmt;
158 	int prec;
159 
160 	/* figure out the data block size needed for each format unit */
161 	for (cursize = 0, fu = fs->nextfu; fu; fu = fu->nextfu) {
162 		if (fu->bcnt) {
163 			cursize += fu->bcnt * fu->reps;
164 			continue;
165 		}
166 		for (bcnt = prec = 0, fmt = fu->fmt; *fmt; ++fmt) {
167 			if (*fmt != '%')
168 				continue;
169 			/*
170 			 * skip any special chars -- save precision in
171 			 * case it's a %s format.
172 			 */
173 			while (strchr(spec + 1, *++fmt));
174 			if (*fmt == '.' && isdigit((unsigned char)*++fmt)) {
175 				prec = atoi(fmt);
176 				while (isdigit((unsigned char)*++fmt));
177 			}
178 			switch(*fmt) {
179 			case 'c':
180 				bcnt += 1;
181 				break;
182 			case 'd': case 'i': case 'o': case 'u':
183 			case 'x': case 'X':
184 				bcnt += 4;
185 				break;
186 			case 'e': case 'E': case 'f': case 'g': case 'G':
187 				bcnt += 8;
188 				break;
189 			case 's':
190 				bcnt += prec;
191 				break;
192 			case '_':
193 				switch(*++fmt) {
194 				case 'c': case 'p': case 'u':
195 					bcnt += 1;
196 					break;
197 				}
198 			}
199 		}
200 		cursize += bcnt * fu->reps;
201 	}
202 	return (cursize);
203 }
204 
205 void
206 rewrite(FS *fs)
207 {
208 	enum { NOTOKAY, USEBCNT, USEPREC } sokay;
209 	PR *pr, **nextpr;
210 	FU *fu;
211 	char *p1, *p2;
212 	char savech, *fmtp, cs[3];
213 	int nconv, prec;
214 	size_t len;
215 
216 	nextpr = NULL;
217 	prec = 0;
218 	for (fu = fs->nextfu; fu; fu = fu->nextfu) {
219 		/*
220 		 * Break each format unit into print units; each conversion
221 		 * character gets its own.
222 		 */
223 		for (nconv = 0, fmtp = fu->fmt; *fmtp; nextpr = &pr->nextpr) {
224 			pr = emalloc(sizeof(PR));
225 			if (!fu->nextpr)
226 				fu->nextpr = pr;
227 			else
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 				for (++p1; strchr(spec, *p1); ++p1);
248 			} else {
249 				/* Skip any special chars, field width. */
250 				while (strchr(spec + 1, *++p1));
251 				if (*p1 == '.' &&
252 				    isdigit((unsigned char)*++p1)) {
253 					sokay = USEPREC;
254 					prec = atoi(p1);
255 					while (isdigit((unsigned char)*++p1))
256 						continue;
257 				} else
258 					sokay = NOTOKAY;
259 			}
260 
261 			p2 = p1 + 1;		/* Set end pointer. */
262 			cs[0] = *p1;		/* Set conversion string. */
263 			cs[1] = '\0';
264 
265 			/*
266 			 * Figure out the byte count for each conversion;
267 			 * rewrite the format as necessary, set up blank-
268 			 * padding for end of data.
269 			 */
270 			switch(cs[0]) {
271 			case 'c':
272 				pr->flags = F_CHAR;
273 				switch(fu->bcnt) {
274 				case 0: case 1:
275 					pr->bcnt = 1;
276 					break;
277 				default:
278 					p1[1] = '\0';
279 					badcnt(p1);
280 				}
281 				break;
282 			case 'd': case 'i':
283 				pr->flags = F_INT;
284 				goto isint;
285 			case 'o': case 'u': case 'x': case 'X':
286 				pr->flags = F_UINT;
287 isint:				cs[2] = '\0';
288 				cs[1] = cs[0];
289 				cs[0] = 'q';
290 				switch(fu->bcnt) {
291 				case 0: case 4:
292 					pr->bcnt = 4;
293 					break;
294 				case 1:
295 					pr->bcnt = 1;
296 					break;
297 				case 2:
298 					pr->bcnt = 2;
299 					break;
300 				case 8:
301 					pr->bcnt = 8;
302 					break;
303 				default:
304 					p1[1] = '\0';
305 					badcnt(p1);
306 				}
307 				break;
308 			case 'e': case 'E': case 'f': case 'g': case 'G':
309 				pr->flags = F_DBL;
310 				switch(fu->bcnt) {
311 				case 0: case 8:
312 					pr->bcnt = 8;
313 					break;
314 				case 4:
315 					pr->bcnt = 4;
316 					break;
317 				default:
318 					p1[1] = '\0';
319 					badcnt(p1);
320 				}
321 				break;
322 			case 's':
323 				pr->flags = F_STR;
324 				switch(sokay) {
325 				case NOTOKAY:
326 					badsfmt();
327 				case USEBCNT:
328 					pr->bcnt = fu->bcnt;
329 					break;
330 				case USEPREC:
331 					pr->bcnt = prec;
332 					break;
333 				}
334 				break;
335 			case '_':
336 				++p2;
337 				switch(p1[1]) {
338 				case 'A':
339 					endfu = fu;
340 					fu->flags |= F_IGNORE;
341 					/* FALLTHROUGH */
342 				case 'a':
343 					pr->flags = F_ADDRESS;
344 					++p2;
345 					switch(p1[2]) {
346 					case 'd': case 'o': case'x':
347 						cs[0] = 'q';
348 						cs[1] = p1[2];
349 						cs[2] = '\0';
350 						break;
351 					default:
352 						p1[3] = '\0';
353 						badconv(p1);
354 					}
355 					break;
356 				case 'c':
357 					pr->flags = F_C;
358 					/* cs[0] = 'c';	set in conv_c */
359 					goto isint2;
360 				case 'p':
361 					pr->flags = F_P;
362 					cs[0] = 'c';
363 					goto isint2;
364 				case 'u':
365 					pr->flags = F_U;
366 					/* cs[0] = 'c';	set in conv_u */
367 isint2:					switch(fu->bcnt) {
368 					case 0: case 1:
369 						pr->bcnt = 1;
370 						break;
371 					default:
372 						p1[2] = '\0';
373 						badcnt(p1);
374 					}
375 					break;
376 				default:
377 					p1[2] = '\0';
378 					badconv(p1);
379 				}
380 				break;
381 			default:
382 				p1[1] = '\0';
383 				badconv(p1);
384 			}
385 
386 			/*
387 			 * Copy to PR format string, set conversion character
388 			 * pointer, update original.
389 			 */
390 			savech = *p2;
391 			p1[0] = '\0';
392 			len = strlen(fmtp) + strlen(cs) + 1;
393 			pr->fmt = emalloc(len);
394 			snprintf(pr->fmt, len, "%s%s", fmtp, cs);
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,
402 			    "byte count with multiple conversion characters");
403 		}
404 		/*
405 		 * If format unit byte count not specified, figure it out
406 		 * so can adjust rep count later.
407 		 */
408 		if (!fu->bcnt)
409 			for (pr = fu->nextpr; pr; pr = pr->nextpr)
410 				fu->bcnt += pr->bcnt;
411 	}
412 	/*
413 	 * If the format string interprets any data at all, and it's
414 	 * not the same as the blocksize, and its last format unit
415 	 * interprets any data at all, and has no iteration count,
416 	 * repeat it as necessary.
417 	 *
418 	 * If, rep count is greater than 1, no trailing whitespace
419 	 * gets output from the last iteration of the format unit.
420 	 */
421 	for (fu = fs->nextfu; fu; fu = fu->nextfu) {
422 		if (!fu->nextfu && fs->bcnt < blocksize &&
423 		    !(fu->flags&F_SETREP) && fu->bcnt)
424 			fu->reps += (blocksize - fs->bcnt) / fu->bcnt;
425 		if (fu->reps > 1) {
426 			for (pr = fu->nextpr;; pr = pr->nextpr)
427 				if (!pr->nextpr)
428 					break;
429 			for (p1 = pr->fmt, p2 = NULL; *p1; ++p1)
430 				p2 = isspace((unsigned char)*p1) ? p1 : NULL;
431 			if (p2)
432 				pr->nospace = p2;
433 		}
434 	}
435 #ifdef DEBUG
436 	for (fu = fs->nextfu; fu; fu = fu->nextfu) {
437 		(void)printf("fmt:");
438 		for (pr = fu->nextpr; pr; pr = pr->nextpr)
439 			(void)printf(" {%s}", pr->fmt);
440 		(void)printf("\n");
441 	}
442 #endif
443 }
444 
445 void
446 escape(char *p1)
447 {
448 	char *p2;
449 
450 	/* alphabetic escape sequences have to be done in place */
451 	for (p2 = p1;; ++p1, ++p2) {
452 		if (!*p1) {
453 			*p2 = *p1;
454 			break;
455 		}
456 		if (*p1 == '\\')
457 			switch(*++p1) {
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 	}
485 }
486 
487 void
488 badcnt(char *s)
489 {
490 	errx(1, "%s: bad byte count", s);
491 }
492 
493 void
494 badsfmt(void)
495 {
496 	errx(1, "%%s: requires a precision or a byte count");
497 }
498 
499 void
500 badfmt(const char *fmt)
501 {
502 	errx(1, "\"%s\": bad format", fmt);
503 }
504 
505 void
506 badconv(char *ch)
507 {
508 	errx(1, "%%%s: bad conversion character", ch);
509 }
510