]> git.ipfire.org Git - thirdparty/util-linux.git/blob - text-utils/hexdump-parse.c
hexdump: add highlighting support
[thirdparty/util-linux.git] / text-utils / hexdump-parse.c
1 /*
2 * Copyright (c) 1989 The Regents of the University of California.
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34 /* 1999-02-22 Arkadiusz Miƛkiewicz <misiek@pld.ORG.PL>
35 * - added Native Language Support
36 */
37
38 #include <sys/types.h>
39 #include <sys/file.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <ctype.h>
43 #include <string.h>
44 #include "hexdump.h"
45 #include "nls.h"
46 #include "xalloc.h"
47 #include "strutils.h"
48 #include "colors.h"
49
50 static void escape(char *p1);
51 static struct list_head *color_fmt(char *cfmt, int bcnt);
52
53 static void __attribute__ ((__noreturn__)) badcnt(const char *s)
54 {
55 errx(EXIT_FAILURE, _("bad byte count for conversion character %s"), s);
56 }
57
58 static void __attribute__ ((__noreturn__)) badsfmt(void)
59 {
60 errx(EXIT_FAILURE, _("%%s requires a precision or a byte count"));
61 }
62
63 static void __attribute__ ((__noreturn__)) badfmt(const char *fmt)
64 {
65 errx(EXIT_FAILURE, _("bad format {%s}"), fmt);
66 }
67
68 static void __attribute__ ((__noreturn__)) badconv(const char *ch)
69 {
70 errx(EXIT_FAILURE, _("bad conversion character %%%s"), ch);
71 }
72
73 #define first_letter(s,f) strchr(f, *(s))
74
75 struct hexdump_fu *endfu; /* format at end-of-data */
76
77 void addfile(char *name, struct hexdump *hex)
78 {
79 char *fmt, *buf = NULL;
80 FILE *fp;
81 size_t n;
82
83 if ((fp = fopen(name, "r")) == NULL)
84 err(EXIT_FAILURE, _("can't read %s"), name);
85
86 while (getline(&buf, &n, fp) != -1) {
87 fmt = buf;
88
89 while (*fmt && isspace(*fmt))
90 ++fmt;
91 if (!*fmt || *fmt == '#')
92 continue;
93
94 add_fmt(fmt, hex);
95 }
96
97 free(buf);
98 fclose(fp);
99 }
100
101 void add_fmt(const char *fmt, struct hexdump *hex)
102 {
103 const char *p, *savep;
104 struct hexdump_fs *tfs;
105 struct hexdump_fu *tfu;
106
107 /* Start new linked list of format units. */
108 tfs = xcalloc(1, sizeof(struct hexdump_fs));
109 INIT_LIST_HEAD(&tfs->fslist);
110 INIT_LIST_HEAD(&tfs->fulist);
111 list_add_tail(&tfs->fslist, &hex->fshead);
112
113 /* Take the format string and break it up into format units. */
114 p = fmt;
115 while (TRUE) {
116 /* Skip leading white space. */
117 if (!*(p = skip_space(p)))
118 break;
119
120 /* Allocate a new format unit and link it in. */
121 tfu = xcalloc(1, sizeof(struct hexdump_fu));
122 tfu->reps = 1;
123
124 INIT_LIST_HEAD(&tfu->fulist);
125 INIT_LIST_HEAD(&tfu->prlist);
126 list_add_tail(&tfu->fulist, &tfs->fulist);
127
128 /* If leading digit, repetition count. */
129 if (isdigit(*p)) {
130 savep = p;
131 while (isdigit(*p) && ++p)
132 ;
133 if (!isspace(*p) && *p != '/')
134 badfmt(fmt);
135 /* may overwrite either white space or slash */
136 tfu->reps = atoi(savep);
137 tfu->flags = F_SETREP;
138 /* skip trailing white space */
139 p = skip_space(++p);
140 }
141
142 /* Skip slash and trailing white space. */
143 if (*p == '/')
144 p = skip_space(p);
145
146 /* byte count */
147 if (isdigit(*p)) {
148 savep = p;
149 while (isdigit(*p) && ++p)
150 ;
151 if (!isspace(*p))
152 badfmt(fmt);
153 tfu->bcnt = atoi(savep);
154 /* skip trailing white space */
155 p = skip_space(++p);
156 }
157
158 /* format */
159 if (*p != '"')
160 badfmt(fmt);
161 savep = ++p;
162 while (*p != '"') {
163 if (!*p++)
164 badfmt(fmt);
165 }
166 tfu->fmt = xmalloc(p - savep + 1);
167 xstrncpy(tfu->fmt, savep, p - savep + 1);
168 escape(tfu->fmt);
169 ++p;
170 }
171 }
172
173 static const char *spec = ".#-+ 0123456789";
174
175 int block_size(struct hexdump_fs *fs)
176 {
177 struct hexdump_fu *fu;
178 int bcnt, prec, cursize = 0;
179 char *fmt;
180 struct list_head *p;
181
182 /* figure out the data block size needed for each format unit */
183 list_for_each (p, &fs->fulist) {
184 fu = list_entry(p, struct hexdump_fu, fulist);
185 if (fu->bcnt) {
186 cursize += fu->bcnt * fu->reps;
187 continue;
188 }
189 bcnt = prec = 0;
190 fmt = fu->fmt;
191 while (*fmt) {
192 if (*fmt != '%') {
193 ++fmt;
194 continue;
195 }
196 /*
197 * skip any special chars -- save precision in
198 * case it's a %s format.
199 */
200 while (strchr(spec + 1, *++fmt))
201 ;
202 if (*fmt == '.' && isdigit(*++fmt)) {
203 prec = atoi(fmt);
204 while (isdigit(*++fmt))
205 ;
206 }
207 if (first_letter(fmt, "diouxX"))
208 bcnt += 4;
209 else if (first_letter(fmt, "efgEG"))
210 bcnt += 8;
211 else if (*fmt == 's')
212 bcnt += prec;
213 else if (*fmt == 'c' || (*fmt == '_' && first_letter(++fmt, "cpu")))
214 ++bcnt;
215 ++fmt;
216 }
217 cursize += bcnt * fu->reps;
218 }
219 return(cursize);
220 }
221
222 void rewrite_rules(struct hexdump_fs *fs, struct hexdump *hex)
223 {
224 enum { NOTOKAY, USEBCNT, USEPREC } sokay;
225 struct hexdump_pr *pr;
226 struct hexdump_fu *fu;
227 struct list_head *p, *q;
228 char *p1, *p2, *fmtp;
229 char savech, cs[3];
230 int nconv, prec = 0;
231
232 list_for_each (p, &fs->fulist) {
233 fu = list_entry(p, struct hexdump_fu, fulist);
234 /*
235 * Break each format unit into print units; each
236 * conversion character gets its own.
237 */
238 nconv = 0;
239 fmtp = fu->fmt;
240 while (*fmtp) {
241 pr = xcalloc(1, sizeof(struct hexdump_pr));
242 INIT_LIST_HEAD(&pr->prlist);
243 list_add_tail(&pr->prlist, &fu->prlist);
244
245 /* Skip preceding text and up to the next % sign. */
246 p1 = fmtp;
247 while (*p1 && *p1 != '%')
248 ++p1;
249
250 /* Only text in the string. */
251 if (!*p1) {
252 pr->fmt = xstrdup(fmtp);
253 pr->flags = F_TEXT;
254 break;
255 }
256
257 /*
258 * Get precision for %s -- if have a byte count, don't
259 * need it.
260 */
261 if (fu->bcnt) {
262 sokay = USEBCNT;
263 /* skip to conversion character */
264 while (++p1 && strchr(spec, *p1))
265 ;
266 } else {
267 /* skip any special chars, field width */
268 while (strchr(spec + 1, *++p1))
269 ;
270 if (*p1 == '.' && isdigit(*++p1)) {
271 sokay = USEPREC;
272 prec = atoi(p1);
273 while (isdigit(*++p1))
274 ;
275 } else
276 sokay = NOTOKAY;
277 }
278
279 p2 = p1 + 1; /* Set end pointer. */
280 cs[0] = *p1; /* Set conversion string. */
281 cs[1] = 0;
282
283 /*
284 * Figure out the byte count for each conversion;
285 * rewrite the format as necessary, set up blank-
286 * padding for end of data.
287 */
288 if (*cs == 'c') {
289 pr->flags = F_CHAR;
290 switch(fu->bcnt) {
291 case 0:
292 case 1:
293 pr->bcnt = 1;
294 break;
295 default:
296 p1[1] = '\0';
297 badcnt(p1);
298 }
299 } else if (first_letter(cs, "di")) {
300 pr->flags = F_INT;
301 goto isint;
302 } else if (first_letter(cs, "ouxX")) {
303 pr->flags = F_UINT;
304 isint: cs[2] = '\0';
305 cs[1] = cs[0];
306 cs[0] = 'q';
307 switch(fu->bcnt) {
308 case 0:
309 pr->bcnt = 4;
310 break;
311 case 1:
312 case 2:
313 case 4:
314 case 8:
315 pr->bcnt = fu->bcnt;
316 break;
317 default:
318 p1[1] = '\0';
319 badcnt(p1);
320 }
321 } else if (first_letter(cs, "efgEG")) {
322 pr->flags = F_DBL;
323 switch(fu->bcnt) {
324 case 0:
325 pr->bcnt = 8;
326 break;
327 case 4:
328 case 8:
329 pr->bcnt = fu->bcnt;
330 break;
331 default:
332 p1[1] = '\0';
333 badcnt(p1);
334 }
335 } else if(*cs == '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 } else if (*cs == '_') {
348 ++p2;
349 switch(p1[1]) {
350 case 'A':
351 endfu = fu;
352 fu->flags |= F_IGNORE;
353 /* FALLTHROUGH */
354 case 'a':
355 pr->flags = F_ADDRESS;
356 ++p2;
357 if (first_letter(p1 + 2, "dox")) {
358 cs[0] = 'q';
359 cs[1] = p1[2];
360 cs[2] = '\0';
361 } else {
362 p1[3] = '\0';
363 badconv(p1);
364 }
365 break;
366 case 'c':
367 pr->flags = F_C;
368 /* cs[0] = 'c'; set in conv_c */
369 goto isint2;
370 case 'p':
371 pr->flags = F_P;
372 cs[0] = 'c';
373 goto isint2;
374 case 'u':
375 pr->flags = F_U;
376 /* cs[0] = 'c'; set in conv_u */
377 isint2: switch(fu->bcnt) {
378 case 0:
379 case 1:
380 pr->bcnt = 1;
381 break;
382 default:
383 p1[2] = '\0';
384 badcnt(p1);
385 }
386 break;
387 default:
388 p1[2] = '\0';
389 badconv(p1);
390 }
391 } else {
392 p1[1] = '\0';
393 badconv(p1);
394 }
395
396 /* Color unit(s) specified */
397 if (*p2 == '_' && p2[1] == 'L') {
398 if (colors_wanted()) {
399 char *a;
400
401 /* "cut out" the color_unit(s) */
402 a = strchr(p2, '[');
403 p2 = strrchr(p2, ']');
404 if (a++ && p2)
405 pr->colorlist = color_fmt(xstrndup(a, p2++ - a), pr->bcnt);
406 else
407 badconv(p2);
408 }
409 /* we don't want colors, quietly skip over them */
410 else {
411 p2 = strrchr(p2, ']');
412 /* be a bit louder if we don't know how to skip over them */
413 if (!p2)
414 badconv("_L");
415 ++p2;
416 }
417 }
418 /*
419 * Copy to hexdump_pr format string, set conversion character
420 * pointer, update original.
421 */
422 savech = *p2;
423 p1[0] = '\0';
424 pr->fmt = xmalloc(strlen(fmtp) + strlen(cs) + 1);
425 strcpy(pr->fmt, fmtp);
426 strcat(pr->fmt, cs);
427 *p2 = savech;
428 pr->cchar = pr->fmt + (p1 - fmtp);
429 fmtp = p2;
430
431 /* Only one conversion character if byte count */
432 if (!(pr->flags&F_ADDRESS) && fu->bcnt && nconv++)
433 errx(EXIT_FAILURE,
434 _("byte count with multiple conversion characters"));
435 }
436 /*
437 * If format unit byte count not specified, figure it out
438 * so can adjust rep count later.
439 */
440 if (!fu->bcnt)
441 list_for_each(q, &fu->prlist)
442 fu->bcnt
443 += (list_entry(q, struct hexdump_pr, prlist))->bcnt;
444 }
445 /*
446 * If the format string interprets any data at all, and it's
447 * not the same as the blocksize, and its last format unit
448 * interprets any data at all, and has no iteration count,
449 * repeat it as necessary.
450 *
451 * If rep count is greater than 1, no trailing whitespace
452 * gets output from the last iteration of the format unit.
453 */
454 list_for_each (p, &fs->fulist) {
455 fu = list_entry(p, struct hexdump_fu, fulist);
456
457 if (list_entry_is_last(&fu->fulist, &fs->fulist) &&
458 fs->bcnt < hex->blocksize &&
459 !(fu->flags&F_SETREP) && fu->bcnt)
460 fu->reps += (hex->blocksize - fs->bcnt) / fu->bcnt;
461 if (fu->reps > 1) {
462 if (!list_empty(&fu->prlist)) {
463 pr = list_last_entry(&fu->prlist,
464 struct hexdump_pr, prlist);
465 for (p1 = pr->fmt, p2 = NULL; *p1; ++p1)
466 p2 = isspace(*p1) ? p1 : NULL;
467 if (p2)
468 pr->nospace = p2;
469 }
470 }
471 }
472 }
473
474 /* [!]color[:string|:hex_number|:oct_number][@offt|@offt_start-offt_end],... */
475 static struct list_head *color_fmt(char *cfmt, int bcnt)
476 {
477 struct hexdump_clr *hc, *hcnext;
478 struct list_head *ret_head;
479 char *clr, *fmt;
480
481 ret_head = xmalloc(sizeof(struct list_head));
482 hcnext = hc = xcalloc(1, sizeof(struct hexdump_clr));
483
484 INIT_LIST_HEAD(&hc->colorlist);
485 INIT_LIST_HEAD(ret_head);
486 list_add_tail(&hc->colorlist, ret_head);
487
488 fmt = cfmt;
489 while (cfmt && *cfmt) {
490 char *end;
491 /* invert this condition */
492 if (*cfmt == '!') {
493 hcnext->invert = 1;
494 ++cfmt;
495 }
496
497 clr = xstrndup(cfmt, strcspn(cfmt, ":@,"));
498 cfmt += strlen(clr);
499 hcnext->fmt = colorscheme_from_string(clr);
500 free(clr);
501
502 if (!hcnext->fmt)
503 return NULL;
504
505 /* only colorize this specific value */
506 if (*cfmt == ':') {
507 ++cfmt;
508 /* a hex or oct value */
509 if (*cfmt == '0') {
510 /* hex */
511 errno = 0;
512 end = NULL;
513 if (cfmt[1] == 'x' || cfmt[1] == 'X')
514 hcnext->val = strtoul(cfmt + 2, &end, 16);
515 else
516 hcnext->val = strtoul(cfmt, &end, 8);
517 if (errno || end == cfmt)
518 badfmt(fmt);
519 cfmt = end;
520 /* a string */
521 } else {
522 off_t fmt_end;
523 char endchar;
524 char *endstr;
525
526 hcnext->val = -1;
527 /* temporarily null-delimit the format, so we can reverse-search
528 * for the start of an offset specifier */
529 fmt_end = strcspn(cfmt, ",");
530 endchar = cfmt[fmt_end];
531 cfmt[fmt_end] = '\0';
532 endstr = strrchr(cfmt, '@');
533
534 if (endstr) {
535 if (endstr[1] != '\0')
536 --endstr;
537 hcnext->str = xstrndup(cfmt, endstr - cfmt + 1);
538 } else
539 hcnext->str = xstrndup(cfmt, fmt_end);
540
541 /* restore the character */
542 cfmt[fmt_end] = endchar;
543 cfmt += strlen(hcnext->str);
544 }
545
546 /* no specific value */
547 } else
548 hcnext->val = -1;
549
550 /* only colorize at this offset */
551 hcnext->range = bcnt;
552 if (cfmt && *cfmt == '@') {
553 errno = 0;
554 hcnext->offt = strtoul(++cfmt, &cfmt, 10);
555 if (errno)
556 badfmt(fmt);
557
558 /* offset range */
559 if (*cfmt == '-') {
560 ++cfmt;
561 errno = 0;
562
563 hcnext->range =
564 strtoul(cfmt, &cfmt, 10) - hcnext->offt + 1;
565 if (errno)
566 badfmt(fmt);
567 /* offset range must be between 0 and format byte count */
568 if (!(hcnext->range >= 0 && hcnext->range <= bcnt))
569 badcnt("_L");
570 }
571 /* no specific offset */
572 } else
573 hcnext->offt = (off_t)-1;
574
575 /* check if the string we're looking for is the same length as the range */
576 if (hcnext->str && (int)strlen(hcnext->str) != hcnext->range)
577 badcnt("_L");
578
579 /* link in another condition */
580 if (cfmt && *cfmt == ',') {
581 ++cfmt;
582
583 hcnext = xcalloc(1, sizeof(struct hexdump_clr));
584 INIT_LIST_HEAD(&hcnext->colorlist);
585 list_add_tail(&hcnext->colorlist, ret_head);
586 }
587 }
588 return ret_head;
589 }
590
591 static void escape(char *p1)
592 {
593 char *p2;
594
595 /* alphabetic escape sequences have to be done in place */
596 p2 = p1;
597 while (TRUE) {
598 if (!*p1) {
599 *p2 = *p1;
600 break;
601 }
602 if (*p1 == '\\')
603 switch(*++p1) {
604 case 'a':
605 /* *p2 = '\a'; */
606 *p2 = '\007';
607 break;
608 case 'b':
609 *p2 = '\b';
610 break;
611 case 'f':
612 *p2 = '\f';
613 break;
614 case 'n':
615 *p2 = '\n';
616 break;
617 case 'r':
618 *p2 = '\r';
619 break;
620 case 't':
621 *p2 = '\t';
622 break;
623 case 'v':
624 *p2 = '\v';
625 break;
626 default:
627 *p2 = *p1;
628 break;
629 }
630 ++p1; ++p2;
631 }
632 }