xref: /openbsd/usr.bin/hexdump/parse.c (revision 898184e3)
1 /*	$OpenBSD: parse.c,v 1.17 2009/10/27 23:59:39 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 #include <sys/types.h>
34 #include <sys/file.h>
35 
36 #include <ctype.h>
37 #include <err.h>
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 
44 #include "hexdump.h"
45 
46 FU *endfu;					/* format at end-of-data */
47 
48 void
49 addfile(char *name)
50 {
51 	FILE *fp;
52 	size_t len;
53 	char *buf, *lbuf, *p;
54 
55 	if ((fp = fopen(name, "r")) == NULL)
56 		err(1, "fopen %s", name);
57 
58 	lbuf = NULL;
59 	while ((buf = fgetln(fp, &len))) {
60 		if (buf[len - 1] == '\n')
61 			buf[len - 1] = '\0';
62 		else {
63 			/* EOF without EOL, copy and add the NUL */
64 			if ((lbuf = malloc(len + 1)) == NULL)
65 				err(1, NULL);
66 			memcpy(lbuf, buf, len);
67 			lbuf[len] = '\0';
68 			buf = lbuf;
69 		}
70 		for (p = buf; isspace((unsigned char)*p); ++p);
71 		if (!*p || *p == '#')
72 			continue;
73 		add(p);
74 	}
75 	free(lbuf);
76 	(void)fclose(fp);
77 }
78 
79 void
80 add(const char *fmt)
81 {
82 	const char *p;
83 	static FS **nextfs;
84 	FS *tfs;
85 	FU *tfu, **nextfu;
86 	const char *savep;
87 
88 	/* start new linked list of format units */
89 	tfs = emalloc(sizeof(FS));
90 	if (!fshead)
91 		fshead = tfs;
92 	else
93 		*nextfs = tfs;
94 	nextfs = &tfs->nextfs;
95 	nextfu = &tfs->nextfu;
96 
97 	/* take the format string and break it up into format units */
98 	for (p = fmt;;) {
99 		/* skip leading white space */
100 		for (; isspace((unsigned char)*p); ++p);
101 		if (!*p)
102 			break;
103 
104 		/* allocate a new format unit and link it in */
105 		tfu = emalloc(sizeof(FU));
106 		*nextfu = tfu;
107 		nextfu = &tfu->nextfu;
108 		tfu->reps = 1;
109 
110 		/* if leading digit, repetition count */
111 		if (isdigit((unsigned char)*p)) {
112 			for (savep = p; isdigit((unsigned char)*p); ++p);
113 			if (!isspace((unsigned char)*p) && *p != '/')
114 				badfmt(fmt);
115 			/* may overwrite either white space or slash */
116 			tfu->reps = atoi(savep);
117 			tfu->flags = F_SETREP;
118 			/* skip trailing white space */
119 			for (++p; isspace((unsigned char)*p); ++p);
120 		}
121 
122 		/* skip slash and trailing white space */
123 		if (*p == '/')
124 			while (isspace((unsigned char)*++p));
125 
126 		/* byte count */
127 		if (isdigit((unsigned char)*p)) {
128 			for (savep = p; isdigit((unsigned char)*p); ++p);
129 			if (!isspace((unsigned char)*p))
130 				badfmt(fmt);
131 			tfu->bcnt = atoi(savep);
132 			/* skip trailing white space */
133 			for (++p; isspace((unsigned char)*p); ++p);
134 		}
135 
136 		/* format */
137 		if (*p != '"')
138 			badfmt(fmt);
139 		for (savep = ++p; *p != '"';)
140 			if (*p++ == 0)
141 				badfmt(fmt);
142 		if (!(tfu->fmt = malloc(p - savep + 1)))
143 			nomem();
144 		(void) strncpy(tfu->fmt, savep, p - savep);
145 		tfu->fmt[p - savep] = '\0';
146 		escape(tfu->fmt);
147 		p++;
148 	}
149 }
150 
151 static const char *spec = ".#-+ 0123456789";
152 
153 int
154 size(FS *fs)
155 {
156 	FU *fu;
157 	int bcnt, cursize;
158 	char *fmt;
159 	int prec;
160 
161 	/* figure out the data block size needed for each format unit */
162 	for (cursize = 0, fu = fs->nextfu; fu; fu = fu->nextfu) {
163 		if (fu->bcnt) {
164 			cursize += fu->bcnt * fu->reps;
165 			continue;
166 		}
167 		for (bcnt = prec = 0, fmt = fu->fmt; *fmt; ++fmt) {
168 			if (*fmt != '%')
169 				continue;
170 			/*
171 			 * skip any special chars -- save precision in
172 			 * case it's a %s format.
173 			 */
174 			while (*++fmt && strchr(spec + 1, *fmt));
175 			if (*fmt == '.' && isdigit((unsigned char)*++fmt)) {
176 				prec = atoi(fmt);
177 				while (isdigit((unsigned char)*++fmt));
178 			}
179 			switch(*fmt) {
180 			case 'c':
181 				bcnt += 1;
182 				break;
183 			case 'd': case 'i': case 'o': case 'u':
184 			case 'x': case 'X':
185 				bcnt += 4;
186 				break;
187 			case 'e': case 'E': case 'f': case 'g': case 'G':
188 				bcnt += 8;
189 				break;
190 			case 's':
191 				bcnt += prec;
192 				break;
193 			case '_':
194 				switch(*++fmt) {
195 				case 'c': case 'p': case 'u':
196 					bcnt += 1;
197 					break;
198 				}
199 			}
200 		}
201 		cursize += bcnt * fu->reps;
202 	}
203 	return (cursize);
204 }
205 
206 void
207 rewrite(FS *fs)
208 {
209 	enum { NOTOKAY, USEBCNT, USEPREC } sokay;
210 	PR *pr, **nextpr;
211 	FU *fu;
212 	char *p1, *p2;
213 	char savech, *fmtp, cs[3];
214 	int nconv, prec;
215 	size_t len;
216 
217 	nextpr = NULL;
218 	prec = 0;
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 		for (nconv = 0, fmtp = fu->fmt; *fmtp; nextpr = &pr->nextpr) {
225 			pr = emalloc(sizeof(PR));
226 			if (!fu->nextpr)
227 				fu->nextpr = pr;
228 			else
229 				*nextpr = pr;
230 
231 			/* Skip preceding text and up to the next % sign. */
232 			for (p1 = fmtp; *p1 && *p1 != '%'; ++p1);
233 
234 			/* Only text in the string. */
235 			if (!*p1) {
236 				pr->fmt = fmtp;
237 				pr->flags = F_TEXT;
238 				break;
239 			}
240 
241 			/*
242 			 * Get precision for %s -- if have a byte count, don't
243 			 * need it.
244 			 */
245 			if (fu->bcnt) {
246 				sokay = USEBCNT;
247 				/* Skip to conversion character. */
248 				for (++p1; *p1 && strchr(spec, *p1); ++p1);
249 			} else {
250 				/* Skip any special chars, field width. */
251 				while (*++p1 && strchr(spec + 1, *p1));
252 				if (*p1 == '.' &&
253 				    isdigit((unsigned char)*++p1)) {
254 					sokay = USEPREC;
255 					prec = atoi(p1);
256 					while (isdigit((unsigned char)*++p1))
257 						continue;
258 				} else
259 					sokay = NOTOKAY;
260 			}
261 
262 			p2 = *p1 ? p1 + 1 : p1;	/* Set end pointer. */
263 			cs[0] = *p1;		/* Set conversion string. */
264 			cs[1] = '\0';
265 
266 			/*
267 			 * Figure out the byte count for each conversion;
268 			 * rewrite the format as necessary, set up blank-
269 			 * padding for end of data.
270 			 */
271 			switch(cs[0]) {
272 			case 'c':
273 				pr->flags = F_CHAR;
274 				switch(fu->bcnt) {
275 				case 0: case 1:
276 					pr->bcnt = 1;
277 					break;
278 				default:
279 					p1[1] = '\0';
280 					badcnt(p1);
281 				}
282 				break;
283 			case 'd': case 'i':
284 			case 'o': case 'u': case 'x': case 'X':
285 				if (cs[0] == 'd' || cs[0] == 'i')
286 					pr->flags = F_INT;
287 				else
288 					pr->flags = F_UINT;
289 
290 				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 						if (p1[2])
356 							p1[3] = '\0';
357 						badconv(p1);
358 					}
359 					break;
360 				case 'c':
361 				case 'p':
362 				case 'u':
363 					if (p1[1] == 'c') {
364 						pr->flags = F_C;
365 						/* cs[0] = 'c';	set in conv_c */
366 					} else if (p1[1] == 'p') {
367 						pr->flags = F_P;
368 						cs[0] = 'c';
369 					} else {
370 						pr->flags = F_U;
371 						/* cs[0] = 'c';	set in conv_u */
372 					}
373 
374 					switch(fu->bcnt) {
375 					case 0: case 1:
376 						pr->bcnt = 1;
377 						break;
378 					default:
379 						p1[2] = '\0';
380 						badcnt(p1);
381 					}
382 					break;
383 				default:
384 					if (p1[1])
385 						p1[2] = '\0';
386 					badconv(p1);
387 				}
388 				break;
389 			default:
390 				if (cs[0])
391 					p1[1] = '\0';
392 				badconv(p1);
393 			}
394 
395 			/*
396 			 * Copy to PR format string, set conversion character
397 			 * pointer, update original.
398 			 */
399 			savech = *p2;
400 			p1[0] = '\0';
401 			len = strlen(fmtp) + strlen(cs) + 1;
402 			pr->fmt = emalloc(len);
403 			snprintf(pr->fmt, len, "%s%s", fmtp, cs);
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,
411 			    "byte count with multiple conversion characters");
412 		}
413 		/*
414 		 * If format unit byte count not specified, figure it out
415 		 * so can adjust rep count later.
416 		 */
417 		if (!fu->bcnt)
418 			for (pr = fu->nextpr; pr; pr = pr->nextpr)
419 				fu->bcnt += pr->bcnt;
420 	}
421 	/*
422 	 * If the format string interprets any data at all, and it's
423 	 * not the same as the blocksize, and its last format unit
424 	 * interprets any data at all, and has no iteration count,
425 	 * repeat it as necessary.
426 	 *
427 	 * If, rep count is greater than 1, no trailing whitespace
428 	 * gets output from the last iteration of the format unit.
429 	 */
430 	for (fu = fs->nextfu; fu; fu = fu->nextfu) {
431 		if (!fu->nextfu && fs->bcnt < blocksize &&
432 		    !(fu->flags&F_SETREP) && fu->bcnt)
433 			fu->reps += (blocksize - fs->bcnt) / fu->bcnt;
434 		if (fu->reps > 1) {
435 			if (!fu->nextpr)
436 				break;
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((unsigned char)*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 			*p2 = *p1;
465 			break;
466 		}
467 		if (*p1 == '\\') {
468 			switch(*++p1) {
469 			case '\0':
470 				*p2++ = '\\';
471 				*p2 = '\0';
472 				return;	/* incomplete escape sequence */
473 			case 'a':
474 			     /* *p2 = '\a'; */
475 				*p2 = '\007';
476 				break;
477 			case 'b':
478 				*p2 = '\b';
479 				break;
480 			case 'f':
481 				*p2 = '\f';
482 				break;
483 			case 'n':
484 				*p2 = '\n';
485 				break;
486 			case 'r':
487 				*p2 = '\r';
488 				break;
489 			case 't':
490 				*p2 = '\t';
491 				break;
492 			case 'v':
493 				*p2 = '\v';
494 				break;
495 			default:
496 				*p2 = *p1;
497 				break;
498 			}
499 		} else
500 			*p2 = *p1;
501 	}
502 }
503 
504 void
505 badcnt(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(char *ch)
524 {
525 	errx(1, "%%%s: bad conversion character", ch);
526 }
527