Debian Codegraph @

src/bin/dwarfdump/dd_regex.c

raw
1 /*
2 regex - Regular expression pattern matching and replacement
3
4 By: Ozan S. Yigit (oz)
5 Dept. of Computer Science
6 York University
7
8 These routines are the PUBLIC DOMAIN equivalents of regex
9 routines as found in 4.nBSD UN*X, with minor extensions.
10
11 These routines are derived from various implementations found
12 in software tools books, and Conroy's grep. They are NOT derived
13 from licensed/restricted software.
14 For more interesting/academic/complicated implementations,
15 see Henry Spencer's regexp routines, or GNU Emacs pattern
16 matching module.
17
18 Modification history:
19
20 $Log: regex.c,v $
21 Revision 1.4 1991/10/17 03:56:42 oz
22 miscellaneous changes, small cleanups etc.
23
24 Revision 1.3 1989/04/01 14:18:09 oz
25 Change all references to a dfa: this is actually an nfa.
26
27 Revision 1.2 88/08/28 15:36:04 oz
28 Use a complement bitmap to represent NCL.
29 This removes the need to have seperate
30 code in the pmatch case block - it is
31 just CCL code now.
32
33 Use the actual CCL code in the CLO
34 section of ematch. No need for a recursive
35 pmatch call.
36
37 Use a bitmap table to set char bits in an
38 8-bit chunk.
39
40 Interfaces:
41 re_comp: compile a regular expression into a NFA.
42 char *re_comp(s)
43 char *s;
44 re_exec: execute the NFA to match a pattern.
45 int re_exec(s)
46 char *s;
47 Regular Expressions:
48 [1] char matches itself, unless it is a special
49 character (metachar): . \ [ ] * + ^ $
50 [2] . matches any character.
51 [3] \ matches the character following it.
52 It is used as an escape character for all
53 other meta-characters, and itself. When used
54 in a set ([4]), it is treated as an ordinary
55 character.
56 [4] [set] matches one of the characters in the set.
57 If the first character in the set is "^",
58 it matches a character NOT in the set, i.e.
59 complements the set. A shorthand S-E is
60 used to specify a set of characters S upto
61 E, inclusive. The special characters "]" and
62 "-" have no special meaning if they appear
63 as the first chars in the set.
64 examples: match:
65 [a-z] any lowercase alpha
66 [^]-] any char except ] and -
67 [^A-Z] any char except uppercase alpha
68 [a-zA-Z] any alpha
69 [5] * any regular expression form [1] to [4], followed by
70 closure char (*) matches zero or more matches of
71 that form.
72 [6] + same as [5], except it matches one or more.
73 [10] a composite regular expression xy where x and y
74 are in the form [1] to [10] matches the longest
75 match of x followed by a match for y.
76 [11] ^ a regular expression starting with a ^ character
77 $ and/or ending with a $ character, restricts the
78 pattern matching to the beginning of the line,
79 or the end of line. [anchors] Elsewhere in the
80 pattern, ^ and $ are treated as ordinary characters.
81
82 Acknowledgements:
83
84 HCR's Hugh Redelmeier has been most helpful in various
85 stages of development. He convinced me to include BOW
86 and EOW constructs, originally invented by Rob Pike at
87 the University of Toronto.
88
89 References:
90 Software tools Kernighan & Plauger
91 Software tools in Pascal Kernighan & Plauger
92 Grep [rsx-11 C dist] David Conroy
93 ed - text editor Un*x Programmer's Manual
94 Advanced editing on Un*x B. W. Kernighan
95 RegExp routines Henry Spencer
96
97 Notes:
98
99 This implementation uses a bit-set representation for character
100 classes for speed and compactness. Each character is represented
101 by one bit in a 128-bit block. Thus, CCL always takes a
102 constant 16 bytes in the internal nfa, and re_exec does a single
103 bit comparison to locate the character in the set.
104
105 Examples:
106
107 pattern: foo*.*
108 compile: CHR f CHR o CLO CHR o END CLO ANY END END
109 matches: fo foo fooo foobar fobar foxx ...
110
111 pattern: fo[ob]a[rz]
112 compile: CHR f CHR o CCL bitset CHR a CCL bitset END
113 matches: fobar fooar fobaz fooaz
114
115 pattern: foo\\+
116 compile: CHR f CHR o CHR o CHR \ CLO CHR \ END END
117 matches: foo\ foo\\ foo\\\ ...
118
119 pattern: \(foo\)[1-3]\1 (same as foo[1-3]foo)
120 compile: BOT 1 CHR f CHR o CHR o EOT 1 CCL bitset REF 1 END
121 matches: foo1foo foo2foo foo3foo
122
123 pattern: \(fo.*\)-\1
124 compile: BOT 1 CHR f CHR o CLO ANY END EOT 1 CHR - REF 1 END
125 matches: foo-foo fo-fo fob-fob foobar-foobar ...
126 */
127 #include <config.h>
128
129 #include <stdio.h> /* printf() */
130 #include "dwarf.h"
131 #include "libdwarf.h"
132 #include "dd_regex.h"
133 #include "dd_safe_strcpy.h"
134 #include "dd_checkutil.h"
135 #include "dd_glflags.h"
136
137 /* This version corrects two bugs (see 'code by davea'
138 below).
139 Compared to the original source:
140 Regular expression grouping with ()
141 is ignored and word checking is ignored.
142 Except when using ^ or $ in the regex
143 we find any matching substring.
144 David Anderson. 2 September 2021.
145 */
146
147 #ifndef DW_DLV_OK
148 /* Makes testing easier, these
149 must match libdwarf.h definitions */
150 #define DW_DLV_NO_ENTRY -1
151 #define DW_DLV_OK 0
152 #define DW_DLV_ERROR 1
153 #endif /* DW_DLV_OK */
154
155 #define inascii(x) (0177&(x))
156 #define MAXNFA 2048
157
158 #define OKP 1
159 #define NOP 0
160
161 #define CHR 1
162 #define ANY 2
163 #define CCL 3 /* character class [ */
164 #define BOL 4 /* beginning of line, ^ */
165 #define EOL 5 /* end of line, 5 */
166 #define REF 10
167 #define CLO 11
168
169 #define END 0
170 #define MAXPREDEF 11
171
172 /*
173 The following defines are not meant to be changeable.
174 They are for readability only.
175 */
176 #define MAXCHR 128
177 #define CHRBIT 8
178 #define BITBLK MAXCHR/CHRBIT
179 #define BLKIND 0170
180 #define BITIND 07
181
182 #define ASCIIB 0177
183
184 #ifdef NO_UCHAR
185 typedef char CHAR;
186 #else
187 typedef unsigned char CHAR;
188 #endif
189
190 static CHAR nfa[MAXNFA]; /* automaton.. */
191 static int sta = NOP; /* status of lastpat */
192
193 static CHAR bittab[BITBLK]; /* bit table for CCL */
194 /* pre-set bits... */
195 static CHAR bitarr[] = {1,2,4,8,16,32,64,128};
196
197 #ifdef DEBUG
198 static void nfadump(CHAR *);
199 static void symbolic(char *);
200 #endif
201
202 static void
203 chset(CHAR c)
204 {
205 bittab[(CHAR) ((c) & BLKIND) >> 3] |= bitarr[(c) & BITIND];
206 }
207
208 #define badpat (nfa[0] = END)
209 #define store(x) do { \
210 if ( mp > endpoint){ \
211 badpat; \
212 printf("ERROR: Pattern too large to store " \
213 "in regex\n"); \
214 glflags.gf_count_major_errors++; \
215 return DW_DLV_ERROR; \
216 } \
217 *mp++ = (x); \
218 } while(0)
219
220 static void
221 resetbittab(void)
222 {
223 int j = 0;
224 for (j = 0; j < BITBLK; ++j) {
225 bittab[j] = 0;
226 }
227 for (j = 0; j < MAXNFA; ++j) {
228 nfa[j] = 0;
229 }
230 sta = NOP;
231 }
232
233 #if 0
234 /* Some may not be alone,
235 . \ [ ] * + ^ $
236 but some can be.
237 */
238 static int
239 dangermetachar(CHAR c)
240 {
241 switch(c) {
242 case '?':
243 case '\\':
244 case '[':
245 case '+':
246 case '^':
247 case '$': return 1;
248 default:
249 return 0;
250 }
251 }
252 #endif
253
254 int
255 dd_re_comp(const char *pat)
256 {
257 const char *p = 0; /* pattern pointer */
258 CHAR *mp = nfa;
259 CHAR *lp = 0; /* saved pointer.. */
260 CHAR *sp = nfa; /* another one.. */
261 CHAR *endpoint = nfa+MAXNFA - 2;
262 int n = 0;
263 CHAR mask = 0; /* xor mask -CCL/NCL */
264 int c1 = 0;
265 int c2 = 0;
266
267 resetbittab();
268 if (!pat || !*pat) {
269 badpat;
270 printf("ERROR: Empty or NULL not a valid "
271 "regular expression\n");
272 glflags.gf_count_major_errors++;
273 return DW_DLV_NO_ENTRY;
274 }
275 for (p = pat; *p; p++) {
276 int a = (unsigned char)*p;
277 int b = inascii(*p);
278 if (b != a) {
279 badpat;
280 printf("ERROR: Only the ASCII subset of "
281 " characters are supported in dwarfdump "
282 "regular expressions\n");
283 glflags.gf_count_major_errors++;
284 return DW_DLV_NO_ENTRY;
285 }
286 }
287
288 for (p = pat; *p; p++) {
289 lp = mp;
290 switch(*p) {
291 case '.': /* match any char.. */
292 store(ANY);
293 break;
294
295 case '^': /* match beginning.. */
296 if (p == pat)
297 store(BOL);
298 else {
299 store(CHR);
300 store(*p);
301 }
302 break;
303
304 case '$': /* match endofline.. */
305 if (!*(p+1)) {
306 store(EOL);
307 } else {
308 store(CHR);
309 store(*p);
310 }
311 break;
312
313 case '[': /* match char class..*/
314 store(CCL);
315 if (*++p == '^') {
316 mask = 0377;
317 p++;
318 } else {
319 mask = 0;
320 }
321 if (*p == '-') { /* real dash */
322 chset(*p++);
323 }
324 if (*p == ']') { /* real brac */
325 chset(*p++);
326 }
327 while (*p && *p != ']') {
328 if (*p == '-' && *(p+1) && *(p+1) != ']') {
329 p++;
330 c1 = *(p-2) + 1;
331 c2 = *p++;
332 while (c1 <= c2)
333 chset((CHAR)c1++);
334 }
335 #ifdef EXTEND
336 else if (*p == '\\' && *(p+1)) {
337 p++;
338 chset(*p++);
339 }
340 #endif /* EXTEND */
341 else {
342 chset(*p++);
343 }
344 }
345 if (!*p) {
346 badpat;
347 printf("ERROR: Regular expression %s missing ]\n",
348 pat) ;
349 glflags.gf_count_major_errors++;
350 return DW_DLV_ERROR;
351 }
352 /* Storing the bitmask into nfa */
353 for (n = 0; n < BITBLK; bittab[n++] =
354 (char) 0) {
355 store(mask ^ bittab[n]);
356 }
357 break;
358
359 case '*': /* match 0 or more.. */
360 case '+': /* match 1 or more.. */
361 if (p == pat) {
362 badpat;
363 printf("ERROR: Regular expression %s has empty * + "
364 "Closure\n",pat);
365 glflags.gf_count_major_errors++;
366 return DW_DLV_ERROR;
367 }
368 lp = sp; /* previous opcode */
369 if (*lp == CLO) { /* equivalence.. */
370 break;
371 }
372 switch(*lp) {
373
374 case BOL:
375 case REF:
376 badpat;
377 printf("ERROR Regular expression %s has illegal "
378 "* + closure\n",pat);
379 glflags.gf_count_major_errors++;
380 return DW_DLV_ERROR;
381 default:
382 break;
383 }
384
385 if (*p == '+') {
386 for (sp = mp; lp < sp; lp++) {
387 store(*lp);
388 }
389 }
390
391 store(END);
392 store(END);
393 sp = mp;
394 while (--mp > lp) {
395 *mp = mp[-1];
396 }
397 store(CLO);
398 mp = sp;
399 break;
400
401 case '\\': /* tags, backrefs .. */
402 ++p;
403 if (!*p) {
404 badpat;
405 printf("ERROR Regular expression backslash"
406 " missing its operand. Erroneous regex\n");
407 glflags.gf_count_major_errors++;
408 return DW_DLV_ERROR;
409 }
410 store(CHR);
411 store(*p);
412 break;
413 default : /* an ordinary char */
414 store(CHR);
415 store(*p);
416 break;
417 }
418 sp = lp;
419 }
420 store(END);
421 sta = OKP;
422 #ifdef DEBUG
423 symbolic("Final nfa");
424 #endif /* DEBUG */
425 return DW_DLV_OK;
426 }
427
428 static char *bol;
429 static int dd_pmatch(const char *, CHAR *,char **str_out,
430 int level);
431
432 /*
433 re_exec:
434 execute nfa to find a match.
435 special cases: (nfa[0])
436 BOL Match only once, starting from the
437 beginning.
438 CHR First locate the character without
439 calling pmatch, and if found, call
440 pmatch for the remaining string.
441 END re_comp failed, poor luser did not
442 check for it. Fail fast.
443 If a match is found, bopat[0] and eopat[0] are set
444 to the beginning and the end of the matched fragment,
445 respectively.
446
447 return DW_DLV_OK, DW_DLV_NO_ENTRY or DW_DLV_ERROR
448 */
449
450 int
451 dd_re_exec(char *lp)
452 {
453 CHAR c = 0;
454 char *ep = 0;
455 CHAR *ap = nfa;
456 int res = 0;
457 int level = 0;
458
459 bol = lp;
460
461 switch(*ap) {
462 case BOL: /* anchored: match from BOL only */
463 res = dd_pmatch(lp,ap,&ep,level);
464 if (res != DW_DLV_OK) {
465 return res;
466 }
467 break;
468 case CHR: /* ordinary char: locate it fast */
469 c = *(ap+1);
470 while (*lp && *lp != c) {
471 lp++;
472 }
473 if (!*lp) { /* if EOS, fail, else fall thru. */
474 return DW_DLV_NO_ENTRY;
475 }
476 goto regmatch; /* GO TO avoids a fall-through
477 warning from gcc */
478 default: { /* regular matching all the way. */
479 regmatch:
480 do {
481 res = dd_pmatch(lp,ap,&ep,level);
482 if (res == DW_DLV_ERROR) {
483 return res;
484 }
485 if (res == DW_DLV_OK) {
486 break;
487 }
488 lp++;
489 } while (*lp);
490 break;
491 }
492 case END: /* munged automaton. fail always */
493 badpat;
494 printf("ERROR in in regex automaton. "
495 "END out of place\n");
496 glflags.gf_count_major_errors++;
497 return DW_DLV_ERROR;
498 }
499 if (res != DW_DLV_OK) {
500 return res;
501 }
502 return DW_DLV_OK;
503 }
504
505 /*
506 dd_pmatch: internal routine for the hard part
507
508 This code is partly snarfed from an early grep written by
509 David Conroy. The backref and tag stuff, and various other
510 innovations are by oz.
511
512 special case optimizations: (nfa[n], nfa[n+1])
513 CLO ANY
514 We KNOW .* will match everything upto the
515 end of line. Thus, directly go to the end of
516 line, without recursive pmatch calls. As in
517 the other closure cases, the remaining pattern
518 must be matched by moving backwards on the
519 string recursively, to find a match for xy
520 (x is ".*" and y is the remaining pattern)
521 where the match satisfies the LONGEST match for
522 x followed by a match for y.
523 CLO CHR
524 We can again scan the string forward for the
525 single char and at the point of failure, we
526 execute the remaining nfa recursively, same as
527 above.
528
529 At the end of a successful match, bopat[n] and eopat[n]
530 are set to the beginning and end of subpatterns matched
531 by tagged expressions (n = 1 to 9).
532
533 returns DW_DLV_OK for a match, and sets the ep pointer
534 to point into the input at the next char to check
535 DW_DLV_NO_ENTRY for a non-match
536 DW_DLV_NO_ERROR for an internal error
537 */
538
539 /*
540 character classification table for word boundary operators BOW
541 and EOW. the reason for not using ctype macros is that we can
542 let the user add into our own table. see re_modw. This table
543 is not in the bitset form, since we may wish to extend it in the
544 future for other character classifications.
545
546 TRUE for 0-9 A-Z a-z _
547 */
548 #if 0 /* For debugging only */
549 static char *
550 naming(CHAR c)
551 {
552 #define CHR 1
553 #define ANY 2
554 #define CCL 3 /* character class [ */
555 #define BOL 4 /* beginning of line, ^ */
556 #define EOL 5 /* end of line, 5 */
557 #define BOT 6 /* beginning of tag, ( */
558 #define EOT 7 /* end of tag, ) */
559 #define BOW 8 /* nonstandard beginning of ? < */
560 #define EOW 9 /* nonstandard end of ? > */
561
562 static int use1;
563 /* Two result arrays so we can allow naming called twice
564 in one printf. Turns any UCHAR into a useful string.
565 Array index must match the #define value for each name.*/
566 static char nam1[10];
567 static char nam2[10];
568 static char * n[] = {
569 "END(0)",
570 "CHR",
571 "ANY",
572 "CCL",
573 "BOL",
574 "EOL",
575 "BOT",
576 "EOT",
577 "BOW",
578 "EOW",
579 "REF",
580 "CLO",
581 "bogus",
582 };
583 char *outtab= 0;
584
585 if (use1) {
586 outtab = nam1;
587 } else {
588 outtab = nam2;
589 }
590 outtab[0] = 0;
591 if (c && c <= MAXPREDEF) {
592 dd_safe_strcpy(outtab,sizeof(nam1),n[c],strlen(n[c]));
593 } else {
594 sprintf(outtab,"0x%x",c); /* debugging only */
595 }
596 use1 = !use1;
597 return outtab;
598 }
599 #define iswordc(x) chrtyp[inascii(x)]
600 #endif /* 0 */
601 #define isinset(x,y) ((x)[((y)&BLKIND)>>3] & bitarr[(y)&BITIND])
602
603 /* skip values for CLO XXX to skip past the closure */
604
605 #define ANYSKIP 2 /* [CLO] ANY END ... */
606 #define CHRSKIP 3 /* [CLO] CHR chr END ... */
607 #define CCLSKIP 18 /* [CLO] CCL 16bytes END ... */
608
609 static int
610 dd_pmatch(const char *lp, CHAR *ap,char **end_ptr,
611 int level)
612 {
613 int op = 0;
614 int c = 0;
615 int n = 0;
616 char *e = 0; /* extra pointer for CLO */
617 int res = 0;
618
619 while ((op = *ap) != END) {
620 ap++;
621 switch(op) {
622 case CHR:
623 if (*lp++ != *ap++) {
624 return DW_DLV_NO_ENTRY;
625 }
626 break;
627 case ANY:
628 if (!*lp++) {
629 return DW_DLV_NO_ENTRY;
630 }
631 break;
632 case CCL:
633 c = *lp++;
634 if (!isinset(ap,c)) {
635 return DW_DLV_NO_ENTRY;
636 }
637
638 ap += BITBLK;
639 break;
640 case BOL:
641 if (lp != bol) {
642 return DW_DLV_NO_ENTRY;
643 }
644 break;
645 case EOL:
646 if (*lp) {
647 return DW_DLV_NO_ENTRY;
648 }
649 break;
650 case CLO: {
651 const char *are = lp;
652 switch(*ap) {
653 case ANY:
654 while (*lp) {
655 lp++;
656 }
657 n = ANYSKIP;
658 break;
659 case CHR:
660 c = *(ap+1);
661 while (*lp && c == *lp) {
662 lp++;
663 }
664 n = CHRSKIP;
665 break;
666 case CCL:
667 for (c = *lp ; c && isinset(ap+1,c); c = *lp) {
668 lp++;
669 }
670 n = CCLSKIP;
671 break;
672 default:
673 badpat;
674 printf("ERROR Regular expression has illegal "
675 "closure: bad nfa\n");
676 glflags.gf_count_major_errors++;
677 return DW_DLV_ERROR;
678 }
679 ap += n;
680 if (lp == are) {
681 /* [code by davea]
682 Empty closure is fine for early accept iff
683 it is the end of the regex too. Else
684 this is a NO_ENTRY */
685 if (!*lp && !*ap) {
686 /* early accept. Nothing left to check. */
687 return DW_DLV_OK;
688 }
689 return DW_DLV_NO_ENTRY;
690 }
691 while (lp >= are) {
692 res = dd_pmatch(lp, ap,&e,level+1);
693 if (res == DW_DLV_ERROR) {
694 return res;
695 }
696 if (res == DW_DLV_OK) {
697 *end_ptr = e;
698 return res;
699 }
700 /* NO_ENTRY so far */
701 --lp;
702 }
703 }
704 return DW_DLV_NO_ENTRY;
705 default:
706 badpat;
707 printf("ERROR Regular expression has illegal "
708 "dd_re_exec: bad nfa.\n");
709 glflags.gf_count_major_errors++;
710 return DW_DLV_ERROR;
711 }
712 }
713 *end_ptr = (char *)lp;
714 return DW_DLV_OK;
715 }
716
717 #ifdef DEBUG
718 /* symbolic - produce a symbolic dump of the nfa */
719 static void
720 symbolic(char *s)
721 {
722 printf("pattern: %s\n", s);
723 printf("nfacode:\n");
724 nfadump(nfa);
725 }
726
727 static void
728 nfadump(CHAR *ap)
729 {
730 register int n = 0;
731
732 while (*ap != END)
733 switch(*ap++) {
734 case CLO:
735 printf("CLOSURE");
736 nfadump(ap);
737 switch(*ap) {
738 case CHR:
739 n = CHRSKIP;
740 break;
741 case ANY:
742 n = ANYSKIP;
743 break;
744 case CCL:
745 n = CCLSKIP;
746 break;
747 default: break;
748 }
749 ap += n;
750 break;
751 case CHR:
752 printf("\tCHR %c\n",*ap++);
753 break;
754 case ANY:
755 printf("\tANY .\n");
756 break;
757 case BOL:
758 printf("\tBOL -\n");
759 break;
760 case EOL:
761 printf("\tEOL -\n");
762 break;
763 case CCL:
764 printf("\tCCL [");
765 for (n = 0; n < MAXCHR; n++)
766 if (isinset(ap,(CHAR)n)) {
767 if (n < ' ')
768 printf("^%c", n ^ 0x040);
769 else
770 printf("%c", n);
771 }
772 printf("]\n");
773 ap += BITBLK;
774 break;
775 default:
776 printf("bad nfa. opcode %o\n", ap[-1]);
777 exit(EXIT_FAILURE);
778 break;
779 }
780 }
781 #endif /* DEBUG */