1 /* Extended regular expression matching and search library,
2 * version 0.12.
3 * (Implements POSIX draft P10003.2/D11.2, except for
4 * internationalization features.)
5 *
6 * Copyright (C) 1993 Free Software Foundation, Inc.
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2, or (at your option)
11 * any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
21
22 /* AIX requires this to be the first thing in the file. */
23 #if defined (_AIX) && !defined (REGEX_MALLOC)
24 #pragma alloca
25 #endif
26
27 #define _GNU_SOURCE
28
29 /*****
30 * Original GNU regex is part of another package which includes the
31 * configure stuff. Until we get XmHTML working properly with autoconf,
32 * we set some reasonable defaults instead.
33 *****/
34 #ifdef HAVE_CONFIG_H
35 # include "config.h"
36 #else
37 # define HAVE_STRING_H 1
38 # define STDC_HEADERS 1
39 #endif
40
41 #if !HAVE_ALLOCA
42 #define REGEX_MALLOC 1
43 #endif
44
45 /* The `emacs' switch turns on certain matching commands
46 * that make sense only in Emacs. */
47 #ifdef emacs
48
49 #include "lisp.h"
50 #include "buffer.h"
51 #include "syntax.h"
52
53 /* Emacs uses `NULL' as a predicate. */
54 #undef NULL
55
56 #else /* not emacs */
57
58 /* We used to test for `BSTRING' here, but only GCC and Emacs define
59 * `BSTRING', as far as I know, and neither of them use this code. */
60 #if defined(HAVE_STRING_H) || defined(STDC_HEADERS)
61 #include <string.h>
62 #ifndef bcmp
63 #define bcmp(s1, s2, n) memcmp ((s1), (s2), (n))
64 #endif
65 #ifndef bcopy
66 #define bcopy(s, d, n) memcpy ((d), (s), (n))
67 #endif
68 #ifndef bzero
69 #define bzero(s, n) memset ((s), 0, (n))
70 #endif
71 #else
72 #include <strings.h>
73 #endif
74
75 #ifdef STDC_HEADERS
76 #include <stdlib.h>
77 #else
78 char *malloc();
79 char *realloc();
80 #endif
81
82
83 /* Define the syntax stuff for \<, \>, etc. */
84
85 /* This must be nonzero for the wordchar and notwordchar pattern
86 * commands in re_match_2. */
87 #ifndef Sword
88 #define Sword 1
89 #endif
90
91 #ifdef SYNTAX_TABLE
92
93 extern char *re_syntax_table;
94
95 #else /* not SYNTAX_TABLE */
96
97 /* How many characters in the character set. */
98 #define CHAR_SET_SIZE 256
99
100 static char re_syntax_table[CHAR_SET_SIZE];
101
102 static void
init_syntax_once()103 init_syntax_once()
104 {
105 register int c;
106 static int done = 0;
107
108 if (done)
109 return;
110
111 bzero(re_syntax_table, sizeof re_syntax_table);
112
113 for (c = 'a'; c <= 'z'; c++)
114 re_syntax_table[c] = Sword;
115
116 for (c = 'A'; c <= 'Z'; c++)
117 re_syntax_table[c] = Sword;
118
119 for (c = '0'; c <= '9'; c++)
120 re_syntax_table[c] = Sword;
121
122 re_syntax_table['_'] = Sword;
123
124 done = 1;
125 }
126
127 #endif /* not SYNTAX_TABLE */
128
129 #define SYNTAX(c) re_syntax_table[c]
130
131 #endif /* not emacs */
132
133 /* Get the interface, including the syntax bits. */
134 #include "GNUregex.h"
135
136 /* isalpha etc. are used for the character classes. */
137 #include <ctype.h>
138
139 #ifndef isascii
140 #define isascii(c) 1
141 #endif
142
143 #ifdef isblank
144 #define ISBLANK(c) (isascii (c) && isblank (c))
145 #else
146 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
147 #endif
148 #ifdef isgraph
149 #define ISGRAPH(c) (isascii (c) && isgraph (c))
150 #else
151 #define ISGRAPH(c) (isascii (c) && isprint (c) && !isspace (c))
152 #endif
153
154 #define ISPRINT(c) (isascii (c) && isprint (c))
155 #define ISDIGIT(c) (isascii (c) && isdigit (c))
156 #define ISALNUM(c) (isascii (c) && isalnum (c))
157 #define ISALPHA(c) (isascii (c) && isalpha (c))
158 #define ISCNTRL(c) (isascii (c) && iscntrl (c))
159 #define ISLOWER(c) (isascii (c) && islower (c))
160 #define ISPUNCT(c) (isascii (c) && ispunct (c))
161 #define ISSPACE(c) (isascii (c) && isspace (c))
162 #define ISUPPER(c) (isascii (c) && isupper (c))
163 #define ISXDIGIT(c) (isascii (c) && isxdigit (c))
164
165 #ifndef NULL
166 #define NULL 0
167 #endif
168
169 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
170 * since ours (we hope) works properly with all combinations of
171 * machines, compilers, `char' and `unsigned char' argument types.
172 * (Per Bothner suggested the basic approach.) */
173 #undef SIGN_EXTEND_CHAR
174 #ifdef __STDC__
175 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
176 #else /* not __STDC__ */
177 /* As in Harbison and Steele. */
178 #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
179 #endif
180
181 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
182 * use `alloca' instead of `malloc'. This is because using malloc in
183 * re_search* or re_match* could cause memory leaks when C-g is used in
184 * Emacs; also, malloc is slower and causes storage fragmentation. On
185 * the other hand, malloc is more portable, and easier to debug.
186 *
187 * Because we sometimes use alloca, some routines have to be macros,
188 * not functions -- `alloca'-allocated space disappears at the end of the
189 * function it is called in. */
190
191 #ifdef REGEX_MALLOC
192
193 #define REGEX_ALLOCATE malloc
194 #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
195
196 #else /* not REGEX_MALLOC */
197
198 /* Emacs already defines alloca, sometimes. */
199 #ifndef alloca
200
201 /* Make alloca work the best possible way. */
202 #ifdef __GNUC__
203 #define alloca __builtin_alloca
204 #else /* not __GNUC__ */
205 #if HAVE_ALLOCA_H
206 #include <alloca.h>
207 #else /* not __GNUC__ or HAVE_ALLOCA_H */
208 #ifndef _AIX /* Already did AIX, up at the top. */
209 char *alloca();
210 #endif /* not _AIX */
211 #endif /* not HAVE_ALLOCA_H */
212 #endif /* not __GNUC__ */
213
214 #endif /* not alloca */
215
216 #define REGEX_ALLOCATE alloca
217
218 /* Assumes a `char *destination' variable. */
219 #define REGEX_REALLOCATE(source, osize, nsize) \
220 (destination = (char *) alloca (nsize), \
221 bcopy (source, destination, osize), \
222 destination)
223
224 #endif /* not REGEX_MALLOC */
225
226
227 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
228 * `string1' or just past its end. This works if PTR is NULL, which is
229 * a good thing. */
230 #define FIRST_STRING_P(ptr) \
231 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
232
233 /* (Re)Allocate N items of type T using malloc, or fail. */
234 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
235 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
236 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
237
238 #define BYTEWIDTH 8 /* In bits. */
239
240 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
241
242 #define MAX(a, b) ((a) > (b) ? (a) : (b))
243 #define MIN(a, b) ((a) < (b) ? (a) : (b))
244
245 typedef char boolean;
246 #define false 0
247 #define true 1
248
249 /* These are the command codes that appear in compiled regular
250 * expressions. Some opcodes are followed by argument bytes. A
251 * command code can specify any interpretation whatsoever for its
252 * arguments. Zero bytes may appear in the compiled regular expression.
253 *
254 * The value of `exactn' is needed in search.c (search_buffer) in Emacs.
255 * So regex.h defines a symbol `RE_EXACTN_VALUE' to be 1; the value of
256 * `exactn' we use here must also be 1. */
257
258 typedef enum {
259 no_op = 0,
260
261 /* Followed by one byte giving n, then by n literal bytes. */
262 exactn = 1,
263
264 /* Matches any (more or less) character. */
265 anychar,
266
267 /* Matches any one char belonging to specified set. First
268 * following byte is number of bitmap bytes. Then come bytes
269 * for a bitmap saying which chars are in. Bits in each byte
270 * are ordered low-bit-first. A character is in the set if its
271 * bit is 1. A character too large to have a bit in the map is
272 * automatically not in the set. */
273 charset,
274
275 /* Same parameters as charset, but match any character that is
276 * not one of those specified. */
277 charset_not,
278
279 /* Start remembering the text that is matched, for storing in a
280 * register. Followed by one byte with the register number, in
281 * the range 0 to one less than the pattern buffer's re_nsub
282 * field. Then followed by one byte with the number of groups
283 * inner to this one. (This last has to be part of the
284 * start_memory only because we need it in the on_failure_jump
285 * of re_match_2.) */
286 start_memory,
287
288 /* Stop remembering the text that is matched and store it in a
289 * memory register. Followed by one byte with the register
290 * number, in the range 0 to one less than `re_nsub' in the
291 * pattern buffer, and one byte with the number of inner groups,
292 * just like `start_memory'. (We need the number of inner
293 * groups here because we don't have any easy way of finding the
294 * corresponding start_memory when we're at a stop_memory.) */
295 stop_memory,
296
297 /* Match a duplicate of something remembered. Followed by one
298 * byte containing the register number. */
299 duplicate,
300
301 /* Fail unless at beginning of line. */
302 begline,
303
304 /* Fail unless at end of line. */
305 endline,
306
307 /* Succeeds if at beginning of buffer (if emacs) or at beginning
308 * of string to be matched (if not). */
309 begbuf,
310
311 /* Analogously, for end of buffer/string. */
312 endbuf,
313
314 /* Followed by two byte relative address to which to jump. */
315 jump,
316
317 /* Same as jump, but marks the end of an alternative. */
318 jump_past_alt,
319
320 /* Followed by two-byte relative address of place to resume at
321 * in case of failure. */
322 on_failure_jump,
323
324 /* Like on_failure_jump, but pushes a placeholder instead of the
325 * current string position when executed. */
326 on_failure_keep_string_jump,
327
328 /* Throw away latest failure point and then jump to following
329 * two-byte relative address. */
330 pop_failure_jump,
331
332 /* Change to pop_failure_jump if know won't have to backtrack to
333 * match; otherwise change to jump. This is used to jump
334 * back to the beginning of a repeat. If what follows this jump
335 * clearly won't match what the repeat does, such that we can be
336 * sure that there is no use backtracking out of repetitions
337 * already matched, then we change it to a pop_failure_jump.
338 * Followed by two-byte address. */
339 maybe_pop_jump,
340
341 /* Jump to following two-byte address, and push a dummy failure
342 * point. This failure point will be thrown away if an attempt
343 * is made to use it for a failure. A `+' construct makes this
344 * before the first repeat. Also used as an intermediary kind
345 * of jump when compiling an alternative. */
346 dummy_failure_jump,
347
348 /* Push a dummy failure point and continue. Used at the end of
349 * alternatives. */
350 push_dummy_failure,
351
352 /* Followed by two-byte relative address and two-byte number n.
353 * After matching N times, jump to the address upon failure. */
354 succeed_n,
355
356 /* Followed by two-byte relative address, and two-byte number n.
357 * Jump to the address N times, then fail. */
358 jump_n,
359
360 /* Set the following two-byte relative address to the
361 * subsequent two-byte number. The address *includes* the two
362 * bytes of number. */
363 set_number_at,
364
365 wordchar, /* Matches any word-constituent character. */
366 notwordchar, /* Matches any char that is not a word-constituent. */
367
368 wordbeg, /* Succeeds if at word beginning. */
369 wordend, /* Succeeds if at word end. */
370
371 wordbound, /* Succeeds if at a word boundary. */
372 notwordbound /* Succeeds if not at a word boundary. */
373
374 #ifdef emacs
375 ,before_dot, /* Succeeds if before point. */
376 at_dot, /* Succeeds if at point. */
377 after_dot, /* Succeeds if after point. */
378
379 /* Matches any character whose syntax is specified. Followed by
380 * a byte which contains a syntax code, e.g., Sword. */
381 syntaxspec,
382
383 /* Matches any character whose syntax is not that specified. */
384 notsyntaxspec
385 #endif /* emacs */
386 } re_opcode_t;
387
388 /* Common operations on the compiled pattern. */
389
390 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
391
392 #define STORE_NUMBER(destination, number) \
393 do { \
394 (destination)[0] = (number) & 0377; \
395 (destination)[1] = (number) >> 8; \
396 } while (0)
397
398 /* Same as STORE_NUMBER, except increment DESTINATION to
399 * the byte after where the number is stored. Therefore, DESTINATION
400 * must be an lvalue. */
401
402 #define STORE_NUMBER_AND_INCR(destination, number) \
403 do { \
404 STORE_NUMBER (destination, number); \
405 (destination) += 2; \
406 } while (0)
407
408 /* Put into DESTINATION a number stored in two contiguous bytes starting
409 * at SOURCE. */
410
411 #define EXTRACT_NUMBER(destination, source) \
412 do { \
413 (destination) = *(source) & 0377; \
414 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
415 } while (0)
416
417 #ifdef DEBUG
418 static void
extract_number(dest,source)419 extract_number(dest, source)
420 int *dest;
421 unsigned char *source;
422 {
423 int temp = SIGN_EXTEND_CHAR(*(source + 1));
424 *dest = *source & 0377;
425 *dest += temp << 8;
426 }
427
428 #ifndef EXTRACT_MACROS /* To debug the macros. */
429 #undef EXTRACT_NUMBER
430 #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
431 #endif /* not EXTRACT_MACROS */
432
433 #endif /* DEBUG */
434
435 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
436 * SOURCE must be an lvalue. */
437
438 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
439 do { \
440 EXTRACT_NUMBER (destination, source); \
441 (source) += 2; \
442 } while (0)
443
444 #ifdef DEBUG
445 static void
extract_number_and_incr(destination,source)446 extract_number_and_incr(destination, source)
447 int *destination;
448 unsigned char **source;
449 {
450 extract_number(destination, *source);
451 *source += 2;
452 }
453
454 #ifndef EXTRACT_MACROS
455 #undef EXTRACT_NUMBER_AND_INCR
456 #define EXTRACT_NUMBER_AND_INCR(dest, src) \
457 extract_number_and_incr (&dest, &src)
458 #endif /* not EXTRACT_MACROS */
459
460 #endif /* DEBUG */
461
462 /* If DEBUG is defined, Regex prints many voluminous messages about what
463 * it is doing (if the variable `debug' is nonzero). If linked with the
464 * main program in `iregex.c', you can enter patterns and strings
465 * interactively. And if linked with the main program in `main.c' and
466 * the other test files, you can run the already-written tests. */
467
468 #ifdef DEBUG
469
470 /* We use standard I/O for debugging. */
471 #include <stdio.h>
472
473 /* It is useful to test things that ``must'' be true when debugging. */
474 #include <assert.h>
475
476 static int debug = 0;
477
478 #define DEBUG_STATEMENT(e) e
479 #define DEBUG_PRINT1(x) if (debug) printf (x)
480 #define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
481 #define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
482 #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
483 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
484 if (debug) print_partial_compiled_pattern (s, e)
485 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
486 if (debug) print_double_string (w, s1, sz1, s2, sz2)
487
488
489 extern void printchar();
490
491 /* Print the fastmap in human-readable form. */
492
493 void
print_fastmap(fastmap)494 print_fastmap(fastmap)
495 char *fastmap;
496 {
497 unsigned was_a_range = 0;
498 unsigned i = 0;
499
500 while (i < (1 << BYTEWIDTH)) {
501 if (fastmap[i++]) {
502 was_a_range = 0;
503 printchar(i - 1);
504 while (i < (1 << BYTEWIDTH) && fastmap[i]) {
505 was_a_range = 1;
506 i++;
507 }
508 if (was_a_range) {
509 printf("-");
510 printchar(i - 1);
511 }
512 }
513 }
514 putchar('\n');
515 }
516
517
518 /* Print a compiled pattern string in human-readable form, starting at
519 * the START pointer into it and ending just before the pointer END. */
520
521 void
print_partial_compiled_pattern(start,end)522 print_partial_compiled_pattern(start, end)
523 unsigned char *start;
524 unsigned char *end;
525 {
526 int mcnt, mcnt2;
527 unsigned char *p = start;
528 unsigned char *pend = end;
529
530 if (start == NULL) {
531 printf("(null)\n");
532 return;
533 }
534 /* Loop over pattern commands. */
535 while (p < pend) {
536 switch ((re_opcode_t) * p++) {
537 case no_op:
538 printf("/no_op");
539 break;
540
541 case exactn:
542 mcnt = *p++;
543 printf("/exactn/%d", mcnt);
544 do {
545 putchar('/');
546 printchar(*p++);
547 }
548 while (--mcnt);
549 break;
550
551 case start_memory:
552 mcnt = *p++;
553 printf("/start_memory/%d/%d", mcnt, *p++);
554 break;
555
556 case stop_memory:
557 mcnt = *p++;
558 printf("/stop_memory/%d/%d", mcnt, *p++);
559 break;
560
561 case duplicate:
562 printf("/duplicate/%d", *p++);
563 break;
564
565 case anychar:
566 printf("/anychar");
567 break;
568
569 case charset:
570 case charset_not:
571 {
572 register int c;
573
574 printf("/charset%s",
575 (re_opcode_t) * (p - 1) == charset_not ? "_not" : "");
576
577 assert(p + *p < pend);
578
579 for (c = 0; c < *p; c++) {
580 unsigned bit;
581 unsigned char map_byte = p[1 + c];
582
583 putchar('/');
584
585 for (bit = 0; bit < BYTEWIDTH; bit++)
586 if (map_byte & (1 << bit))
587 printchar(c * BYTEWIDTH + bit);
588 }
589 p += 1 + *p;
590 break;
591 }
592
593 case begline:
594 printf("/begline");
595 break;
596
597 case endline:
598 printf("/endline");
599 break;
600
601 case on_failure_jump:
602 extract_number_and_incr(&mcnt, &p);
603 printf("/on_failure_jump/0/%d", mcnt);
604 break;
605
606 case on_failure_keep_string_jump:
607 extract_number_and_incr(&mcnt, &p);
608 printf("/on_failure_keep_string_jump/0/%d", mcnt);
609 break;
610
611 case dummy_failure_jump:
612 extract_number_and_incr(&mcnt, &p);
613 printf("/dummy_failure_jump/0/%d", mcnt);
614 break;
615
616 case push_dummy_failure:
617 printf("/push_dummy_failure");
618 break;
619
620 case maybe_pop_jump:
621 extract_number_and_incr(&mcnt, &p);
622 printf("/maybe_pop_jump/0/%d", mcnt);
623 break;
624
625 case pop_failure_jump:
626 extract_number_and_incr(&mcnt, &p);
627 printf("/pop_failure_jump/0/%d", mcnt);
628 break;
629
630 case jump_past_alt:
631 extract_number_and_incr(&mcnt, &p);
632 printf("/jump_past_alt/0/%d", mcnt);
633 break;
634
635 case jump:
636 extract_number_and_incr(&mcnt, &p);
637 printf("/jump/0/%d", mcnt);
638 break;
639
640 case succeed_n:
641 extract_number_and_incr(&mcnt, &p);
642 extract_number_and_incr(&mcnt2, &p);
643 printf("/succeed_n/0/%d/0/%d", mcnt, mcnt2);
644 break;
645
646 case jump_n:
647 extract_number_and_incr(&mcnt, &p);
648 extract_number_and_incr(&mcnt2, &p);
649 printf("/jump_n/0/%d/0/%d", mcnt, mcnt2);
650 break;
651
652 case set_number_at:
653 extract_number_and_incr(&mcnt, &p);
654 extract_number_and_incr(&mcnt2, &p);
655 printf("/set_number_at/0/%d/0/%d", mcnt, mcnt2);
656 break;
657
658 case wordbound:
659 printf("/wordbound");
660 break;
661
662 case notwordbound:
663 printf("/notwordbound");
664 break;
665
666 case wordbeg:
667 printf("/wordbeg");
668 break;
669
670 case wordend:
671 printf("/wordend");
672
673 #ifdef emacs
674 case before_dot:
675 printf("/before_dot");
676 break;
677
678 case at_dot:
679 printf("/at_dot");
680 break;
681
682 case after_dot:
683 printf("/after_dot");
684 break;
685
686 case syntaxspec:
687 printf("/syntaxspec");
688 mcnt = *p++;
689 printf("/%d", mcnt);
690 break;
691
692 case notsyntaxspec:
693 printf("/notsyntaxspec");
694 mcnt = *p++;
695 printf("/%d", mcnt);
696 break;
697 #endif /* emacs */
698
699 case wordchar:
700 printf("/wordchar");
701 break;
702
703 case notwordchar:
704 printf("/notwordchar");
705 break;
706
707 case begbuf:
708 printf("/begbuf");
709 break;
710
711 case endbuf:
712 printf("/endbuf");
713 break;
714
715 default:
716 printf("?%d", *(p - 1));
717 }
718 }
719 printf("/\n");
720 }
721
722
723 void
print_compiled_pattern(bufp)724 print_compiled_pattern(bufp)
725 struct re_pattern_buffer *bufp;
726 {
727 unsigned char *buffer = bufp->buffer;
728
729 print_partial_compiled_pattern(buffer, buffer + bufp->used);
730 printf("%d bytes used/%d bytes allocated.\n", bufp->used, bufp->allocated);
731
732 if (bufp->fastmap_accurate && bufp->fastmap) {
733 printf("fastmap: ");
734 print_fastmap(bufp->fastmap);
735 }
736 printf("re_nsub: %d\t", bufp->re_nsub);
737 printf("regs_alloc: %d\t", bufp->regs_allocated);
738 printf("can_be_null: %d\t", bufp->can_be_null);
739 printf("newline_anchor: %d\n", bufp->newline_anchor);
740 printf("no_sub: %d\t", bufp->no_sub);
741 printf("not_bol: %d\t", bufp->not_bol);
742 printf("not_eol: %d\t", bufp->not_eol);
743 printf("syntax: %d\n", bufp->syntax);
744 /* Perhaps we should print the translate table? */
745 }
746
747
748 void
print_double_string(where,string1,size1,string2,size2)749 print_double_string(where, string1, size1, string2, size2)
750 const char *where;
751 const char *string1;
752 const char *string2;
753 int size1;
754 int size2;
755 {
756 unsigned this_char;
757
758 if (where == NULL)
759 printf("(null)");
760 else {
761 if (FIRST_STRING_P(where)) {
762 for (this_char = where - string1; this_char < size1; this_char++)
763 printchar(string1[this_char]);
764
765 where = string2;
766 }
767 for (this_char = where - string2; this_char < size2; this_char++)
768 printchar(string2[this_char]);
769 }
770 }
771
772 #else /* not DEBUG */
773
774 #undef assert
775 #define assert(e)
776
777 #define DEBUG_STATEMENT(e)
778 #define DEBUG_PRINT1(x)
779 #define DEBUG_PRINT2(x1, x2)
780 #define DEBUG_PRINT3(x1, x2, x3)
781 #define DEBUG_PRINT4(x1, x2, x3, x4)
782 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
783 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
784
785 #endif /* not DEBUG */
786
787 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
788 * also be assigned to arbitrarily: each pattern buffer stores its own
789 * syntax, so it can be changed between regex compilations. */
790 reg_syntax_t re_syntax_options = RE_SYNTAX_EMACS;
791
792
793 /* Specify the precise syntax of regexps for compilation. This provides
794 * for compatibility for various utilities which historically have
795 * different, incompatible syntaxes.
796 *
797 * The argument SYNTAX is a bit mask comprised of the various bits
798 * defined in regex.h. We return the old syntax. */
799
800 reg_syntax_t
re_set_syntax(syntax)801 re_set_syntax(syntax)
802 reg_syntax_t syntax;
803 {
804 reg_syntax_t ret = re_syntax_options;
805
806 re_syntax_options = syntax;
807 return ret;
808 }
809
810 /* This table gives an error message for each of the error codes listed
811 * in regex.h. Obviously the order here has to be same as there. */
812
813 static const char *re_error_msg[] =
814 {NULL, /* REG_NOERROR */
815 "No match", /* REG_NOMATCH */
816 "Invalid regular expression", /* REG_BADPAT */
817 "Invalid collation character", /* REG_ECOLLATE */
818 "Invalid character class name", /* REG_ECTYPE */
819 "Trailing backslash", /* REG_EESCAPE */
820 "Invalid back reference", /* REG_ESUBREG */
821 "Unmatched [ or [^", /* REG_EBRACK */
822 "Unmatched ( or \\(", /* REG_EPAREN */
823 "Unmatched \\{", /* REG_EBRACE */
824 "Invalid content of \\{\\}", /* REG_BADBR */
825 "Invalid range end", /* REG_ERANGE */
826 "Memory exhausted", /* REG_ESPACE */
827 "Invalid preceding regular expression", /* REG_BADRPT */
828 "Premature end of regular expression", /* REG_EEND */
829 "Regular expression too big", /* REG_ESIZE */
830 "Unmatched ) or \\)", /* REG_ERPAREN */
831 };
832
833 /* Subroutine declarations and macros for regex_compile. */
834
835 static void store_op1(), store_op2();
836 static void insert_op1(), insert_op2();
837 static boolean at_begline_loc_p(), at_endline_loc_p();
838 static boolean group_in_compile_stack();
839 static reg_errcode_t compile_range();
840
841 /* Fetch the next character in the uncompiled pattern---translating it
842 * if necessary. Also cast from a signed character in the constant
843 * string passed to us by the user to an unsigned char that we can use
844 * as an array index (in, e.g., `translate'). */
845 #define PATFETCH(c) \
846 do {if (p == pend) return REG_EEND; \
847 c = (unsigned char) *p++; \
848 if (translate) c = translate[c]; \
849 } while (0)
850
851 /* Fetch the next character in the uncompiled pattern, with no
852 * translation. */
853 #define PATFETCH_RAW(c) \
854 do {if (p == pend) return REG_EEND; \
855 c = (unsigned char) *p++; \
856 } while (0)
857
858 /* Go backwards one character in the pattern. */
859 #define PATUNFETCH p--
860
861
862 /* If `translate' is non-null, return translate[D], else just D. We
863 * cast the subscript to translate because some data is declared as
864 * `char *', to avoid warnings when a string constant is passed. But
865 * when we use a character as a subscript we must make it unsigned. */
866 #define TRANSLATE(d) (translate ? translate[(unsigned char) (d)] : (d))
867
868
869 /* Macros for outputting the compiled pattern into `buffer'. */
870
871 /* If the buffer isn't allocated when it comes in, use this. */
872 #define INIT_BUF_SIZE 32
873
874 /* Make sure we have at least N more bytes of space in buffer. */
875 #define GET_BUFFER_SPACE(n) \
876 while (b - bufp->buffer + (n) > bufp->allocated) \
877 EXTEND_BUFFER ()
878
879 /* Make sure we have one more byte of buffer space and then add C to it. */
880 #define BUF_PUSH(c) \
881 do { \
882 GET_BUFFER_SPACE (1); \
883 *b++ = (unsigned char) (c); \
884 } while (0)
885
886
887 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
888 #define BUF_PUSH_2(c1, c2) \
889 do { \
890 GET_BUFFER_SPACE (2); \
891 *b++ = (unsigned char) (c1); \
892 *b++ = (unsigned char) (c2); \
893 } while (0)
894
895
896 /* As with BUF_PUSH_2, except for three bytes. */
897 #define BUF_PUSH_3(c1, c2, c3) \
898 do { \
899 GET_BUFFER_SPACE (3); \
900 *b++ = (unsigned char) (c1); \
901 *b++ = (unsigned char) (c2); \
902 *b++ = (unsigned char) (c3); \
903 } while (0)
904
905
906 /* Store a jump with opcode OP at LOC to location TO. We store a
907 * relative address offset by the three bytes the jump itself occupies. */
908 #define STORE_JUMP(op, loc, to) \
909 store_op1 (op, loc, (to) - (loc) - 3)
910
911 /* Likewise, for a two-argument jump. */
912 #define STORE_JUMP2(op, loc, to, arg) \
913 store_op2 (op, loc, (to) - (loc) - 3, arg)
914
915 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
916 #define INSERT_JUMP(op, loc, to) \
917 insert_op1 (op, loc, (to) - (loc) - 3, b)
918
919 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
920 #define INSERT_JUMP2(op, loc, to, arg) \
921 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
922
923
924 /* This is not an arbitrary limit: the arguments which represent offsets
925 * into the pattern are two bytes long. So if 2^16 bytes turns out to
926 * be too small, many things would have to change. */
927 #define MAX_BUF_SIZE (1L << 16)
928
929
930 /* Extend the buffer by twice its current size via realloc and
931 * reset the pointers that pointed into the old block to point to the
932 * correct places in the new one. If extending the buffer results in it
933 * being larger than MAX_BUF_SIZE, then flag memory exhausted. */
934 #define EXTEND_BUFFER() \
935 do { \
936 unsigned char *old_buffer = bufp->buffer; \
937 if (bufp->allocated == MAX_BUF_SIZE) \
938 return REG_ESIZE; \
939 bufp->allocated <<= 1; \
940 if (bufp->allocated > MAX_BUF_SIZE) \
941 bufp->allocated = MAX_BUF_SIZE; \
942 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
943 if (bufp->buffer == NULL) \
944 return REG_ESPACE; \
945 /* If the buffer moved, move all the pointers into it. */ \
946 if (old_buffer != bufp->buffer) \
947 { \
948 b = (b - old_buffer) + bufp->buffer; \
949 begalt = (begalt - old_buffer) + bufp->buffer; \
950 if (fixup_alt_jump) \
951 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
952 if (laststart) \
953 laststart = (laststart - old_buffer) + bufp->buffer; \
954 if (pending_exact) \
955 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
956 } \
957 } while (0)
958
959
960 /* Since we have one byte reserved for the register number argument to
961 * {start,stop}_memory, the maximum number of groups we can report
962 * things about is what fits in that byte. */
963 #define MAX_REGNUM 255
964
965 /* But patterns can have more than `MAX_REGNUM' registers. We just
966 * ignore the excess. */
967 typedef unsigned regnum_t;
968
969
970 /* Macros for the compile stack. */
971
972 /* Since offsets can go either forwards or backwards, this type needs to
973 * be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
974 typedef int pattern_offset_t;
975
976 typedef struct {
977 pattern_offset_t begalt_offset;
978 pattern_offset_t fixup_alt_jump;
979 pattern_offset_t inner_group_offset;
980 pattern_offset_t laststart_offset;
981 regnum_t regnum;
982 } compile_stack_elt_t;
983
984
985 typedef struct {
986 compile_stack_elt_t *stack;
987 unsigned size;
988 unsigned avail; /* Offset of next open position. */
989 } compile_stack_type;
990
991
992 #define INIT_COMPILE_STACK_SIZE 32
993
994 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
995 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
996
997 /* The next available element. */
998 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
999
1000
1001 /* Set the bit for character C in a list. */
1002 #define SET_LIST_BIT(c) \
1003 (b[((unsigned char) (c)) / BYTEWIDTH] \
1004 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1005
1006
1007 /* Get the next unsigned number in the uncompiled pattern. */
1008 #define GET_UNSIGNED_NUMBER(num) \
1009 { if (p != pend) \
1010 { \
1011 PATFETCH (c); \
1012 while (ISDIGIT (c)) \
1013 { \
1014 if (num < 0) \
1015 num = 0; \
1016 num = num * 10 + c - '0'; \
1017 if (p == pend) \
1018 break; \
1019 PATFETCH (c); \
1020 } \
1021 } \
1022 }
1023
1024 #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1025
1026 #define IS_CHAR_CLASS(string) \
1027 (STREQ (string, "alpha") || STREQ (string, "upper") \
1028 || STREQ (string, "lower") || STREQ (string, "digit") \
1029 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1030 || STREQ (string, "space") || STREQ (string, "print") \
1031 || STREQ (string, "punct") || STREQ (string, "graph") \
1032 || STREQ (string, "cntrl") || STREQ (string, "blank"))
1033
1034 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1035 * Returns one of error codes defined in `regex.h', or zero for success.
1036 *
1037 * Assumes the `allocated' (and perhaps `buffer') and `translate'
1038 * fields are set in BUFP on entry.
1039 *
1040 * If it succeeds, results are put in BUFP (if it returns an error, the
1041 * contents of BUFP are undefined):
1042 * `buffer' is the compiled pattern;
1043 * `syntax' is set to SYNTAX;
1044 * `used' is set to the length of the compiled pattern;
1045 * `fastmap_accurate' is zero;
1046 * `re_nsub' is the number of subexpressions in PATTERN;
1047 * `not_bol' and `not_eol' are zero;
1048 *
1049 * The `fastmap' and `newline_anchor' fields are neither
1050 * examined nor set. */
1051
1052 static reg_errcode_t
regex_compile(pattern,size,syntax,bufp)1053 regex_compile(pattern, size, syntax, bufp)
1054 const char *pattern;
1055 int size;
1056 reg_syntax_t syntax;
1057 struct re_pattern_buffer *bufp;
1058 {
1059 /* We fetch characters from PATTERN here. Even though PATTERN is
1060 * `char *' (i.e., signed), we declare these variables as unsigned, so
1061 * they can be reliably used as array indices. */
1062 register unsigned char c, c1;
1063
1064 /* A random tempory spot in PATTERN. */
1065 const char *p1;
1066
1067 /* Points to the end of the buffer, where we should append. */
1068 register unsigned char *b;
1069
1070 /* Keeps track of unclosed groups. */
1071 compile_stack_type compile_stack;
1072
1073 /* Points to the current (ending) position in the pattern. */
1074 const char *p = pattern;
1075 const char *pend = pattern + size;
1076
1077 /* How to translate the characters in the pattern. */
1078 char *translate = bufp->translate;
1079
1080 /* Address of the count-byte of the most recently inserted `exactn'
1081 * command. This makes it possible to tell if a new exact-match
1082 * character can be added to that command or if the character requires
1083 * a new `exactn' command. */
1084 unsigned char *pending_exact = 0;
1085
1086 /* Address of start of the most recently finished expression.
1087 * This tells, e.g., postfix * where to find the start of its
1088 * operand. Reset at the beginning of groups and alternatives. */
1089 unsigned char *laststart = 0;
1090
1091 /* Address of beginning of regexp, or inside of last group. */
1092 unsigned char *begalt;
1093
1094 /* Place in the uncompiled pattern (i.e., the {) to
1095 * which to go back if the interval is invalid. */
1096 const char *beg_interval;
1097
1098 /* Address of the place where a forward jump should go to the end of
1099 * the containing expression. Each alternative of an `or' -- except the
1100 * last -- ends with a forward jump of this sort. */
1101 unsigned char *fixup_alt_jump = 0;
1102
1103 /* Counts open-groups as they are encountered. Remembered for the
1104 * matching close-group on the compile stack, so the same register
1105 * number is put in the stop_memory as the start_memory. */
1106 regnum_t regnum = 0;
1107
1108 #ifdef DEBUG
1109 DEBUG_PRINT1("\nCompiling pattern: ");
1110 if (debug) {
1111 unsigned debug_count;
1112
1113 for (debug_count = 0; debug_count < size; debug_count++)
1114 printchar(pattern[debug_count]);
1115 putchar('\n');
1116 }
1117 #endif /* DEBUG */
1118
1119 /* Initialize the compile stack. */
1120 compile_stack.stack = TALLOC(INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
1121 if (compile_stack.stack == NULL)
1122 return REG_ESPACE;
1123
1124 compile_stack.size = INIT_COMPILE_STACK_SIZE;
1125 compile_stack.avail = 0;
1126
1127 /* Initialize the pattern buffer. */
1128 bufp->syntax = syntax;
1129 bufp->fastmap_accurate = 0;
1130 bufp->not_bol = bufp->not_eol = 0;
1131
1132 /* Set `used' to zero, so that if we return an error, the pattern
1133 * printer (for debugging) will think there's no pattern. We reset it
1134 * at the end. */
1135 bufp->used = 0;
1136
1137 /* Always count groups, whether or not bufp->no_sub is set. */
1138 bufp->re_nsub = 0;
1139
1140 #if !defined (emacs) && !defined (SYNTAX_TABLE)
1141 /* Initialize the syntax table. */
1142 init_syntax_once();
1143 #endif
1144
1145 if (bufp->allocated == 0) {
1146 if (bufp->buffer) { /* If zero allocated, but buffer is non-null, try to realloc
1147 * enough space. This loses if buffer's address is bogus, but
1148 * that is the user's responsibility. */
1149 RETALLOC(bufp->buffer, INIT_BUF_SIZE, unsigned char);
1150 } else { /* Caller did not allocate a buffer. Do it for them. */
1151 bufp->buffer = TALLOC(INIT_BUF_SIZE, unsigned char);
1152 }
1153 if (!bufp->buffer) {
1154 free(compile_stack.stack);
1155 return REG_ESPACE;
1156 }
1157
1158 bufp->allocated = INIT_BUF_SIZE;
1159 }
1160 begalt = b = bufp->buffer;
1161
1162 /* Loop through the uncompiled pattern until we're at the end. */
1163 while (p != pend) {
1164 PATFETCH(c);
1165
1166 switch (c) {
1167 case '^':
1168 {
1169 if ( /* If at start of pattern, it's an operator. */
1170 p == pattern + 1
1171 /* If context independent, it's an operator. */
1172 || syntax & RE_CONTEXT_INDEP_ANCHORS
1173 /* Otherwise, depends on what's come before. */
1174 || at_begline_loc_p(pattern, p, syntax))
1175 BUF_PUSH(begline);
1176 else
1177 goto normal_char;
1178 }
1179 break;
1180
1181
1182 case '$':
1183 {
1184 if ( /* If at end of pattern, it's an operator. */
1185 p == pend
1186 /* If context independent, it's an operator. */
1187 || syntax & RE_CONTEXT_INDEP_ANCHORS
1188 /* Otherwise, depends on what's next. */
1189 || at_endline_loc_p(p, pend, syntax))
1190 BUF_PUSH(endline);
1191 else
1192 goto normal_char;
1193 }
1194 break;
1195
1196
1197 case '+':
1198 case '?':
1199 if ((syntax & RE_BK_PLUS_QM)
1200 || (syntax & RE_LIMITED_OPS))
1201 goto normal_char;
1202 handle_plus:
1203 case '*':
1204 /* If there is no previous pattern... */
1205 if (!laststart) {
1206 if (syntax & RE_CONTEXT_INVALID_OPS)
1207 return REG_BADRPT;
1208 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
1209 goto normal_char;
1210 } {
1211 /* Are we optimizing this jump? */
1212 boolean keep_string_p = false;
1213
1214 /* 1 means zero (many) matches is allowed. */
1215 char zero_times_ok = 0, many_times_ok = 0;
1216
1217 /* If there is a sequence of repetition chars, collapse it
1218 * down to just one (the right one). We can't combine
1219 * interval operators with these because of, e.g., `a{2}*',
1220 * which should only match an even number of `a's. */
1221
1222 for (;;) {
1223 zero_times_ok |= c != '+';
1224 many_times_ok |= c != '?';
1225
1226 if (p == pend)
1227 break;
1228
1229 PATFETCH(c);
1230
1231 if (c == '*'
1232 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')));
1233
1234 else if (syntax & RE_BK_PLUS_QM && c == '\\') {
1235 if (p == pend)
1236 return REG_EESCAPE;
1237
1238 PATFETCH(c1);
1239 if (!(c1 == '+' || c1 == '?')) {
1240 PATUNFETCH;
1241 PATUNFETCH;
1242 break;
1243 }
1244 c = c1;
1245 } else {
1246 PATUNFETCH;
1247 break;
1248 }
1249
1250 /* If we get here, we found another repeat character. */
1251 }
1252
1253 /* Star, etc. applied to an empty pattern is equivalent
1254 * to an empty pattern. */
1255 if (!laststart)
1256 break;
1257
1258 /* Now we know whether or not zero matches is allowed
1259 * and also whether or not two or more matches is allowed. */
1260 if (many_times_ok) { /* More than one repetition is allowed, so put in at the
1261 * end a backward relative jump from `b' to before the next
1262 * jump we're going to put in below (which jumps from
1263 * laststart to after this jump).
1264 *
1265 * But if we are at the `*' in the exact sequence `.*\n',
1266 * insert an unconditional jump backwards to the .,
1267 * instead of the beginning of the loop. This way we only
1268 * push a failure point once, instead of every time
1269 * through the loop. */
1270 assert(p - 1 > pattern);
1271
1272 /* Allocate the space for the jump. */
1273 GET_BUFFER_SPACE(3);
1274
1275 /* We know we are not at the first character of the pattern,
1276 * because laststart was nonzero. And we've already
1277 * incremented `p', by the way, to be the character after
1278 * the `*'. Do we have to do something analogous here
1279 * for null bytes, because of RE_DOT_NOT_NULL? */
1280 if (TRANSLATE(*(p - 2)) == TRANSLATE('.')
1281 && zero_times_ok
1282 && p < pend && TRANSLATE(*p) == TRANSLATE('\n')
1283 && !(syntax & RE_DOT_NEWLINE)) { /* We have .*\n. */
1284 STORE_JUMP(jump, b, laststart);
1285 keep_string_p = true;
1286 } else
1287 /* Anything else. */
1288 STORE_JUMP(maybe_pop_jump, b, laststart - 3);
1289
1290 /* We've added more stuff to the buffer. */
1291 b += 3;
1292 }
1293 /* On failure, jump from laststart to b + 3, which will be the
1294 * end of the buffer after this jump is inserted. */
1295 GET_BUFFER_SPACE(3);
1296 INSERT_JUMP(keep_string_p ? on_failure_keep_string_jump
1297 : on_failure_jump,
1298 laststart, b + 3);
1299 pending_exact = 0;
1300 b += 3;
1301
1302 if (!zero_times_ok) {
1303 /* At least one repetition is required, so insert a
1304 * `dummy_failure_jump' before the initial
1305 * `on_failure_jump' instruction of the loop. This
1306 * effects a skip over that instruction the first time
1307 * we hit that loop. */
1308 GET_BUFFER_SPACE(3);
1309 INSERT_JUMP(dummy_failure_jump, laststart, laststart + 6);
1310 b += 3;
1311 }
1312 }
1313 break;
1314
1315
1316 case '.':
1317 laststart = b;
1318 BUF_PUSH(anychar);
1319 break;
1320
1321
1322 case '[':
1323 {
1324 boolean had_char_class = false;
1325
1326 if (p == pend)
1327 return REG_EBRACK;
1328
1329 /* Ensure that we have enough space to push a charset: the
1330 * opcode, the length count, and the bitset; 34 bytes in all. */
1331 GET_BUFFER_SPACE(34);
1332
1333 laststart = b;
1334
1335 /* We test `*p == '^' twice, instead of using an if
1336 * statement, so we only need one BUF_PUSH. */
1337 BUF_PUSH(*p == '^' ? charset_not : charset);
1338 if (*p == '^')
1339 p++;
1340
1341 /* Remember the first position in the bracket expression. */
1342 p1 = p;
1343
1344 /* Push the number of bytes in the bitmap. */
1345 BUF_PUSH((1 << BYTEWIDTH) / BYTEWIDTH);
1346
1347 /* Clear the whole map. */
1348 bzero(b, (1 << BYTEWIDTH) / BYTEWIDTH);
1349
1350 /* charset_not matches newline according to a syntax bit. */
1351 if ((re_opcode_t) b[-2] == charset_not
1352 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
1353 SET_LIST_BIT('\n');
1354
1355 /* Read in characters and ranges, setting map bits. */
1356 for (;;) {
1357 if (p == pend)
1358 return REG_EBRACK;
1359
1360 PATFETCH(c);
1361
1362 /* \ might escape characters inside [...] and [^...]. */
1363 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\') {
1364 if (p == pend)
1365 return REG_EESCAPE;
1366
1367 PATFETCH(c1);
1368 SET_LIST_BIT(c1);
1369 continue;
1370 }
1371 /* Could be the end of the bracket expression. If it's
1372 * not (i.e., when the bracket expression is `[]' so
1373 * far), the ']' character bit gets set way below. */
1374 if (c == ']' && p != p1 + 1)
1375 break;
1376
1377 /* Look ahead to see if it's a range when the last thing
1378 * was a character class. */
1379 if (had_char_class && c == '-' && *p != ']')
1380 return REG_ERANGE;
1381
1382 /* Look ahead to see if it's a range when the last thing
1383 * was a character: if this is a hyphen not at the
1384 * beginning or the end of a list, then it's the range
1385 * operator. */
1386 if (c == '-'
1387 && !(p - 2 >= pattern && p[-2] == '[')
1388 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
1389 && *p != ']') {
1390 reg_errcode_t ret
1391 = compile_range(&p, pend, translate, syntax, b);
1392 if (ret != REG_NOERROR)
1393 return ret;
1394 } else if (p[0] == '-' && p[1] != ']') { /* This handles ranges made up of characters only. */
1395 reg_errcode_t ret;
1396
1397 /* Move past the `-'. */
1398 PATFETCH(c1);
1399
1400 ret = compile_range(&p, pend, translate, syntax, b);
1401 if (ret != REG_NOERROR)
1402 return ret;
1403 }
1404 /* See if we're at the beginning of a possible character
1405 * class. */
1406
1407 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':') { /* Leave room for the null. */
1408 char str[CHAR_CLASS_MAX_LENGTH + 1];
1409
1410 PATFETCH(c);
1411 c1 = 0;
1412
1413 /* If pattern is `[[:'. */
1414 if (p == pend)
1415 return REG_EBRACK;
1416
1417 for (;;) {
1418 PATFETCH(c);
1419 if (c == ':' || c == ']' || p == pend
1420 || c1 == CHAR_CLASS_MAX_LENGTH)
1421 break;
1422 str[c1++] = c;
1423 }
1424 str[c1] = '\0';
1425
1426 /* If isn't a word bracketed by `[:' and:`]':
1427 * undo the ending character, the letters, and leave
1428 * the leading `:' and `[' (but set bits for them). */
1429 if (c == ':' && *p == ']') {
1430 int ch;
1431 boolean is_alnum = STREQ(str, "alnum");
1432 boolean is_alpha = STREQ(str, "alpha");
1433 boolean is_blank = STREQ(str, "blank");
1434 boolean is_cntrl = STREQ(str, "cntrl");
1435 boolean is_digit = STREQ(str, "digit");
1436 boolean is_graph = STREQ(str, "graph");
1437 boolean is_lower = STREQ(str, "lower");
1438 boolean is_print = STREQ(str, "print");
1439 boolean is_punct = STREQ(str, "punct");
1440 boolean is_space = STREQ(str, "space");
1441 boolean is_upper = STREQ(str, "upper");
1442 boolean is_xdigit = STREQ(str, "xdigit");
1443
1444 if (!IS_CHAR_CLASS(str))
1445 return REG_ECTYPE;
1446
1447 /* Throw away the ] at the end of the character
1448 * class. */
1449 PATFETCH(c);
1450
1451 if (p == pend)
1452 return REG_EBRACK;
1453
1454 for (ch = 0; ch < 1 << BYTEWIDTH; ch++) {
1455 if ((is_alnum && ISALNUM(ch))
1456 || (is_alpha && ISALPHA(ch))
1457 || (is_blank && ISBLANK(ch))
1458 || (is_cntrl && ISCNTRL(ch))
1459 || (is_digit && ISDIGIT(ch))
1460 || (is_graph && ISGRAPH(ch))
1461 || (is_lower && ISLOWER(ch))
1462 || (is_print && ISPRINT(ch))
1463 || (is_punct && ISPUNCT(ch))
1464 || (is_space && ISSPACE(ch))
1465 || (is_upper && ISUPPER(ch))
1466 || (is_xdigit && ISXDIGIT(ch)))
1467 SET_LIST_BIT(ch);
1468 }
1469 had_char_class = true;
1470 } else {
1471 c1++;
1472 while (c1--)
1473 PATUNFETCH;
1474 SET_LIST_BIT('[');
1475 SET_LIST_BIT(':');
1476 had_char_class = false;
1477 }
1478 } else {
1479 had_char_class = false;
1480 SET_LIST_BIT(c);
1481 }
1482 }
1483
1484 /* Discard any (non)matching list bytes that are all 0 at the
1485 * end of the map. Decrease the map-length byte too. */
1486 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
1487 b[-1]--;
1488 b += b[-1];
1489 }
1490 break;
1491
1492
1493 case '(':
1494 if (syntax & RE_NO_BK_PARENS)
1495 goto handle_open;
1496 else
1497 goto normal_char;
1498
1499
1500 case ')':
1501 if (syntax & RE_NO_BK_PARENS)
1502 goto handle_close;
1503 else
1504 goto normal_char;
1505
1506
1507 case '\n':
1508 if (syntax & RE_NEWLINE_ALT)
1509 goto handle_alt;
1510 else
1511 goto normal_char;
1512
1513
1514 case '|':
1515 if (syntax & RE_NO_BK_VBAR)
1516 goto handle_alt;
1517 else
1518 goto normal_char;
1519
1520
1521 case '{':
1522 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
1523 goto handle_interval;
1524 else
1525 goto normal_char;
1526
1527
1528 case '\\':
1529 if (p == pend)
1530 return REG_EESCAPE;
1531
1532 /* Do not translate the character after the \, so that we can
1533 * distinguish, e.g., \B from \b, even if we normally would
1534 * translate, e.g., B to b. */
1535 PATFETCH_RAW(c);
1536
1537 switch (c) {
1538 case '(':
1539 if (syntax & RE_NO_BK_PARENS)
1540 goto normal_backslash;
1541
1542 handle_open:
1543 bufp->re_nsub++;
1544 regnum++;
1545
1546 if (COMPILE_STACK_FULL) {
1547 RETALLOC(compile_stack.stack, compile_stack.size << 1,
1548 compile_stack_elt_t);
1549 if (compile_stack.stack == NULL)
1550 return REG_ESPACE;
1551
1552 compile_stack.size <<= 1;
1553 }
1554 /* These are the values to restore when we hit end of this
1555 * group. They are all relative offsets, so that if the
1556 * whole pattern moves because of realloc, they will still
1557 * be valid. */
1558 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
1559 COMPILE_STACK_TOP.fixup_alt_jump
1560 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
1561 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
1562 COMPILE_STACK_TOP.regnum = regnum;
1563
1564 /* We will eventually replace the 0 with the number of
1565 * groups inner to this one. But do not push a
1566 * start_memory for groups beyond the last one we can
1567 * represent in the compiled pattern. */
1568 if (regnum <= MAX_REGNUM) {
1569 COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
1570 BUF_PUSH_3(start_memory, regnum, 0);
1571 }
1572 compile_stack.avail++;
1573
1574 fixup_alt_jump = 0;
1575 laststart = 0;
1576 begalt = b;
1577 /* If we've reached MAX_REGNUM groups, then this open
1578 * won't actually generate any code, so we'll have to
1579 * clear pending_exact explicitly. */
1580 pending_exact = 0;
1581 break;
1582
1583
1584 case ')':
1585 if (syntax & RE_NO_BK_PARENS)
1586 goto normal_backslash;
1587
1588 if (COMPILE_STACK_EMPTY)
1589 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
1590 goto normal_backslash;
1591 else
1592 return REG_ERPAREN;
1593
1594 handle_close:
1595 if (fixup_alt_jump) { /* Push a dummy failure point at the end of the
1596 * alternative for a possible future
1597 * `pop_failure_jump' to pop. See comments at
1598 * `push_dummy_failure' in `re_match_2'. */
1599 BUF_PUSH(push_dummy_failure);
1600
1601 /* We allocated space for this jump when we assigned
1602 * to `fixup_alt_jump', in the `handle_alt' case below. */
1603 STORE_JUMP(jump_past_alt, fixup_alt_jump, b - 1);
1604 }
1605 /* See similar code for backslashed left paren above. */
1606 if (COMPILE_STACK_EMPTY)
1607 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
1608 goto normal_char;
1609 else
1610 return REG_ERPAREN;
1611
1612 /* Since we just checked for an empty stack above, this
1613 * ``can't happen''. */
1614 assert(compile_stack.avail != 0);
1615 {
1616 /* We don't just want to restore into `regnum', because
1617 * later groups should continue to be numbered higher,
1618 * as in `(ab)c(de)' -- the second group is #2. */
1619 regnum_t this_group_regnum;
1620
1621 compile_stack.avail--;
1622 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
1623 fixup_alt_jump
1624 = COMPILE_STACK_TOP.fixup_alt_jump
1625 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
1626 : 0;
1627 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
1628 this_group_regnum = COMPILE_STACK_TOP.regnum;
1629 /* If we've reached MAX_REGNUM groups, then this open
1630 * won't actually generate any code, so we'll have to
1631 * clear pending_exact explicitly. */
1632 pending_exact = 0;
1633
1634 /* We're at the end of the group, so now we know how many
1635 * groups were inside this one. */
1636 if (this_group_regnum <= MAX_REGNUM) {
1637 unsigned char *inner_group_loc
1638 = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
1639
1640 *inner_group_loc = regnum - this_group_regnum;
1641 BUF_PUSH_3(stop_memory, this_group_regnum,
1642 regnum - this_group_regnum);
1643 }
1644 }
1645 break;
1646
1647
1648 case '|': /* `\|'. */
1649 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
1650 goto normal_backslash;
1651 handle_alt:
1652 if (syntax & RE_LIMITED_OPS)
1653 goto normal_char;
1654
1655 /* Insert before the previous alternative a jump which
1656 * jumps to this alternative if the former fails. */
1657 GET_BUFFER_SPACE(3);
1658 INSERT_JUMP(on_failure_jump, begalt, b + 6);
1659 pending_exact = 0;
1660 b += 3;
1661
1662 /* The alternative before this one has a jump after it
1663 * which gets executed if it gets matched. Adjust that
1664 * jump so it will jump to this alternative's analogous
1665 * jump (put in below, which in turn will jump to the next
1666 * (if any) alternative's such jump, etc.). The last such
1667 * jump jumps to the correct final destination. A picture:
1668 * _____ _____
1669 * | | | |
1670 * | v | v
1671 * a | b | c
1672 *
1673 * If we are at `b', then fixup_alt_jump right now points to a
1674 * three-byte space after `a'. We'll put in the jump, set
1675 * fixup_alt_jump to right after `b', and leave behind three
1676 * bytes which we'll fill in when we get to after `c'. */
1677
1678 if (fixup_alt_jump)
1679 STORE_JUMP(jump_past_alt, fixup_alt_jump, b);
1680
1681 /* Mark and leave space for a jump after this alternative,
1682 * to be filled in later either by next alternative or
1683 * when know we're at the end of a series of alternatives. */
1684 fixup_alt_jump = b;
1685 GET_BUFFER_SPACE(3);
1686 b += 3;
1687
1688 laststart = 0;
1689 begalt = b;
1690 break;
1691
1692
1693 case '{':
1694 /* If \{ is a literal. */
1695 if (!(syntax & RE_INTERVALS)
1696 /* If we're at `\{' and it's not the open-interval
1697 * operator. */
1698 || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
1699 || (p - 2 == pattern && p == pend))
1700 goto normal_backslash;
1701
1702 handle_interval:
1703 {
1704 /* If got here, then the syntax allows intervals. */
1705
1706 /* At least (most) this many matches must be made. */
1707 int lower_bound = -1, upper_bound = -1;
1708
1709 beg_interval = p - 1;
1710
1711 if (p == pend) {
1712 if (syntax & RE_NO_BK_BRACES)
1713 goto unfetch_interval;
1714 else
1715 return REG_EBRACE;
1716 }
1717 GET_UNSIGNED_NUMBER(lower_bound);
1718
1719 if (c == ',') {
1720 GET_UNSIGNED_NUMBER(upper_bound);
1721 if (upper_bound < 0)
1722 upper_bound = RE_DUP_MAX;
1723 } else
1724 /* Interval such as `{1}' => match exactly once. */
1725 upper_bound = lower_bound;
1726
1727 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
1728 || lower_bound > upper_bound) {
1729 if (syntax & RE_NO_BK_BRACES)
1730 goto unfetch_interval;
1731 else
1732 return REG_BADBR;
1733 }
1734 if (!(syntax & RE_NO_BK_BRACES)) {
1735 if (c != '\\')
1736 return REG_EBRACE;
1737
1738 PATFETCH(c);
1739 }
1740 if (c != '}') {
1741 if (syntax & RE_NO_BK_BRACES)
1742 goto unfetch_interval;
1743 else
1744 return REG_BADBR;
1745 }
1746 /* We just parsed a valid interval. */
1747
1748 /* If it's invalid to have no preceding re. */
1749 if (!laststart) {
1750 if (syntax & RE_CONTEXT_INVALID_OPS)
1751 return REG_BADRPT;
1752 else if (syntax & RE_CONTEXT_INDEP_OPS)
1753 laststart = b;
1754 else
1755 goto unfetch_interval;
1756 }
1757 /* If the upper bound is zero, don't want to succeed at
1758 * all; jump from `laststart' to `b + 3', which will be
1759 * the end of the buffer after we insert the jump. */
1760 if (upper_bound == 0) {
1761 GET_BUFFER_SPACE(3);
1762 INSERT_JUMP(jump, laststart, b + 3);
1763 b += 3;
1764 }
1765 /* Otherwise, we have a nontrivial interval. When
1766 * we're all done, the pattern will look like:
1767 * set_number_at <jump count> <upper bound>
1768 * set_number_at <succeed_n count> <lower bound>
1769 * succeed_n <after jump addr> <succed_n count>
1770 * <body of loop>
1771 * jump_n <succeed_n addr> <jump count>
1772 * (The upper bound and `jump_n' are omitted if
1773 * `upper_bound' is 1, though.) */
1774 else { /* If the upper bound is > 1, we need to insert
1775 * more at the end of the loop. */
1776 unsigned nbytes = 10 + (upper_bound > 1) * 10;
1777
1778 GET_BUFFER_SPACE(nbytes);
1779
1780 /* Initialize lower bound of the `succeed_n', even
1781 * though it will be set during matching by its
1782 * attendant `set_number_at' (inserted next),
1783 * because `re_compile_fastmap' needs to know.
1784 * Jump to the `jump_n' we might insert below. */
1785 INSERT_JUMP2(succeed_n, laststart,
1786 b + 5 + (upper_bound > 1) * 5,
1787 lower_bound);
1788 b += 5;
1789
1790 /* Code to initialize the lower bound. Insert
1791 * before the `succeed_n'. The `5' is the last two
1792 * bytes of this `set_number_at', plus 3 bytes of
1793 * the following `succeed_n'. */
1794 insert_op2(set_number_at, laststart, 5, lower_bound, b);
1795 b += 5;
1796
1797 if (upper_bound > 1) { /* More than one repetition is allowed, so
1798 * append a backward jump to the `succeed_n'
1799 * that starts this interval.
1800 *
1801 * When we've reached this during matching,
1802 * we'll have matched the interval once, so
1803 * jump back only `upper_bound - 1' times. */
1804 STORE_JUMP2(jump_n, b, laststart + 5,
1805 upper_bound - 1);
1806 b += 5;
1807
1808 /* The location we want to set is the second
1809 * parameter of the `jump_n'; that is `b-2' as
1810 * an absolute address. `laststart' will be
1811 * the `set_number_at' we're about to insert;
1812 * `laststart+3' the number to set, the source
1813 * for the relative address. But we are
1814 * inserting into the middle of the pattern --
1815 * so everything is getting moved up by 5.
1816 * Conclusion: (b - 2) - (laststart + 3) + 5,
1817 * i.e., b - laststart.
1818 *
1819 * We insert this at the beginning of the loop
1820 * so that if we fail during matching, we'll
1821 * reinitialize the bounds. */
1822 insert_op2(set_number_at, laststart, b - laststart,
1823 upper_bound - 1, b);
1824 b += 5;
1825 }
1826 }
1827 pending_exact = 0;
1828 beg_interval = NULL;
1829 }
1830 break;
1831
1832 unfetch_interval:
1833 /* If an invalid interval, match the characters as literals. */
1834 assert(beg_interval);
1835 p = beg_interval;
1836 beg_interval = NULL;
1837
1838 /* normal_char and normal_backslash need `c'. */
1839 PATFETCH(c);
1840
1841 if (!(syntax & RE_NO_BK_BRACES)) {
1842 if (p > pattern && p[-1] == '\\')
1843 goto normal_backslash;
1844 }
1845 goto normal_char;
1846
1847 #ifdef emacs
1848 /* There is no way to specify the before_dot and after_dot
1849 * operators. rms says this is ok. --karl */
1850 case '=':
1851 BUF_PUSH(at_dot);
1852 break;
1853
1854 case 's':
1855 laststart = b;
1856 PATFETCH(c);
1857 BUF_PUSH_2(syntaxspec, syntax_spec_code[c]);
1858 break;
1859
1860 case 'S':
1861 laststart = b;
1862 PATFETCH(c);
1863 BUF_PUSH_2(notsyntaxspec, syntax_spec_code[c]);
1864 break;
1865 #endif /* emacs */
1866
1867
1868 case 'w':
1869 laststart = b;
1870 BUF_PUSH(wordchar);
1871 break;
1872
1873
1874 case 'W':
1875 laststart = b;
1876 BUF_PUSH(notwordchar);
1877 break;
1878
1879
1880 case '<':
1881 BUF_PUSH(wordbeg);
1882 break;
1883
1884 case '>':
1885 BUF_PUSH(wordend);
1886 break;
1887
1888 case 'b':
1889 BUF_PUSH(wordbound);
1890 break;
1891
1892 case 'B':
1893 BUF_PUSH(notwordbound);
1894 break;
1895
1896 case '`':
1897 BUF_PUSH(begbuf);
1898 break;
1899
1900 case '\'':
1901 BUF_PUSH(endbuf);
1902 break;
1903
1904 case '1':
1905 case '2':
1906 case '3':
1907 case '4':
1908 case '5':
1909 case '6':
1910 case '7':
1911 case '8':
1912 case '9':
1913 if (syntax & RE_NO_BK_REFS)
1914 goto normal_char;
1915
1916 c1 = c - '0';
1917
1918 if (c1 > regnum)
1919 return REG_ESUBREG;
1920
1921 /* Can't back reference to a subexpression if inside of it. */
1922 if (group_in_compile_stack(compile_stack, c1))
1923 goto normal_char;
1924
1925 laststart = b;
1926 BUF_PUSH_2(duplicate, c1);
1927 break;
1928
1929
1930 case '+':
1931 case '?':
1932 if (syntax & RE_BK_PLUS_QM)
1933 goto handle_plus;
1934 else
1935 goto normal_backslash;
1936
1937 default:
1938 normal_backslash:
1939 /* You might think it would be useful for \ to mean
1940 * not to translate; but if we don't translate it
1941 * it will never match anything. */
1942 c = TRANSLATE(c);
1943 goto normal_char;
1944 }
1945 break;
1946
1947
1948 default:
1949 /* Expects the character in `c'. */
1950 normal_char:
1951 /* If no exactn currently being built. */
1952 if (!pending_exact
1953
1954 /* If last exactn not at current position. */
1955 || pending_exact + *pending_exact + 1 != b
1956
1957 /* We have only one byte following the exactn for the count. */
1958 || *pending_exact == (1 << BYTEWIDTH) - 1
1959
1960 /* If followed by a repetition operator. */
1961 || *p == '*' || *p == '^'
1962 || ((syntax & RE_BK_PLUS_QM)
1963 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
1964 : (*p == '+' || *p == '?'))
1965 || ((syntax & RE_INTERVALS)
1966 && ((syntax & RE_NO_BK_BRACES)
1967 ? *p == '{'
1968 : (p[0] == '\\' && p[1] == '{')))) {
1969 /* Start building a new exactn. */
1970
1971 laststart = b;
1972
1973 BUF_PUSH_2(exactn, 0);
1974 pending_exact = b - 1;
1975 }
1976 BUF_PUSH(c);
1977 (*pending_exact)++;
1978 break;
1979 } /* switch (c) */
1980 } /* while p != pend */
1981
1982
1983 /* Through the pattern now. */
1984
1985 if (fixup_alt_jump)
1986 STORE_JUMP(jump_past_alt, fixup_alt_jump, b);
1987
1988 if (!COMPILE_STACK_EMPTY)
1989 return REG_EPAREN;
1990
1991 free(compile_stack.stack);
1992
1993 /* We have succeeded; set the length of the buffer. */
1994 bufp->used = b - bufp->buffer;
1995
1996 #ifdef DEBUG
1997 if (debug) {
1998 DEBUG_PRINT1("\nCompiled pattern: ");
1999 print_compiled_pattern(bufp);
2000 }
2001 #endif /* DEBUG */
2002
2003 return REG_NOERROR;
2004 } /* regex_compile */
2005
2006 /* Subroutines for `regex_compile'. */
2007
2008 /* Store OP at LOC followed by two-byte integer parameter ARG. */
2009
2010 static void
store_op1(op,loc,arg)2011 store_op1(op, loc, arg)
2012 re_opcode_t op;
2013 unsigned char *loc;
2014 int arg;
2015 {
2016 *loc = (unsigned char) op;
2017 STORE_NUMBER(loc + 1, arg);
2018 }
2019
2020
2021 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
2022
2023 static void
store_op2(op,loc,arg1,arg2)2024 store_op2(op, loc, arg1, arg2)
2025 re_opcode_t op;
2026 unsigned char *loc;
2027 int arg1, arg2;
2028 {
2029 *loc = (unsigned char) op;
2030 STORE_NUMBER(loc + 1, arg1);
2031 STORE_NUMBER(loc + 3, arg2);
2032 }
2033
2034
2035 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
2036 * for OP followed by two-byte integer parameter ARG. */
2037
2038 static void
insert_op1(op,loc,arg,end)2039 insert_op1(op, loc, arg, end)
2040 re_opcode_t op;
2041 unsigned char *loc;
2042 int arg;
2043 unsigned char *end;
2044 {
2045 register unsigned char *pfrom = end;
2046 register unsigned char *pto = end + 3;
2047
2048 while (pfrom != loc)
2049 *--pto = *--pfrom;
2050
2051 store_op1(op, loc, arg);
2052 }
2053
2054
2055 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
2056
2057 static void
insert_op2(op,loc,arg1,arg2,end)2058 insert_op2(op, loc, arg1, arg2, end)
2059 re_opcode_t op;
2060 unsigned char *loc;
2061 int arg1, arg2;
2062 unsigned char *end;
2063 {
2064 register unsigned char *pfrom = end;
2065 register unsigned char *pto = end + 5;
2066
2067 while (pfrom != loc)
2068 *--pto = *--pfrom;
2069
2070 store_op2(op, loc, arg1, arg2);
2071 }
2072
2073
2074 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
2075 * after an alternative or a begin-subexpression. We assume there is at
2076 * least one character before the ^. */
2077
2078 static boolean
at_begline_loc_p(pattern,p,syntax)2079 at_begline_loc_p(pattern, p, syntax)
2080 const char *pattern, *p;
2081 reg_syntax_t syntax;
2082 {
2083 const char *prev = p - 2;
2084 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
2085
2086 return
2087 /* After a subexpression? */
2088 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
2089 /* After an alternative? */
2090 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
2091 }
2092
2093
2094 /* The dual of at_begline_loc_p. This one is for $. We assume there is
2095 * at least one character after the $, i.e., `P < PEND'. */
2096
2097 static boolean
at_endline_loc_p(p,pend,syntax)2098 at_endline_loc_p(p, pend, syntax)
2099 const char *p, *pend;
2100 int syntax;
2101 {
2102 const char *next = p;
2103 boolean next_backslash = *next == '\\';
2104 const char *next_next = p + 1 < pend ? p + 1 : NULL;
2105
2106 return
2107 /* Before a subexpression? */
2108 (syntax & RE_NO_BK_PARENS ? *next == ')'
2109 : next_backslash && next_next && *next_next == ')')
2110 /* Before an alternative? */
2111 || (syntax & RE_NO_BK_VBAR ? *next == '|'
2112 : next_backslash && next_next && *next_next == '|');
2113 }
2114
2115
2116 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
2117 * false if it's not. */
2118
2119 static boolean
group_in_compile_stack(compile_stack,regnum)2120 group_in_compile_stack(compile_stack, regnum)
2121 compile_stack_type compile_stack;
2122 regnum_t regnum;
2123 {
2124 int this_element;
2125
2126 for (this_element = compile_stack.avail - 1;
2127 this_element >= 0;
2128 this_element--)
2129 if (compile_stack.stack[this_element].regnum == regnum)
2130 return true;
2131
2132 return false;
2133 }
2134
2135
2136 /* Read the ending character of a range (in a bracket expression) from the
2137 * uncompiled pattern *P_PTR (which ends at PEND). We assume the
2138 * starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
2139 * Then we set the translation of all bits between the starting and
2140 * ending characters (inclusive) in the compiled pattern B.
2141 *
2142 * Return an error code.
2143 *
2144 * We use these short variable names so we can use the same macros as
2145 * `regex_compile' itself. */
2146
2147 static reg_errcode_t
compile_range(p_ptr,pend,translate,syntax,b)2148 compile_range(p_ptr, pend, translate, syntax, b)
2149 const char **p_ptr, *pend;
2150 char *translate;
2151 reg_syntax_t syntax;
2152 unsigned char *b;
2153 {
2154 unsigned this_char;
2155
2156 const char *p = *p_ptr;
2157 int range_start, range_end;
2158
2159 if (p == pend)
2160 return REG_ERANGE;
2161
2162 /* Even though the pattern is a signed `char *', we need to fetch
2163 * with unsigned char *'s; if the high bit of the pattern character
2164 * is set, the range endpoints will be negative if we fetch using a
2165 * signed char *.
2166 *
2167 * We also want to fetch the endpoints without translating them; the
2168 * appropriate translation is done in the bit-setting loop below. */
2169 range_start = ((unsigned char *) p)[-2];
2170 range_end = ((unsigned char *) p)[0];
2171
2172 /* Have to increment the pointer into the pattern string, so the
2173 * caller isn't still at the ending character. */
2174 (*p_ptr)++;
2175
2176 /* If the start is after the end, the range is empty. */
2177 if (range_start > range_end)
2178 return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
2179
2180 /* Here we see why `this_char' has to be larger than an `unsigned
2181 * char' -- the range is inclusive, so if `range_end' == 0xff
2182 * (assuming 8-bit characters), we would otherwise go into an infinite
2183 * loop, since all characters <= 0xff. */
2184 for (this_char = range_start; this_char <= range_end; this_char++) {
2185 SET_LIST_BIT(TRANSLATE(this_char));
2186 }
2187
2188 return REG_NOERROR;
2189 }
2190
2191 /* Failure stack declarations and macros; both re_compile_fastmap and
2192 * re_match_2 use a failure stack. These have to be macros because of
2193 * REGEX_ALLOCATE. */
2194
2195
2196 /* Number of failure points for which to initially allocate space
2197 * when matching. If this number is exceeded, we allocate more
2198 * space, so it is not a hard limit. */
2199 #ifndef INIT_FAILURE_ALLOC
2200 #define INIT_FAILURE_ALLOC 5
2201 #endif
2202
2203 /* Roughly the maximum number of failure points on the stack. Would be
2204 * exactly that if always used MAX_FAILURE_SPACE each time we failed.
2205 * This is a variable only so users of regex can assign to it; we never
2206 * change it ourselves. */
2207 int re_max_failures = 2000;
2208
2209 typedef const unsigned char *fail_stack_elt_t;
2210
2211 typedef struct {
2212 fail_stack_elt_t *stack;
2213 unsigned size;
2214 unsigned avail; /* Offset of next open position. */
2215 } fail_stack_type;
2216
2217 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
2218 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
2219 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
2220 #define FAIL_STACK_TOP() (fail_stack.stack[fail_stack.avail])
2221
2222
2223 /* Initialize `fail_stack'. Do `return -2' if the alloc fails. */
2224
2225 #define INIT_FAIL_STACK() \
2226 do { \
2227 fail_stack.stack = (fail_stack_elt_t *) \
2228 REGEX_ALLOCATE (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
2229 \
2230 if (fail_stack.stack == NULL) \
2231 return -2; \
2232 \
2233 fail_stack.size = INIT_FAILURE_ALLOC; \
2234 fail_stack.avail = 0; \
2235 } while (0)
2236
2237
2238 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
2239 *
2240 * Return 1 if succeeds, and 0 if either ran out of memory
2241 * allocating space for it or it was already too large.
2242 *
2243 * REGEX_REALLOCATE requires `destination' be declared. */
2244
2245 #define DOUBLE_FAIL_STACK(fail_stack) \
2246 ((fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS \
2247 ? 0 \
2248 : ((fail_stack).stack = (fail_stack_elt_t *) \
2249 REGEX_REALLOCATE ((fail_stack).stack, \
2250 (fail_stack).size * sizeof (fail_stack_elt_t), \
2251 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
2252 \
2253 (fail_stack).stack == NULL \
2254 ? 0 \
2255 : ((fail_stack).size <<= 1, \
2256 1)))
2257
2258
2259 /* Push PATTERN_OP on FAIL_STACK.
2260 *
2261 * Return 1 if was able to do so and 0 if ran out of memory allocating
2262 * space to do so. */
2263 #define PUSH_PATTERN_OP(pattern_op, fail_stack) \
2264 ((FAIL_STACK_FULL () \
2265 && !DOUBLE_FAIL_STACK (fail_stack)) \
2266 ? 0 \
2267 : ((fail_stack).stack[(fail_stack).avail++] = pattern_op, \
2268 1))
2269
2270 /* This pushes an item onto the failure stack. Must be a four-byte
2271 * value. Assumes the variable `fail_stack'. Probably should only
2272 * be called from within `PUSH_FAILURE_POINT'. */
2273 #define PUSH_FAILURE_ITEM(item) \
2274 fail_stack.stack[fail_stack.avail++] = (fail_stack_elt_t) item
2275
2276 /* The complement operation. Assumes `fail_stack' is nonempty. */
2277 #define POP_FAILURE_ITEM() fail_stack.stack[--fail_stack.avail]
2278
2279 /* Used to omit pushing failure point id's when we're not debugging. */
2280 #ifdef DEBUG
2281 #define DEBUG_PUSH PUSH_FAILURE_ITEM
2282 #define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_ITEM ()
2283 #else
2284 #define DEBUG_PUSH(item)
2285 #define DEBUG_POP(item_addr)
2286 #endif
2287
2288
2289 /* Push the information about the state we will need
2290 * if we ever fail back to it.
2291 *
2292 * Requires variables fail_stack, regstart, regend, reg_info, and
2293 * num_regs be declared. DOUBLE_FAIL_STACK requires `destination' be
2294 * declared.
2295 *
2296 * Does `return FAILURE_CODE' if runs out of memory. */
2297
2298 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
2299 do { \
2300 char *destination; \
2301 /* Must be int, so when we don't save any registers, the arithmetic \
2302 of 0 + -1 isn't done as unsigned. */ \
2303 int this_reg; \
2304 \
2305 DEBUG_STATEMENT (failure_id++); \
2306 DEBUG_STATEMENT (nfailure_points_pushed++); \
2307 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
2308 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
2309 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
2310 \
2311 DEBUG_PRINT2 (" slots needed: %d\n", NUM_FAILURE_ITEMS); \
2312 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
2313 \
2314 /* Ensure we have enough space allocated for what we will push. */ \
2315 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
2316 { \
2317 if (!DOUBLE_FAIL_STACK (fail_stack)) \
2318 return failure_code; \
2319 \
2320 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
2321 (fail_stack).size); \
2322 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
2323 } \
2324 \
2325 /* Push the info, starting with the registers. */ \
2326 DEBUG_PRINT1 ("\n"); \
2327 \
2328 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
2329 this_reg++) \
2330 { \
2331 DEBUG_PRINT2 (" Pushing reg: %d\n", this_reg); \
2332 DEBUG_STATEMENT (num_regs_pushed++); \
2333 \
2334 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
2335 PUSH_FAILURE_ITEM (regstart[this_reg]); \
2336 \
2337 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
2338 PUSH_FAILURE_ITEM (regend[this_reg]); \
2339 \
2340 DEBUG_PRINT2 (" info: 0x%x\n ", reg_info[this_reg]); \
2341 DEBUG_PRINT2 (" match_null=%d", \
2342 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
2343 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
2344 DEBUG_PRINT2 (" matched_something=%d", \
2345 MATCHED_SOMETHING (reg_info[this_reg])); \
2346 DEBUG_PRINT2 (" ever_matched=%d", \
2347 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
2348 DEBUG_PRINT1 ("\n"); \
2349 PUSH_FAILURE_ITEM (reg_info[this_reg].word); \
2350 } \
2351 \
2352 DEBUG_PRINT2 (" Pushing low active reg: %d\n", lowest_active_reg);\
2353 PUSH_FAILURE_ITEM (lowest_active_reg); \
2354 \
2355 DEBUG_PRINT2 (" Pushing high active reg: %d\n", highest_active_reg);\
2356 PUSH_FAILURE_ITEM (highest_active_reg); \
2357 \
2358 DEBUG_PRINT2 (" Pushing pattern 0x%x: ", pattern_place); \
2359 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
2360 PUSH_FAILURE_ITEM (pattern_place); \
2361 \
2362 DEBUG_PRINT2 (" Pushing string 0x%x: `", string_place); \
2363 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
2364 size2); \
2365 DEBUG_PRINT1 ("'\n"); \
2366 PUSH_FAILURE_ITEM (string_place); \
2367 \
2368 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
2369 DEBUG_PUSH (failure_id); \
2370 } while (0)
2371
2372 /* This is the number of items that are pushed and popped on the stack
2373 * for each register. */
2374 #define NUM_REG_ITEMS 3
2375
2376 /* Individual items aside from the registers. */
2377 #ifdef DEBUG
2378 #define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
2379 #else
2380 #define NUM_NONREG_ITEMS 4
2381 #endif
2382
2383 /* We push at most this many items on the stack. */
2384 #define MAX_FAILURE_ITEMS ((num_regs - 1) * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
2385
2386 /* We actually push this many items. */
2387 #define NUM_FAILURE_ITEMS \
2388 ((highest_active_reg - lowest_active_reg + 1) * NUM_REG_ITEMS \
2389 + NUM_NONREG_ITEMS)
2390
2391 /* How many items can still be added to the stack without overflowing it. */
2392 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
2393
2394
2395 /* Pops what PUSH_FAIL_STACK pushes.
2396 *
2397 * We restore into the parameters, all of which should be lvalues:
2398 * STR -- the saved data position.
2399 * PAT -- the saved pattern position.
2400 * LOW_REG, HIGH_REG -- the highest and lowest active registers.
2401 * REGSTART, REGEND -- arrays of string positions.
2402 * REG_INFO -- array of information about each subexpression.
2403 *
2404 * Also assumes the variables `fail_stack' and (if debugging), `bufp',
2405 * `pend', `string1', `size1', `string2', and `size2'. */
2406
2407 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
2408 { \
2409 DEBUG_STATEMENT (fail_stack_elt_t failure_id;) \
2410 int this_reg; \
2411 const unsigned char *string_temp; \
2412 \
2413 assert (!FAIL_STACK_EMPTY ()); \
2414 \
2415 /* Remove failure points and point to how many regs pushed. */ \
2416 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
2417 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
2418 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
2419 \
2420 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
2421 \
2422 DEBUG_POP (&failure_id); \
2423 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
2424 \
2425 /* If the saved string location is NULL, it came from an \
2426 on_failure_keep_string_jump opcode, and we want to throw away the \
2427 saved NULL, thus retaining our current position in the string. */ \
2428 string_temp = POP_FAILURE_ITEM (); \
2429 if (string_temp != NULL) \
2430 str = (const char *) string_temp; \
2431 \
2432 DEBUG_PRINT2 (" Popping string 0x%x: `", str); \
2433 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
2434 DEBUG_PRINT1 ("'\n"); \
2435 \
2436 pat = (unsigned char *) POP_FAILURE_ITEM (); \
2437 DEBUG_PRINT2 (" Popping pattern 0x%x: ", pat); \
2438 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
2439 \
2440 /* Restore register info. */ \
2441 high_reg = (unsigned long) POP_FAILURE_ITEM (); \
2442 DEBUG_PRINT2 (" Popping high active reg: %d\n", high_reg); \
2443 \
2444 low_reg = (unsigned long) POP_FAILURE_ITEM (); \
2445 DEBUG_PRINT2 (" Popping low active reg: %d\n", low_reg); \
2446 \
2447 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
2448 { \
2449 DEBUG_PRINT2 (" Popping reg: %d\n", this_reg); \
2450 \
2451 reg_info[this_reg].word = POP_FAILURE_ITEM (); \
2452 DEBUG_PRINT2 (" info: 0x%x\n", reg_info[this_reg]); \
2453 \
2454 regend[this_reg] = (const char *) POP_FAILURE_ITEM (); \
2455 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
2456 \
2457 regstart[this_reg] = (const char *) POP_FAILURE_ITEM (); \
2458 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
2459 } \
2460 \
2461 DEBUG_STATEMENT (nfailure_points_popped++); \
2462 } /* POP_FAILURE_POINT */
2463
2464 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
2465 * BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
2466 * characters can start a string that matches the pattern. This fastmap
2467 * is used by re_search to skip quickly over impossible starting points.
2468 *
2469 * The caller must supply the address of a (1 << BYTEWIDTH)-byte data
2470 * area as BUFP->fastmap.
2471 *
2472 * We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
2473 * the pattern buffer.
2474 *
2475 * Returns 0 if we succeed, -2 if an internal error. */
2476
2477 int
re_compile_fastmap(bufp)2478 re_compile_fastmap(bufp)
2479 struct re_pattern_buffer *bufp;
2480 {
2481 int j, k;
2482 fail_stack_type fail_stack;
2483 #ifndef REGEX_MALLOC
2484 char *destination;
2485 #endif
2486 /* We don't push any register information onto the failure stack. */
2487 unsigned num_regs = 0;
2488
2489 register char *fastmap = bufp->fastmap;
2490 unsigned char *pattern = bufp->buffer;
2491 unsigned long size = bufp->used;
2492 const unsigned char *p = pattern;
2493 register unsigned char *pend = pattern + size;
2494
2495 /* Assume that each path through the pattern can be null until
2496 * proven otherwise. We set this false at the bottom of switch
2497 * statement, to which we get only if a particular path doesn't
2498 * match the empty string. */
2499 boolean path_can_be_null = true;
2500
2501 /* We aren't doing a `succeed_n' to begin with. */
2502 boolean succeed_n_p = false;
2503
2504 assert(fastmap != NULL && p != NULL);
2505
2506 INIT_FAIL_STACK();
2507 bzero(fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
2508 bufp->fastmap_accurate = 1; /* It will be when we're done. */
2509 bufp->can_be_null = 0;
2510
2511 while (p != pend || !FAIL_STACK_EMPTY()) {
2512 if (p == pend) {
2513 bufp->can_be_null |= path_can_be_null;
2514
2515 /* Reset for next path. */
2516 path_can_be_null = true;
2517
2518 p = fail_stack.stack[--fail_stack.avail];
2519 }
2520 /* We should never be about to go beyond the end of the pattern. */
2521 assert(p < pend);
2522
2523 #ifdef SWITCH_ENUM_BUG
2524 switch ((int) ((re_opcode_t) * p++))
2525 #else
2526 switch ((re_opcode_t) * p++)
2527 #endif
2528 {
2529
2530 /* I guess the idea here is to simply not bother with a fastmap
2531 * if a backreference is used, since it's too hard to figure out
2532 * the fastmap for the corresponding group. Setting
2533 * `can_be_null' stops `re_search_2' from using the fastmap, so
2534 * that is all we do. */
2535 case duplicate:
2536 FREE_VAR (fail_stack.stack);
2537 bufp->can_be_null = 1;
2538 return 0;
2539
2540
2541 /* Following are the cases which match a character. These end
2542 * with `break'. */
2543
2544 case exactn:
2545 fastmap[p[1]] = 1;
2546 break;
2547
2548
2549 case charset:
2550 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
2551 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
2552 fastmap[j] = 1;
2553 break;
2554
2555
2556 case charset_not:
2557 /* Chars beyond end of map must be allowed. */
2558 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
2559 fastmap[j] = 1;
2560
2561 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
2562 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
2563 fastmap[j] = 1;
2564 break;
2565
2566
2567 case wordchar:
2568 for (j = 0; j < (1 << BYTEWIDTH); j++)
2569 if (SYNTAX(j) == Sword)
2570 fastmap[j] = 1;
2571 break;
2572
2573
2574 case notwordchar:
2575 for (j = 0; j < (1 << BYTEWIDTH); j++)
2576 if (SYNTAX(j) != Sword)
2577 fastmap[j] = 1;
2578 break;
2579
2580
2581 case anychar:
2582 /* `.' matches anything ... */
2583 for (j = 0; j < (1 << BYTEWIDTH); j++)
2584 fastmap[j] = 1;
2585
2586 /* ... except perhaps newline. */
2587 if (!(bufp->syntax & RE_DOT_NEWLINE))
2588 fastmap['\n'] = 0;
2589
2590 /* Return if we have already set `can_be_null'; if we have,
2591 * then the fastmap is irrelevant. Something's wrong here. */
2592 else if (bufp->can_be_null)
2593 return 0;
2594
2595 /* Otherwise, have to check alternative paths. */
2596 break;
2597
2598
2599 #ifdef emacs
2600 case syntaxspec:
2601 k = *p++;
2602 for (j = 0; j < (1 << BYTEWIDTH); j++)
2603 if (SYNTAX(j) == (enum syntaxcode) k)
2604 fastmap[j] = 1;
2605 break;
2606
2607
2608 case notsyntaxspec:
2609 k = *p++;
2610 for (j = 0; j < (1 << BYTEWIDTH); j++)
2611 if (SYNTAX(j) != (enum syntaxcode) k)
2612 fastmap[j] = 1;
2613 break;
2614
2615
2616 /* All cases after this match the empty string. These end with
2617 * `continue'. */
2618
2619
2620 case before_dot:
2621 case at_dot:
2622 case after_dot:
2623 continue;
2624 #endif /* not emacs */
2625
2626
2627 case no_op:
2628 case begline:
2629 case endline:
2630 case begbuf:
2631 case endbuf:
2632 case wordbound:
2633 case notwordbound:
2634 case wordbeg:
2635 case wordend:
2636 case push_dummy_failure:
2637 continue;
2638
2639
2640 case jump_n:
2641 case pop_failure_jump:
2642 case maybe_pop_jump:
2643 case jump:
2644 case jump_past_alt:
2645 case dummy_failure_jump:
2646 EXTRACT_NUMBER_AND_INCR(j, p);
2647 p += j;
2648 if (j > 0)
2649 continue;
2650
2651 /* Jump backward implies we just went through the body of a
2652 * loop and matched nothing. Opcode jumped to should be
2653 * `on_failure_jump' or `succeed_n'. Just treat it like an
2654 * ordinary jump. For a * loop, it has pushed its failure
2655 * point already; if so, discard that as redundant. */
2656 if ((re_opcode_t) * p != on_failure_jump
2657 && (re_opcode_t) * p != succeed_n)
2658 continue;
2659
2660 p++;
2661 EXTRACT_NUMBER_AND_INCR(j, p);
2662 p += j;
2663
2664 /* If what's on the stack is where we are now, pop it. */
2665 if (!FAIL_STACK_EMPTY()
2666 && fail_stack.stack[fail_stack.avail - 1] == p)
2667 fail_stack.avail--;
2668
2669 continue;
2670
2671
2672 case on_failure_jump:
2673 case on_failure_keep_string_jump:
2674 handle_on_failure_jump:
2675 EXTRACT_NUMBER_AND_INCR(j, p);
2676
2677 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
2678 * end of the pattern. We don't want to push such a point,
2679 * since when we restore it above, entering the switch will
2680 * increment `p' past the end of the pattern. We don't need
2681 * to push such a point since we obviously won't find any more
2682 * fastmap entries beyond `pend'. Such a pattern can match
2683 * the null string, though. */
2684 if (p + j < pend) {
2685 if (!PUSH_PATTERN_OP(p + j, fail_stack))
2686 return -2;
2687 } else
2688 bufp->can_be_null = 1;
2689
2690 if (succeed_n_p) {
2691 EXTRACT_NUMBER_AND_INCR(k, p); /* Skip the n. */
2692 succeed_n_p = false;
2693 }
2694 continue;
2695
2696
2697 case succeed_n:
2698 /* Get to the number of times to succeed. */
2699 p += 2;
2700
2701 /* Increment p past the n for when k != 0. */
2702 EXTRACT_NUMBER_AND_INCR(k, p);
2703 if (k == 0) {
2704 p -= 4;
2705 succeed_n_p = true; /* Spaghetti code alert. */
2706 goto handle_on_failure_jump;
2707 }
2708 continue;
2709
2710
2711 case set_number_at:
2712 p += 4;
2713 continue;
2714
2715
2716 case start_memory:
2717 case stop_memory:
2718 p += 2;
2719 continue;
2720
2721
2722 default:
2723 abort(); /* We have listed all the cases. */
2724 } /* switch *p++ */
2725
2726 /* Getting here means we have found the possible starting
2727 * characters for one path of the pattern -- and that the empty
2728 * string does not match. We need not follow this path further.
2729 * Instead, look at the next alternative (remembered on the
2730 * stack), or quit if no more. The test at the top of the loop
2731 * does these things. */
2732 path_can_be_null = false;
2733 p = pend;
2734 } /* while p */
2735
2736 /* Set `can_be_null' for the last path (also the first path, if the
2737 * pattern is empty). */
2738 bufp->can_be_null |= path_can_be_null;
2739 return 0;
2740 } /* re_compile_fastmap */
2741
2742 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
2743 * ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
2744 * this memory for recording register information. STARTS and ENDS
2745 * must be allocated using the malloc library routine, and must each
2746 * be at least NUM_REGS * sizeof (regoff_t) bytes long.
2747 *
2748 * If NUM_REGS == 0, then subsequent matches should allocate their own
2749 * register data.
2750 *
2751 * Unless this function is called, the first search or match using
2752 * PATTERN_BUFFER will allocate its own register data, without
2753 * freeing the old data. */
2754
2755 void
re_set_registers(bufp,regs,num_regs,starts,ends)2756 re_set_registers(bufp, regs, num_regs, starts, ends)
2757 struct re_pattern_buffer *bufp;
2758 struct re_registers *regs;
2759 unsigned num_regs;
2760 regoff_t *starts, *ends;
2761 {
2762 if (num_regs) {
2763 bufp->regs_allocated = REGS_REALLOCATE;
2764 regs->num_regs = num_regs;
2765 regs->start = starts;
2766 regs->end = ends;
2767 } else {
2768 bufp->regs_allocated = REGS_UNALLOCATED;
2769 regs->num_regs = 0;
2770 regs->start = regs->end = (regoff_t) 0;
2771 }
2772 }
2773
2774 /* Searching routines. */
2775
2776 /* Like re_search_2, below, but only one string is specified, and
2777 * doesn't let you say where to stop matching. */
2778
2779 int
re_search(bufp,string,size,startpos,range,regs)2780 re_search(bufp, string, size, startpos, range, regs)
2781 struct re_pattern_buffer *bufp;
2782 const char *string;
2783 int size, startpos, range;
2784 struct re_registers *regs;
2785 {
2786 return re_search_2(bufp, NULL, 0, string, size, startpos, range,
2787 regs, size);
2788 }
2789
2790
2791 /* Using the compiled pattern in BUFP->buffer, first tries to match the
2792 * virtual concatenation of STRING1 and STRING2, starting first at index
2793 * STARTPOS, then at STARTPOS + 1, and so on.
2794 *
2795 * STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
2796 *
2797 * RANGE is how far to scan while trying to match. RANGE = 0 means try
2798 * only at STARTPOS; in general, the last start tried is STARTPOS +
2799 * RANGE.
2800 *
2801 * In REGS, return the indices of the virtual concatenation of STRING1
2802 * and STRING2 that matched the entire BUFP->buffer and its contained
2803 * subexpressions.
2804 *
2805 * Do not consider matching one past the index STOP in the virtual
2806 * concatenation of STRING1 and STRING2.
2807 *
2808 * We return either the position in the strings at which the match was
2809 * found, -1 if no match, or -2 if error (such as failure
2810 * stack overflow). */
2811
2812 int
re_search_2(bufp,string1,size1,string2,size2,startpos,range,regs,stop)2813 re_search_2(bufp, string1, size1, string2, size2, startpos, range, regs, stop)
2814 struct re_pattern_buffer *bufp;
2815 const char *string1, *string2;
2816 int size1, size2;
2817 int startpos;
2818 int range;
2819 struct re_registers *regs;
2820 int stop;
2821 {
2822 int val;
2823 register char *fastmap = bufp->fastmap;
2824 register char *translate = bufp->translate;
2825 int total_size = size1 + size2;
2826 int endpos = startpos + range;
2827
2828 /* Check for out-of-range STARTPOS. */
2829 if (startpos < 0 || startpos > total_size)
2830 return -1;
2831
2832 /* Fix up RANGE if it might eventually take us outside
2833 * the virtual concatenation of STRING1 and STRING2. */
2834 if (endpos < -1)
2835 range = -1 - startpos;
2836 else if (endpos > total_size)
2837 range = total_size - startpos;
2838
2839 /* If the search isn't to be a backwards one, don't waste time in a
2840 * search for a pattern that must be anchored. */
2841 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0) {
2842 if (startpos > 0)
2843 return -1;
2844 else
2845 range = 1;
2846 }
2847 /* Update the fastmap now if not correct already. */
2848 if (fastmap && !bufp->fastmap_accurate)
2849 if (re_compile_fastmap(bufp) == -2)
2850 return -2;
2851
2852 /* Loop through the string, looking for a place to start matching. */
2853 for (;;) {
2854 /* If a fastmap is supplied, skip quickly over characters that
2855 * cannot be the start of a match. If the pattern can match the
2856 * null string, however, we don't need to skip characters; we want
2857 * the first null string. */
2858 if (fastmap && startpos < total_size && !bufp->can_be_null) {
2859 if (range > 0) { /* Searching forwards. */
2860 register const char *d;
2861 register int lim = 0;
2862 int irange = range;
2863
2864 if (startpos < size1 && startpos + range >= size1)
2865 lim = range - (size1 - startpos);
2866
2867 d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
2868
2869 /* Written out as an if-else to avoid testing `translate'
2870 * inside the loop. */
2871 if (translate)
2872 while (range > lim
2873 && !fastmap[(unsigned char)
2874 translate[(unsigned char) *d++]])
2875 range--;
2876 else
2877 while (range > lim && !fastmap[(unsigned char) *d++])
2878 range--;
2879
2880 startpos += irange - range;
2881 } else { /* Searching backwards. */
2882 register char c = (size1 == 0 || startpos >= size1
2883 ? string2[startpos - size1]
2884 : string1[startpos]);
2885
2886 if (!fastmap[(unsigned char) TRANSLATE(c)])
2887 goto advance;
2888 }
2889 }
2890 /* If can't match the null string, and that's all we have left, fail. */
2891 if (range >= 0 && startpos == total_size && fastmap
2892 && !bufp->can_be_null)
2893 return -1;
2894
2895 val = re_match_2(bufp, string1, size1, string2, size2,
2896 startpos, regs, stop);
2897 if (val >= 0)
2898 return startpos;
2899
2900 if (val == -2)
2901 return -2;
2902
2903 advance:
2904 if (!range)
2905 break;
2906 else if (range > 0) {
2907 range--;
2908 startpos++;
2909 } else {
2910 range++;
2911 startpos--;
2912 }
2913 }
2914 return -1;
2915 } /* re_search_2 */
2916
2917 /* Declarations and macros for re_match_2. */
2918
2919 static int bcmp_translate();
2920 static boolean alt_match_null_string_p(), common_op_match_null_string_p(),
2921 group_match_null_string_p();
2922
2923 /* Structure for per-register (a.k.a. per-group) information.
2924 * This must not be longer than one word, because we push this value
2925 * onto the failure stack. Other register information, such as the
2926 * starting and ending positions (which are addresses), and the list of
2927 * inner groups (which is a bits list) are maintained in separate
2928 * variables.
2929 *
2930 * We are making a (strictly speaking) nonportable assumption here: that
2931 * the compiler will pack our bit fields into something that fits into
2932 * the type of `word', i.e., is something that fits into one item on the
2933 * failure stack. */
2934 typedef union {
2935 fail_stack_elt_t word;
2936 struct {
2937 /* This field is one if this group can match the empty string,
2938 * zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
2939 #define MATCH_NULL_UNSET_VALUE 3
2940 unsigned match_null_string_p:2;
2941 unsigned is_active:1;
2942 unsigned matched_something:1;
2943 unsigned ever_matched_something:1;
2944 } bits;
2945 } register_info_type;
2946
2947 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
2948 #define IS_ACTIVE(R) ((R).bits.is_active)
2949 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
2950 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
2951
2952
2953 /* Call this when have matched a real character; it sets `matched' flags
2954 * for the subexpressions which we are currently inside. Also records
2955 * that those subexprs have matched. */
2956 #define SET_REGS_MATCHED() \
2957 do \
2958 { \
2959 unsigned r; \
2960 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
2961 { \
2962 MATCHED_SOMETHING (reg_info[r]) \
2963 = EVER_MATCHED_SOMETHING (reg_info[r]) \
2964 = 1; \
2965 } \
2966 } \
2967 while (0)
2968
2969
2970 /* This converts PTR, a pointer into one of the search strings `string1'
2971 * and `string2' into an offset from the beginning of that string. */
2972 #define POINTER_TO_OFFSET(ptr) \
2973 (FIRST_STRING_P (ptr) ? (ptr) - string1 : (ptr) - string2 + size1)
2974
2975 /* Registers are set to a sentinel when they haven't yet matched. */
2976 #define REG_UNSET_VALUE ((char *) -1)
2977 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
2978
2979
2980 /* Macros for dealing with the split strings in re_match_2. */
2981
2982 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
2983
2984 /* Call before fetching a character with *d. This switches over to
2985 * string2 if necessary. */
2986 #define PREFETCH() \
2987 while (d == dend) \
2988 { \
2989 /* End of string2 => fail. */ \
2990 if (dend == end_match_2) \
2991 goto fail; \
2992 /* End of string1 => advance to string2. */ \
2993 d = string2; \
2994 dend = end_match_2; \
2995 }
2996
2997
2998 /* Test if at very beginning or at very end of the virtual concatenation
2999 * of `string1' and `string2'. If only one string, it's `string2'. */
3000 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
3001 #define AT_STRINGS_END(d) ((d) == end2)
3002
3003
3004 /* Test if D points to a character which is word-constituent. We have
3005 * two special cases to check for: if past the end of string1, look at
3006 * the first character in string2; and if before the beginning of
3007 * string2, look at the last character in string1. */
3008 #define WORDCHAR_P(d) \
3009 (SYNTAX ((d) == end1 ? *string2 \
3010 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
3011 == Sword)
3012
3013 /* Test if the character before D and the one at D differ with respect
3014 * to being word-constituent. */
3015 #define AT_WORD_BOUNDARY(d) \
3016 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
3017 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
3018
3019
3020 /* Free everything we malloc. */
3021 #ifdef REGEX_MALLOC
3022 #define FREE_VAR(var) if (var) free (var); var = NULL
3023 #define FREE_VARIABLES() \
3024 do { \
3025 FREE_VAR (fail_stack.stack); \
3026 FREE_VAR (regstart); \
3027 FREE_VAR (regend); \
3028 FREE_VAR (old_regstart); \
3029 FREE_VAR (old_regend); \
3030 FREE_VAR (best_regstart); \
3031 FREE_VAR (best_regend); \
3032 FREE_VAR (reg_info); \
3033 FREE_VAR (reg_dummy); \
3034 FREE_VAR (reg_info_dummy); \
3035 } while (0)
3036 #else /* not REGEX_MALLOC */
3037 /* Some MIPS systems (at least) want this to free alloca'd storage. */
3038 #define FREE_VARIABLES() alloca (0)
3039 #endif /* not REGEX_MALLOC */
3040
3041
3042 /* These values must meet several constraints. They must not be valid
3043 * register values; since we have a limit of 255 registers (because
3044 * we use only one byte in the pattern for the register number), we can
3045 * use numbers larger than 255. They must differ by 1, because of
3046 * NUM_FAILURE_ITEMS above. And the value for the lowest register must
3047 * be larger than the value for the highest register, so we do not try
3048 * to actually save any registers when none are active. */
3049 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
3050 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
3051
3052 /* Matching routines. */
3053
3054 #ifndef emacs /* Emacs never uses this. */
3055 /* re_match is like re_match_2 except it takes only a single string. */
3056
3057 int
re_match(bufp,string,size,pos,regs)3058 re_match(bufp, string, size, pos, regs)
3059 struct re_pattern_buffer *bufp;
3060 const char *string;
3061 int size, pos;
3062 struct re_registers *regs;
3063 {
3064 return re_match_2(bufp, NULL, 0, string, size, pos, regs, size);
3065 }
3066 #endif /* not emacs */
3067
3068
3069 /* re_match_2 matches the compiled pattern in BUFP against the
3070 * the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
3071 * and SIZE2, respectively). We start matching at POS, and stop
3072 * matching at STOP.
3073 *
3074 * If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
3075 * store offsets for the substring each group matched in REGS. See the
3076 * documentation for exactly how many groups we fill.
3077 *
3078 * We return -1 if no match, -2 if an internal error (such as the
3079 * failure stack overflowing). Otherwise, we return the length of the
3080 * matched substring. */
3081
3082 int
re_match_2(bufp,string1,size1,string2,size2,pos,regs,stop)3083 re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop)
3084 struct re_pattern_buffer *bufp;
3085 const char *string1, *string2;
3086 int size1, size2;
3087 int pos;
3088 struct re_registers *regs;
3089 int stop;
3090 {
3091 /* General temporaries. */
3092 int mcnt;
3093 unsigned char *p1;
3094
3095 /* Just past the end of the corresponding string. */
3096 const char *end1, *end2;
3097
3098 /* Pointers into string1 and string2, just past the last characters in
3099 * each to consider matching. */
3100 const char *end_match_1, *end_match_2;
3101
3102 /* Where we are in the data, and the end of the current string. */
3103 const char *d, *dend;
3104
3105 /* Where we are in the pattern, and the end of the pattern. */
3106 unsigned char *p = bufp->buffer;
3107 register unsigned char *pend = p + bufp->used;
3108
3109 /* We use this to map every character in the string. */
3110 char *translate = bufp->translate;
3111
3112 /* Failure point stack. Each place that can handle a failure further
3113 * down the line pushes a failure point on this stack. It consists of
3114 * restart, regend, and reg_info for all registers corresponding to
3115 * the subexpressions we're currently inside, plus the number of such
3116 * registers, and, finally, two char *'s. The first char * is where
3117 * to resume scanning the pattern; the second one is where to resume
3118 * scanning the strings. If the latter is zero, the failure point is
3119 * a ``dummy''; if a failure happens and the failure point is a dummy,
3120 * it gets discarded and the next next one is tried. */
3121 fail_stack_type fail_stack;
3122 #ifdef DEBUG
3123 static unsigned failure_id = 0;
3124 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
3125 #endif
3126
3127 /* We fill all the registers internally, independent of what we
3128 * return, for use in backreferences. The number here includes
3129 * an element for register zero. */
3130 unsigned num_regs = bufp->re_nsub + 1;
3131
3132 /* The currently active registers. */
3133 unsigned long lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3134 unsigned long highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3135
3136 /* Information on the contents of registers. These are pointers into
3137 * the input strings; they record just what was matched (on this
3138 * attempt) by a subexpression part of the pattern, that is, the
3139 * regnum-th regstart pointer points to where in the pattern we began
3140 * matching and the regnum-th regend points to right after where we
3141 * stopped matching the regnum-th subexpression. (The zeroth register
3142 * keeps track of what the whole pattern matches.) */
3143 const char **regstart = NULL, **regend = NULL;
3144
3145 /* If a group that's operated upon by a repetition operator fails to
3146 * match anything, then the register for its start will need to be
3147 * restored because it will have been set to wherever in the string we
3148 * are when we last see its open-group operator. Similarly for a
3149 * register's end. */
3150 const char **old_regstart = NULL, **old_regend = NULL;
3151
3152 /* The is_active field of reg_info helps us keep track of which (possibly
3153 * nested) subexpressions we are currently in. The matched_something
3154 * field of reg_info[reg_num] helps us tell whether or not we have
3155 * matched any of the pattern so far this time through the reg_num-th
3156 * subexpression. These two fields get reset each time through any
3157 * loop their register is in. */
3158 register_info_type *reg_info = NULL;
3159
3160 /* The following record the register info as found in the above
3161 * variables when we find a match better than any we've seen before.
3162 * This happens as we backtrack through the failure points, which in
3163 * turn happens only if we have not yet matched the entire string. */
3164 unsigned best_regs_set = false;
3165 const char **best_regstart = NULL, **best_regend = NULL;
3166
3167 /* Logically, this is `best_regend[0]'. But we don't want to have to
3168 * allocate space for that if we're not allocating space for anything
3169 * else (see below). Also, we never need info about register 0 for
3170 * any of the other register vectors, and it seems rather a kludge to
3171 * treat `best_regend' differently than the rest. So we keep track of
3172 * the end of the best match so far in a separate variable. We
3173 * initialize this to NULL so that when we backtrack the first time
3174 * and need to test it, it's not garbage. */
3175 const char *match_end = NULL;
3176
3177 /* Used when we pop values we don't care about. */
3178 const char **reg_dummy = NULL;
3179 register_info_type *reg_info_dummy = NULL;
3180
3181 #ifdef DEBUG
3182 /* Counts the total number of registers pushed. */
3183 unsigned num_regs_pushed = 0;
3184 #endif
3185
3186 DEBUG_PRINT1("\n\nEntering re_match_2.\n");
3187
3188 INIT_FAIL_STACK();
3189
3190 /* Do not bother to initialize all the register variables if there are
3191 * no groups in the pattern, as it takes a fair amount of time. If
3192 * there are groups, we include space for register 0 (the whole
3193 * pattern), even though we never use it, since it simplifies the
3194 * array indexing. We should fix this. */
3195 if (bufp->re_nsub) {
3196 regstart = REGEX_TALLOC(num_regs, const char *);
3197 regend = REGEX_TALLOC(num_regs, const char *);
3198 old_regstart = REGEX_TALLOC(num_regs, const char *);
3199 old_regend = REGEX_TALLOC(num_regs, const char *);
3200 best_regstart = REGEX_TALLOC(num_regs, const char *);
3201 best_regend = REGEX_TALLOC(num_regs, const char *);
3202 reg_info = REGEX_TALLOC(num_regs, register_info_type);
3203 reg_dummy = REGEX_TALLOC(num_regs, const char *);
3204 reg_info_dummy = REGEX_TALLOC(num_regs, register_info_type);
3205
3206 if (!(regstart && regend && old_regstart && old_regend && reg_info
3207 && best_regstart && best_regend && reg_dummy && reg_info_dummy)) {
3208 FREE_VARIABLES();
3209 return -2;
3210 }
3211 }
3212 #ifdef REGEX_MALLOC
3213 else {
3214 /* We must initialize all our variables to NULL, so that
3215 * `FREE_VARIABLES' doesn't try to free them. */
3216 regstart = regend = old_regstart = old_regend = best_regstart
3217 = best_regend = reg_dummy = NULL;
3218 reg_info = reg_info_dummy = (register_info_type *) NULL;
3219 }
3220 #endif /* REGEX_MALLOC */
3221
3222 /* The starting position is bogus. */
3223 if (pos < 0 || pos > size1 + size2) {
3224 FREE_VARIABLES();
3225 return -1;
3226 }
3227 /* Initialize subexpression text positions to -1 to mark ones that no
3228 * start_memory/stop_memory has been seen for. Also initialize the
3229 * register information struct. */
3230 for (mcnt = 1; mcnt < num_regs; mcnt++) {
3231 regstart[mcnt] = regend[mcnt]
3232 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
3233
3234 REG_MATCH_NULL_STRING_P(reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
3235 IS_ACTIVE(reg_info[mcnt]) = 0;
3236 MATCHED_SOMETHING(reg_info[mcnt]) = 0;
3237 EVER_MATCHED_SOMETHING(reg_info[mcnt]) = 0;
3238 }
3239
3240 /* We move `string1' into `string2' if the latter's empty -- but not if
3241 * `string1' is null. */
3242 if (size2 == 0 && string1 != NULL) {
3243 string2 = string1;
3244 size2 = size1;
3245 string1 = 0;
3246 size1 = 0;
3247 }
3248 end1 = string1 + size1;
3249 end2 = string2 + size2;
3250
3251 /* Compute where to stop matching, within the two strings. */
3252 if (stop <= size1) {
3253 end_match_1 = string1 + stop;
3254 end_match_2 = string2;
3255 } else {
3256 end_match_1 = end1;
3257 end_match_2 = string2 + stop - size1;
3258 }
3259
3260 /* `p' scans through the pattern as `d' scans through the data.
3261 * `dend' is the end of the input string that `d' points within. `d'
3262 * is advanced into the following input string whenever necessary, but
3263 * this happens before fetching; therefore, at the beginning of the
3264 * loop, `d' can be pointing at the end of a string, but it cannot
3265 * equal `string2'. */
3266 if (size1 > 0 && pos <= size1) {
3267 d = string1 + pos;
3268 dend = end_match_1;
3269 } else {
3270 d = string2 + pos - size1;
3271 dend = end_match_2;
3272 }
3273
3274 DEBUG_PRINT1("The compiled pattern is: ");
3275 DEBUG_PRINT_COMPILED_PATTERN(bufp, p, pend);
3276 DEBUG_PRINT1("The string to match is: `");
3277 DEBUG_PRINT_DOUBLE_STRING(d, string1, size1, string2, size2);
3278 DEBUG_PRINT1("'\n");
3279
3280 /* This loops over pattern commands. It exits by returning from the
3281 * function if the match is complete, or it drops through if the match
3282 * fails at this starting point in the input data. */
3283 for (;;) {
3284 DEBUG_PRINT2("\n0x%x: ", p);
3285
3286 if (p == pend) { /* End of pattern means we might have succeeded. */
3287 DEBUG_PRINT1("end of pattern ... ");
3288
3289 /* If we haven't matched the entire string, and we want the
3290 * longest match, try backtracking. */
3291 if (d != end_match_2) {
3292 DEBUG_PRINT1("backtracking.\n");
3293
3294 if (!FAIL_STACK_EMPTY()) { /* More failure points to try. */
3295 boolean same_str_p = (FIRST_STRING_P(match_end)
3296 == MATCHING_IN_FIRST_STRING);
3297
3298 /* If exceeds best match so far, save it. */
3299 if (!best_regs_set
3300 || (same_str_p && d > match_end)
3301 || (!same_str_p && !MATCHING_IN_FIRST_STRING)) {
3302 best_regs_set = true;
3303 match_end = d;
3304
3305 DEBUG_PRINT1("\nSAVING match as best so far.\n");
3306
3307 for (mcnt = 1; mcnt < num_regs; mcnt++) {
3308 best_regstart[mcnt] = regstart[mcnt];
3309 best_regend[mcnt] = regend[mcnt];
3310 }
3311 }
3312 goto fail;
3313 }
3314 /* If no failure points, don't restore garbage. */
3315 else if (best_regs_set) {
3316 restore_best_regs:
3317 /* Restore best match. It may happen that `dend ==
3318 * end_match_1' while the restored d is in string2.
3319 * For example, the pattern `x.*y.*z' against the
3320 * strings `x-' and `y-z-', if the two strings are
3321 * not consecutive in memory. */
3322 DEBUG_PRINT1("Restoring best registers.\n");
3323
3324 d = match_end;
3325 dend = ((d >= string1 && d <= end1)
3326 ? end_match_1 : end_match_2);
3327
3328 for (mcnt = 1; mcnt < num_regs; mcnt++) {
3329 regstart[mcnt] = best_regstart[mcnt];
3330 regend[mcnt] = best_regend[mcnt];
3331 }
3332 }
3333 } /* d != end_match_2 */
3334 DEBUG_PRINT1("Accepting match.\n");
3335
3336 /* If caller wants register contents data back, do it. */
3337 if (regs && !bufp->no_sub) {
3338 /* Have the register data arrays been allocated? */
3339 if (bufp->regs_allocated == REGS_UNALLOCATED) { /* No. So allocate them with malloc. We need one
3340 * extra element beyond `num_regs' for the `-1' marker
3341 * GNU code uses. */
3342 regs->num_regs = MAX(RE_NREGS, num_regs + 1);
3343 regs->start = TALLOC(regs->num_regs, regoff_t);
3344 regs->end = TALLOC(regs->num_regs, regoff_t);
3345 if (regs->start == NULL || regs->end == NULL)
3346 return -2;
3347 bufp->regs_allocated = REGS_REALLOCATE;
3348 } else if (bufp->regs_allocated == REGS_REALLOCATE) { /* Yes. If we need more elements than were already
3349 * allocated, reallocate them. If we need fewer, just
3350 * leave it alone. */
3351 if (regs->num_regs < num_regs + 1) {
3352 regs->num_regs = num_regs + 1;
3353 RETALLOC(regs->start, regs->num_regs, regoff_t);
3354 RETALLOC(regs->end, regs->num_regs, regoff_t);
3355 if (regs->start == NULL || regs->end == NULL)
3356 return -2;
3357 }
3358 } else
3359 assert(bufp->regs_allocated == REGS_FIXED);
3360
3361 /* Convert the pointer data in `regstart' and `regend' to
3362 * indices. Register zero has to be set differently,
3363 * since we haven't kept track of any info for it. */
3364 if (regs->num_regs > 0) {
3365 regs->start[0] = pos;
3366 regs->end[0] = (MATCHING_IN_FIRST_STRING ? d - string1
3367 : d - string2 + size1);
3368 }
3369 /* Go through the first `min (num_regs, regs->num_regs)'
3370 * registers, since that is all we initialized. */
3371 for (mcnt = 1; mcnt < MIN(num_regs, regs->num_regs); mcnt++) {
3372 if (REG_UNSET(regstart[mcnt]) || REG_UNSET(regend[mcnt]))
3373 regs->start[mcnt] = regs->end[mcnt] = -1;
3374 else {
3375 regs->start[mcnt] = POINTER_TO_OFFSET(regstart[mcnt]);
3376 regs->end[mcnt] = POINTER_TO_OFFSET(regend[mcnt]);
3377 }
3378 }
3379
3380 /* If the regs structure we return has more elements than
3381 * were in the pattern, set the extra elements to -1. If
3382 * we (re)allocated the registers, this is the case,
3383 * because we always allocate enough to have at least one
3384 * -1 at the end. */
3385 for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
3386 regs->start[mcnt] = regs->end[mcnt] = -1;
3387 } /* regs && !bufp->no_sub */
3388 FREE_VARIABLES();
3389 DEBUG_PRINT4("%u failure points pushed, %u popped (%u remain).\n",
3390 nfailure_points_pushed, nfailure_points_popped,
3391 nfailure_points_pushed - nfailure_points_popped);
3392 DEBUG_PRINT2("%u registers pushed.\n", num_regs_pushed);
3393
3394 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
3395 ? string1
3396 : string2 - size1);
3397
3398 DEBUG_PRINT2("Returning %d from re_match_2.\n", mcnt);
3399
3400 return mcnt;
3401 }
3402 /* Otherwise match next pattern command. */
3403 #ifdef SWITCH_ENUM_BUG
3404 switch ((int) ((re_opcode_t) * p++))
3405 #else
3406 switch ((re_opcode_t) * p++)
3407 #endif
3408 {
3409 /* Ignore these. Used to ignore the n of succeed_n's which
3410 * currently have n == 0. */
3411 case no_op:
3412 DEBUG_PRINT1("EXECUTING no_op.\n");
3413 break;
3414
3415
3416 /* Match the next n pattern characters exactly. The following
3417 * byte in the pattern defines n, and the n bytes after that
3418 * are the characters to match. */
3419 case exactn:
3420 mcnt = *p++;
3421 DEBUG_PRINT2("EXECUTING exactn %d.\n", mcnt);
3422
3423 /* This is written out as an if-else so we don't waste time
3424 * testing `translate' inside the loop. */
3425 if (translate) {
3426 do {
3427 PREFETCH();
3428 if (translate[(unsigned char) *d++] != (char) *p++)
3429 goto fail;
3430 }
3431 while (--mcnt);
3432 } else {
3433 do {
3434 PREFETCH();
3435 if (*d++ != (char) *p++)
3436 goto fail;
3437 }
3438 while (--mcnt);
3439 }
3440 SET_REGS_MATCHED();
3441 break;
3442
3443
3444 /* Match any character except possibly a newline or a null. */
3445 case anychar:
3446 DEBUG_PRINT1("EXECUTING anychar.\n");
3447
3448 PREFETCH();
3449
3450 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE(*d) == '\n')
3451 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE(*d) == '\000'))
3452 goto fail;
3453
3454 SET_REGS_MATCHED();
3455 DEBUG_PRINT2(" Matched `%d'.\n", *d);
3456 d++;
3457 break;
3458
3459
3460 case charset:
3461 case charset_not:
3462 {
3463 register unsigned char c;
3464 boolean not = (re_opcode_t) * (p - 1) == charset_not;
3465
3466 DEBUG_PRINT2("EXECUTING charset%s.\n", not ? "_not" : "");
3467
3468 PREFETCH();
3469 c = TRANSLATE(*d); /* The character to match. */
3470
3471 /* Cast to `unsigned' instead of `unsigned char' in case the
3472 * bit list is a full 32 bytes long. */
3473 if (c < (unsigned) (*p * BYTEWIDTH)
3474 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
3475 not = !not;
3476
3477 p += 1 + *p;
3478
3479 if (!not)
3480 goto fail;
3481
3482 SET_REGS_MATCHED();
3483 d++;
3484 break;
3485 }
3486
3487
3488 /* The beginning of a group is represented by start_memory.
3489 * The arguments are the register number in the next byte, and the
3490 * number of groups inner to this one in the next. The text
3491 * matched within the group is recorded (in the internal
3492 * registers data structure) under the register number. */
3493 case start_memory:
3494 DEBUG_PRINT3("EXECUTING start_memory %d (%d):\n", *p, p[1]);
3495
3496 /* Find out if this group can match the empty string. */
3497 p1 = p; /* To send to group_match_null_string_p. */
3498
3499 if (REG_MATCH_NULL_STRING_P(reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
3500 REG_MATCH_NULL_STRING_P(reg_info[*p])
3501 = group_match_null_string_p(&p1, pend, reg_info);
3502
3503 /* Save the position in the string where we were the last time
3504 * we were at this open-group operator in case the group is
3505 * operated upon by a repetition operator, e.g., with `(a*)*b'
3506 * against `ab'; then we want to ignore where we are now in
3507 * the string in case this attempt to match fails. */
3508 old_regstart[*p] = REG_MATCH_NULL_STRING_P(reg_info[*p])
3509 ? REG_UNSET(regstart[*p]) ? d : regstart[*p]
3510 : regstart[*p];
3511 DEBUG_PRINT2(" old_regstart: %d\n",
3512 POINTER_TO_OFFSET(old_regstart[*p]));
3513
3514 regstart[*p] = d;
3515 DEBUG_PRINT2(" regstart: %d\n", POINTER_TO_OFFSET(regstart[*p]));
3516
3517 IS_ACTIVE(reg_info[*p]) = 1;
3518 MATCHED_SOMETHING(reg_info[*p]) = 0;
3519
3520 /* This is the new highest active register. */
3521 highest_active_reg = *p;
3522
3523 /* If nothing was active before, this is the new lowest active
3524 * register. */
3525 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
3526 lowest_active_reg = *p;
3527
3528 /* Move past the register number and inner group count. */
3529 p += 2;
3530 break;
3531
3532
3533 /* The stop_memory opcode represents the end of a group. Its
3534 * arguments are the same as start_memory's: the register
3535 * number, and the number of inner groups. */
3536 case stop_memory:
3537 DEBUG_PRINT3("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
3538
3539 /* We need to save the string position the last time we were at
3540 * this close-group operator in case the group is operated
3541 * upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
3542 * against `aba'; then we want to ignore where we are now in
3543 * the string in case this attempt to match fails. */
3544 old_regend[*p] = REG_MATCH_NULL_STRING_P(reg_info[*p])
3545 ? REG_UNSET(regend[*p]) ? d : regend[*p]
3546 : regend[*p];
3547 DEBUG_PRINT2(" old_regend: %d\n",
3548 POINTER_TO_OFFSET(old_regend[*p]));
3549
3550 regend[*p] = d;
3551 DEBUG_PRINT2(" regend: %d\n", POINTER_TO_OFFSET(regend[*p]));
3552
3553 /* This register isn't active anymore. */
3554 IS_ACTIVE(reg_info[*p]) = 0;
3555
3556 /* If this was the only register active, nothing is active
3557 * anymore. */
3558 if (lowest_active_reg == highest_active_reg) {
3559 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3560 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3561 } else { /* We must scan for the new highest active register, since
3562 * it isn't necessarily one less than now: consider
3563 * (a(b)c(d(e)f)g). When group 3 ends, after the f), the
3564 * new highest active register is 1. */
3565 unsigned char r = *p - 1;
3566 while (r > 0 && !IS_ACTIVE(reg_info[r]))
3567 r--;
3568
3569 /* If we end up at register zero, that means that we saved
3570 * the registers as the result of an `on_failure_jump', not
3571 * a `start_memory', and we jumped to past the innermost
3572 * `stop_memory'. For example, in ((.)*) we save
3573 * registers 1 and 2 as a result of the *, but when we pop
3574 * back to the second ), we are at the stop_memory 1.
3575 * Thus, nothing is active. */
3576 if (r == 0) {
3577 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3578 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3579 } else
3580 highest_active_reg = r;
3581 }
3582
3583 /* If just failed to match something this time around with a
3584 * group that's operated on by a repetition operator, try to
3585 * force exit from the ``loop'', and restore the register
3586 * information for this group that we had before trying this
3587 * last match. */
3588 if ((!MATCHED_SOMETHING(reg_info[*p])
3589 || (re_opcode_t) p[-3] == start_memory)
3590 && (p + 2) < pend) {
3591 boolean is_a_jump_n = false;
3592
3593 p1 = p + 2;
3594 mcnt = 0;
3595 switch ((re_opcode_t) * p1++) {
3596 case jump_n:
3597 is_a_jump_n = true;
3598 case pop_failure_jump:
3599 case maybe_pop_jump:
3600 case jump:
3601 case dummy_failure_jump:
3602 EXTRACT_NUMBER_AND_INCR(mcnt, p1);
3603 if (is_a_jump_n)
3604 p1 += 2;
3605 break;
3606
3607 default:
3608 /* do nothing */ ;
3609 }
3610 p1 += mcnt;
3611
3612 /* If the next operation is a jump backwards in the pattern
3613 * to an on_failure_jump right before the start_memory
3614 * corresponding to this stop_memory, exit from the loop
3615 * by forcing a failure after pushing on the stack the
3616 * on_failure_jump's jump in the pattern, and d. */
3617 if (mcnt < 0 && (re_opcode_t) * p1 == on_failure_jump
3618 && (re_opcode_t) p1[3] == start_memory && p1[4] == *p) {
3619 /* If this group ever matched anything, then restore
3620 * what its registers were before trying this last
3621 * failed match, e.g., with `(a*)*b' against `ab' for
3622 * regstart[1], and, e.g., with `((a*)*(b*)*)*'
3623 * against `aba' for regend[3].
3624 *
3625 * Also restore the registers for inner groups for,
3626 * e.g., `((a*)(b*))*' against `aba' (register 3 would
3627 * otherwise get trashed). */
3628
3629 if (EVER_MATCHED_SOMETHING(reg_info[*p])) {
3630 unsigned r;
3631
3632 EVER_MATCHED_SOMETHING(reg_info[*p]) = 0;
3633
3634 /* Restore this and inner groups' (if any) registers. */
3635 for (r = *p; r < *p + *(p + 1); r++) {
3636 regstart[r] = old_regstart[r];
3637
3638 /* xx why this test? */
3639 if ((long) old_regend[r] >= (long) regstart[r])
3640 regend[r] = old_regend[r];
3641 }
3642 }
3643 p1++;
3644 EXTRACT_NUMBER_AND_INCR(mcnt, p1);
3645 PUSH_FAILURE_POINT(p1 + mcnt, d, -2);
3646
3647 goto fail;
3648 }
3649 }
3650 /* Move past the register number and the inner group count. */
3651 p += 2;
3652 break;
3653
3654
3655 /* \<digit> has been turned into a `duplicate' command which is
3656 * followed by the numeric value of <digit> as the register number. */
3657 case duplicate:
3658 {
3659 register const char *d2, *dend2;
3660 int regno = *p++; /* Get which register to match against. */
3661 DEBUG_PRINT2("EXECUTING duplicate %d.\n", regno);
3662
3663 /* Can't back reference a group which we've never matched. */
3664 if (REG_UNSET(regstart[regno]) || REG_UNSET(regend[regno]))
3665 goto fail;
3666
3667 /* Where in input to try to start matching. */
3668 d2 = regstart[regno];
3669
3670 /* Where to stop matching; if both the place to start and
3671 * the place to stop matching are in the same string, then
3672 * set to the place to stop, otherwise, for now have to use
3673 * the end of the first string. */
3674
3675 dend2 = ((FIRST_STRING_P(regstart[regno])
3676 == FIRST_STRING_P(regend[regno]))
3677 ? regend[regno] : end_match_1);
3678 for (;;) {
3679 /* If necessary, advance to next segment in register
3680 * contents. */
3681 while (d2 == dend2) {
3682 if (dend2 == end_match_2)
3683 break;
3684 if (dend2 == regend[regno])
3685 break;
3686
3687 /* End of string1 => advance to string2. */
3688 d2 = string2;
3689 dend2 = regend[regno];
3690 }
3691 /* At end of register contents => success */
3692 if (d2 == dend2)
3693 break;
3694
3695 /* If necessary, advance to next segment in data. */
3696 PREFETCH();
3697
3698 /* How many characters left in this segment to match. */
3699 mcnt = dend - d;
3700
3701 /* Want how many consecutive characters we can match in
3702 * one shot, so, if necessary, adjust the count. */
3703 if (mcnt > dend2 - d2)
3704 mcnt = dend2 - d2;
3705
3706 /* Compare that many; failure if mismatch, else move
3707 * past them. */
3708 if (translate
3709 ? bcmp_translate(d, d2, mcnt, translate)
3710 : bcmp(d, d2, mcnt))
3711 goto fail;
3712 d += mcnt, d2 += mcnt;
3713 }
3714 }
3715 break;
3716
3717
3718 /* begline matches the empty string at the beginning of the string
3719 * (unless `not_bol' is set in `bufp'), and, if
3720 * `newline_anchor' is set, after newlines. */
3721 case begline:
3722 DEBUG_PRINT1("EXECUTING begline.\n");
3723
3724 if (AT_STRINGS_BEG(d)) {
3725 if (!bufp->not_bol)
3726 break;
3727 } else if (d[-1] == '\n' && bufp->newline_anchor) {
3728 break;
3729 }
3730 /* In all other cases, we fail. */
3731 goto fail;
3732
3733
3734 /* endline is the dual of begline. */
3735 case endline:
3736 DEBUG_PRINT1("EXECUTING endline.\n");
3737
3738 if (AT_STRINGS_END(d)) {
3739 if (!bufp->not_eol)
3740 break;
3741 }
3742 /* We have to ``prefetch'' the next character. */
3743 else if ((d == end1 ? *string2 : *d) == '\n'
3744 && bufp->newline_anchor) {
3745 break;
3746 }
3747 goto fail;
3748
3749
3750 /* Match at the very beginning of the data. */
3751 case begbuf:
3752 DEBUG_PRINT1("EXECUTING begbuf.\n");
3753 if (AT_STRINGS_BEG(d))
3754 break;
3755 goto fail;
3756
3757
3758 /* Match at the very end of the data. */
3759 case endbuf:
3760 DEBUG_PRINT1("EXECUTING endbuf.\n");
3761 if (AT_STRINGS_END(d))
3762 break;
3763 goto fail;
3764
3765
3766 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
3767 * pushes NULL as the value for the string on the stack. Then
3768 * `pop_failure_point' will keep the current value for the
3769 * string, instead of restoring it. To see why, consider
3770 * matching `foo\nbar' against `.*\n'. The .* matches the foo;
3771 * then the . fails against the \n. But the next thing we want
3772 * to do is match the \n against the \n; if we restored the
3773 * string value, we would be back at the foo.
3774 *
3775 * Because this is used only in specific cases, we don't need to
3776 * check all the things that `on_failure_jump' does, to make
3777 * sure the right things get saved on the stack. Hence we don't
3778 * share its code. The only reason to push anything on the
3779 * stack at all is that otherwise we would have to change
3780 * `anychar's code to do something besides goto fail in this
3781 * case; that seems worse than this. */
3782 case on_failure_keep_string_jump:
3783 DEBUG_PRINT1("EXECUTING on_failure_keep_string_jump");
3784
3785 EXTRACT_NUMBER_AND_INCR(mcnt, p);
3786 DEBUG_PRINT3(" %d (to 0x%x):\n", mcnt, p + mcnt);
3787
3788 PUSH_FAILURE_POINT(p + mcnt, NULL, -2);
3789 break;
3790
3791
3792 /* Uses of on_failure_jump:
3793 *
3794 * Each alternative starts with an on_failure_jump that points
3795 * to the beginning of the next alternative. Each alternative
3796 * except the last ends with a jump that in effect jumps past
3797 * the rest of the alternatives. (They really jump to the
3798 * ending jump of the following alternative, because tensioning
3799 * these jumps is a hassle.)
3800 *
3801 * Repeats start with an on_failure_jump that points past both
3802 * the repetition text and either the following jump or
3803 * pop_failure_jump back to this on_failure_jump. */
3804 case on_failure_jump:
3805 on_failure:
3806 DEBUG_PRINT1("EXECUTING on_failure_jump");
3807
3808 EXTRACT_NUMBER_AND_INCR(mcnt, p);
3809 DEBUG_PRINT3(" %d (to 0x%x)", mcnt, p + mcnt);
3810
3811 /* If this on_failure_jump comes right before a group (i.e.,
3812 * the original * applied to a group), save the information
3813 * for that group and all inner ones, so that if we fail back
3814 * to this point, the group's information will be correct.
3815 * For example, in \(a*\)*\1, we need the preceding group,
3816 * and in \(\(a*\)b*\)\2, we need the inner group. */
3817
3818 /* We can't use `p' to check ahead because we push
3819 * a failure point to `p + mcnt' after we do this. */
3820 p1 = p;
3821
3822 /* We need to skip no_op's before we look for the
3823 * start_memory in case this on_failure_jump is happening as
3824 * the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
3825 * against aba. */
3826 while (p1 < pend && (re_opcode_t) * p1 == no_op)
3827 p1++;
3828
3829 if (p1 < pend && (re_opcode_t) * p1 == start_memory) {
3830 /* We have a new highest active register now. This will
3831 * get reset at the start_memory we are about to get to,
3832 * but we will have saved all the registers relevant to
3833 * this repetition op, as described above. */
3834 highest_active_reg = *(p1 + 1) + *(p1 + 2);
3835 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
3836 lowest_active_reg = *(p1 + 1);
3837 }
3838 DEBUG_PRINT1(":\n");
3839 PUSH_FAILURE_POINT(p + mcnt, d, -2);
3840 break;
3841
3842
3843 /* A smart repeat ends with `maybe_pop_jump'.
3844 * We change it to either `pop_failure_jump' or `jump'. */
3845 case maybe_pop_jump:
3846 EXTRACT_NUMBER_AND_INCR(mcnt, p);
3847 DEBUG_PRINT2("EXECUTING maybe_pop_jump %d.\n", mcnt);
3848 {
3849 register unsigned char *p2 = p;
3850
3851 /* Compare the beginning of the repeat with what in the
3852 * pattern follows its end. If we can establish that there
3853 * is nothing that they would both match, i.e., that we
3854 * would have to backtrack because of (as in, e.g., `a*a')
3855 * then we can change to pop_failure_jump, because we'll
3856 * never have to backtrack.
3857 *
3858 * This is not true in the case of alternatives: in
3859 * `(a|ab)*' we do need to backtrack to the `ab' alternative
3860 * (e.g., if the string was `ab'). But instead of trying to
3861 * detect that here, the alternative has put on a dummy
3862 * failure point which is what we will end up popping. */
3863
3864 /* Skip over open/close-group commands. */
3865 while (p2 + 2 < pend
3866 && ((re_opcode_t) * p2 == stop_memory
3867 || (re_opcode_t) * p2 == start_memory))
3868 p2 += 3; /* Skip over args, too. */
3869
3870 /* If we're at the end of the pattern, we can change. */
3871 if (p2 == pend) {
3872 /* Consider what happens when matching ":\(.*\)"
3873 * against ":/". I don't really understand this code
3874 * yet. */
3875 p[-3] = (unsigned char) pop_failure_jump;
3876 DEBUG_PRINT1
3877 (" End of pattern: change to `pop_failure_jump'.\n");
3878 } else if ((re_opcode_t) * p2 == exactn
3879 || (bufp->newline_anchor && (re_opcode_t) * p2 == endline)) {
3880 register unsigned char c
3881 = *p2 == (unsigned char) endline ? '\n' : p2[2];
3882 p1 = p + mcnt;
3883
3884 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
3885 * to the `maybe_finalize_jump' of this case. Examine what
3886 * follows. */
3887 if ((re_opcode_t) p1[3] == exactn && p1[5] != c) {
3888 p[-3] = (unsigned char) pop_failure_jump;
3889 DEBUG_PRINT3(" %c != %c => pop_failure_jump.\n",
3890 c, p1[5]);
3891 } else if ((re_opcode_t) p1[3] == charset
3892 || (re_opcode_t) p1[3] == charset_not) {
3893 int not = (re_opcode_t) p1[3] == charset_not;
3894
3895 if (c < (unsigned char) (p1[4] * BYTEWIDTH)
3896 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
3897 not = !not;
3898
3899 /* `not' is equal to 1 if c would match, which means
3900 * that we can't change to pop_failure_jump. */
3901 if (!not) {
3902 p[-3] = (unsigned char) pop_failure_jump;
3903 DEBUG_PRINT1(" No match => pop_failure_jump.\n");
3904 }
3905 }
3906 }
3907 }
3908 p -= 2; /* Point at relative address again. */
3909 if ((re_opcode_t) p[-1] != pop_failure_jump) {
3910 p[-1] = (unsigned char) jump;
3911 DEBUG_PRINT1(" Match => jump.\n");
3912 goto unconditional_jump;
3913 }
3914 /* Note fall through. */
3915
3916
3917 /* The end of a simple repeat has a pop_failure_jump back to
3918 * its matching on_failure_jump, where the latter will push a
3919 * failure point. The pop_failure_jump takes off failure
3920 * points put on by this pop_failure_jump's matching
3921 * on_failure_jump; we got through the pattern to here from the
3922 * matching on_failure_jump, so didn't fail. */
3923 case pop_failure_jump:
3924 {
3925 /* We need to pass separate storage for the lowest and
3926 * highest registers, even though we don't care about the
3927 * actual values. Otherwise, we will restore only one
3928 * register from the stack, since lowest will == highest in
3929 * `pop_failure_point'. */
3930 unsigned long dummy_low_reg, dummy_high_reg;
3931 unsigned char *pdummy;
3932 const char *sdummy;
3933
3934 DEBUG_PRINT1("EXECUTING pop_failure_jump.\n");
3935 POP_FAILURE_POINT(sdummy, pdummy,
3936 dummy_low_reg, dummy_high_reg,
3937 reg_dummy, reg_dummy, reg_info_dummy);
3938 }
3939 /* Note fall through. */
3940
3941
3942 /* Unconditionally jump (without popping any failure points). */
3943 case jump:
3944 unconditional_jump:
3945 EXTRACT_NUMBER_AND_INCR(mcnt, p); /* Get the amount to jump. */
3946 DEBUG_PRINT2("EXECUTING jump %d ", mcnt);
3947 p += mcnt; /* Do the jump. */
3948 DEBUG_PRINT2("(to 0x%x).\n", p);
3949 break;
3950
3951
3952 /* We need this opcode so we can detect where alternatives end
3953 * in `group_match_null_string_p' et al. */
3954 case jump_past_alt:
3955 DEBUG_PRINT1("EXECUTING jump_past_alt.\n");
3956 goto unconditional_jump;
3957
3958
3959 /* Normally, the on_failure_jump pushes a failure point, which
3960 * then gets popped at pop_failure_jump. We will end up at
3961 * pop_failure_jump, also, and with a pattern of, say, `a+', we
3962 * are skipping over the on_failure_jump, so we have to push
3963 * something meaningless for pop_failure_jump to pop. */
3964 case dummy_failure_jump:
3965 DEBUG_PRINT1("EXECUTING dummy_failure_jump.\n");
3966 /* It doesn't matter what we push for the string here. What
3967 * the code at `fail' tests is the value for the pattern. */
3968 PUSH_FAILURE_POINT(0, 0, -2);
3969 goto unconditional_jump;
3970
3971
3972 /* At the end of an alternative, we need to push a dummy failure
3973 * point in case we are followed by a `pop_failure_jump', because
3974 * we don't want the failure point for the alternative to be
3975 * popped. For example, matching `(a|ab)*' against `aab'
3976 * requires that we match the `ab' alternative. */
3977 case push_dummy_failure:
3978 DEBUG_PRINT1("EXECUTING push_dummy_failure.\n");
3979 /* See comments just above at `dummy_failure_jump' about the
3980 * two zeroes. */
3981 PUSH_FAILURE_POINT(0, 0, -2);
3982 break;
3983
3984 /* Have to succeed matching what follows at least n times.
3985 * After that, handle like `on_failure_jump'. */
3986 case succeed_n:
3987 EXTRACT_NUMBER(mcnt, p + 2);
3988 DEBUG_PRINT2("EXECUTING succeed_n %d.\n", mcnt);
3989
3990 assert(mcnt >= 0);
3991 /* Originally, this is how many times we HAVE to succeed. */
3992 if (mcnt > 0) {
3993 mcnt--;
3994 p += 2;
3995 STORE_NUMBER_AND_INCR(p, mcnt);
3996 DEBUG_PRINT3(" Setting 0x%x to %d.\n", p, mcnt);
3997 } else if (mcnt == 0) {
3998 DEBUG_PRINT2(" Setting two bytes from 0x%x to no_op.\n", p + 2);
3999 p[2] = (unsigned char) no_op;
4000 p[3] = (unsigned char) no_op;
4001 goto on_failure;
4002 }
4003 break;
4004
4005 case jump_n:
4006 EXTRACT_NUMBER(mcnt, p + 2);
4007 DEBUG_PRINT2("EXECUTING jump_n %d.\n", mcnt);
4008
4009 /* Originally, this is how many times we CAN jump. */
4010 if (mcnt) {
4011 mcnt--;
4012 STORE_NUMBER(p + 2, mcnt);
4013 goto unconditional_jump;
4014 }
4015 /* If don't have to jump any more, skip over the rest of command. */
4016 else
4017 p += 4;
4018 break;
4019
4020 case set_number_at:
4021 {
4022 DEBUG_PRINT1("EXECUTING set_number_at.\n");
4023
4024 EXTRACT_NUMBER_AND_INCR(mcnt, p);
4025 p1 = p + mcnt;
4026 EXTRACT_NUMBER_AND_INCR(mcnt, p);
4027 DEBUG_PRINT3(" Setting 0x%x to %d.\n", p1, mcnt);
4028 STORE_NUMBER(p1, mcnt);
4029 break;
4030 }
4031
4032 case wordbound:
4033 DEBUG_PRINT1("EXECUTING wordbound.\n");
4034 if (AT_WORD_BOUNDARY(d))
4035 break;
4036 goto fail;
4037
4038 case notwordbound:
4039 DEBUG_PRINT1("EXECUTING notwordbound.\n");
4040 if (AT_WORD_BOUNDARY(d))
4041 goto fail;
4042 break;
4043
4044 case wordbeg:
4045 DEBUG_PRINT1("EXECUTING wordbeg.\n");
4046 if (WORDCHAR_P(d) && (AT_STRINGS_BEG(d) || !WORDCHAR_P(d - 1)))
4047 break;
4048 goto fail;
4049
4050 case wordend:
4051 DEBUG_PRINT1("EXECUTING wordend.\n");
4052 if (!AT_STRINGS_BEG(d) && WORDCHAR_P(d - 1)
4053 && (!WORDCHAR_P(d) || AT_STRINGS_END(d)))
4054 break;
4055 goto fail;
4056
4057 #ifdef emacs
4058 #ifdef emacs19
4059 case before_dot:
4060 DEBUG_PRINT1("EXECUTING before_dot.\n");
4061 if (PTR_CHAR_POS((unsigned char *) d) >= point)
4062 goto fail;
4063 break;
4064
4065 case at_dot:
4066 DEBUG_PRINT1("EXECUTING at_dot.\n");
4067 if (PTR_CHAR_POS((unsigned char *) d) != point)
4068 goto fail;
4069 break;
4070
4071 case after_dot:
4072 DEBUG_PRINT1("EXECUTING after_dot.\n");
4073 if (PTR_CHAR_POS((unsigned char *) d) <= point)
4074 goto fail;
4075 break;
4076 #else /* not emacs19 */
4077 case at_dot:
4078 DEBUG_PRINT1("EXECUTING at_dot.\n");
4079 if (PTR_CHAR_POS((unsigned char *) d) + 1 != point)
4080 goto fail;
4081 break;
4082 #endif /* not emacs19 */
4083
4084 case syntaxspec:
4085 DEBUG_PRINT2("EXECUTING syntaxspec %d.\n", mcnt);
4086 mcnt = *p++;
4087 goto matchsyntax;
4088
4089 case wordchar:
4090 DEBUG_PRINT1("EXECUTING Emacs wordchar.\n");
4091 mcnt = (int) Sword;
4092 matchsyntax:
4093 PREFETCH();
4094 if (SYNTAX(*d++) != (enum syntaxcode) mcnt)
4095 goto fail;
4096 SET_REGS_MATCHED();
4097 break;
4098
4099 case notsyntaxspec:
4100 DEBUG_PRINT2("EXECUTING notsyntaxspec %d.\n", mcnt);
4101 mcnt = *p++;
4102 goto matchnotsyntax;
4103
4104 case notwordchar:
4105 DEBUG_PRINT1("EXECUTING Emacs notwordchar.\n");
4106 mcnt = (int) Sword;
4107 matchnotsyntax:
4108 PREFETCH();
4109 if (SYNTAX(*d++) == (enum syntaxcode) mcnt)
4110 goto fail;
4111 SET_REGS_MATCHED();
4112 break;
4113
4114 #else /* not emacs */
4115 case wordchar:
4116 DEBUG_PRINT1("EXECUTING non-Emacs wordchar.\n");
4117 PREFETCH();
4118 if (!WORDCHAR_P(d))
4119 goto fail;
4120 SET_REGS_MATCHED();
4121 d++;
4122 break;
4123
4124 case notwordchar:
4125 DEBUG_PRINT1("EXECUTING non-Emacs notwordchar.\n");
4126 PREFETCH();
4127 if (WORDCHAR_P(d))
4128 goto fail;
4129 SET_REGS_MATCHED();
4130 d++;
4131 break;
4132 #endif /* not emacs */
4133
4134 default:
4135 abort();
4136 }
4137 continue; /* Successfully executed one pattern command; keep going. */
4138
4139
4140 /* We goto here if a matching operation fails. */
4141 fail:
4142 if (!FAIL_STACK_EMPTY()) { /* A restart point is known. Restore to that state. */
4143 DEBUG_PRINT1("\nFAIL:\n");
4144 POP_FAILURE_POINT(d, p,
4145 lowest_active_reg, highest_active_reg,
4146 regstart, regend, reg_info);
4147
4148 /* If this failure point is a dummy, try the next one. */
4149 if (!p)
4150 goto fail;
4151
4152 /* If we failed to the end of the pattern, don't examine *p. */
4153 assert(p <= pend);
4154 if (p < pend) {
4155 boolean is_a_jump_n = false;
4156
4157 /* If failed to a backwards jump that's part of a repetition
4158 * loop, need to pop this failure point and use the next one. */
4159 switch ((re_opcode_t) * p) {
4160 case jump_n:
4161 is_a_jump_n = true;
4162 case maybe_pop_jump:
4163 case pop_failure_jump:
4164 case jump:
4165 p1 = p + 1;
4166 EXTRACT_NUMBER_AND_INCR(mcnt, p1);
4167 p1 += mcnt;
4168
4169 if ((is_a_jump_n && (re_opcode_t) * p1 == succeed_n)
4170 || (!is_a_jump_n
4171 && (re_opcode_t) * p1 == on_failure_jump))
4172 goto fail;
4173 break;
4174 default:
4175 /* do nothing */ ;
4176 }
4177 }
4178 if (d >= string1 && d <= end1)
4179 dend = end_match_1;
4180 } else
4181 break; /* Matching at this starting point really fails. */
4182 } /* for (;;) */
4183
4184 if (best_regs_set)
4185 goto restore_best_regs;
4186
4187 FREE_VARIABLES();
4188
4189 return -1; /* Failure to match. */
4190 } /* re_match_2 */
4191
4192 /* Subroutine definitions for re_match_2. */
4193
4194
4195 /* We are passed P pointing to a register number after a start_memory.
4196 *
4197 * Return true if the pattern up to the corresponding stop_memory can
4198 * match the empty string, and false otherwise.
4199 *
4200 * If we find the matching stop_memory, sets P to point to one past its number.
4201 * Otherwise, sets P to an undefined byte less than or equal to END.
4202 *
4203 * We don't handle duplicates properly (yet). */
4204
4205 static boolean
group_match_null_string_p(p,end,reg_info)4206 group_match_null_string_p(p, end, reg_info)
4207 unsigned char **p, *end;
4208 register_info_type *reg_info;
4209 {
4210 int mcnt;
4211 /* Point to after the args to the start_memory. */
4212 unsigned char *p1 = *p + 2;
4213
4214 while (p1 < end) {
4215 /* Skip over opcodes that can match nothing, and return true or
4216 * false, as appropriate, when we get to one that can't, or to the
4217 * matching stop_memory. */
4218
4219 switch ((re_opcode_t) * p1) {
4220 /* Could be either a loop or a series of alternatives. */
4221 case on_failure_jump:
4222 p1++;
4223 EXTRACT_NUMBER_AND_INCR(mcnt, p1);
4224
4225 /* If the next operation is not a jump backwards in the
4226 * pattern. */
4227
4228 if (mcnt >= 0) {
4229 /* Go through the on_failure_jumps of the alternatives,
4230 * seeing if any of the alternatives cannot match nothing.
4231 * The last alternative starts with only a jump,
4232 * whereas the rest start with on_failure_jump and end
4233 * with a jump, e.g., here is the pattern for `a|b|c':
4234 *
4235 * /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
4236 * /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
4237 * /exactn/1/c
4238 *
4239 * So, we have to first go through the first (n-1)
4240 * alternatives and then deal with the last one separately. */
4241
4242
4243 /* Deal with the first (n-1) alternatives, which start
4244 * with an on_failure_jump (see above) that jumps to right
4245 * past a jump_past_alt. */
4246
4247 while ((re_opcode_t) p1[mcnt - 3] == jump_past_alt) {
4248 /* `mcnt' holds how many bytes long the alternative
4249 * is, including the ending `jump_past_alt' and
4250 * its number. */
4251
4252 if (!alt_match_null_string_p(p1, p1 + mcnt - 3,
4253 reg_info))
4254 return false;
4255
4256 /* Move to right after this alternative, including the
4257 * jump_past_alt. */
4258 p1 += mcnt;
4259
4260 /* Break if it's the beginning of an n-th alternative
4261 * that doesn't begin with an on_failure_jump. */
4262 if ((re_opcode_t) * p1 != on_failure_jump)
4263 break;
4264
4265 /* Still have to check that it's not an n-th
4266 * alternative that starts with an on_failure_jump. */
4267 p1++;
4268 EXTRACT_NUMBER_AND_INCR(mcnt, p1);
4269 if ((re_opcode_t) p1[mcnt - 3] != jump_past_alt) {
4270 /* Get to the beginning of the n-th alternative. */
4271 p1 -= 3;
4272 break;
4273 }
4274 }
4275
4276 /* Deal with the last alternative: go back and get number
4277 * of the `jump_past_alt' just before it. `mcnt' contains
4278 * the length of the alternative. */
4279 EXTRACT_NUMBER(mcnt, p1 - 2);
4280
4281 if (!alt_match_null_string_p(p1, p1 + mcnt, reg_info))
4282 return false;
4283
4284 p1 += mcnt; /* Get past the n-th alternative. */
4285 } /* if mcnt > 0 */
4286 break;
4287
4288
4289 case stop_memory:
4290 assert(p1[1] == **p);
4291 *p = p1 + 2;
4292 return true;
4293
4294
4295 default:
4296 if (!common_op_match_null_string_p(&p1, end, reg_info))
4297 return false;
4298 }
4299 } /* while p1 < end */
4300
4301 return false;
4302 } /* group_match_null_string_p */
4303
4304
4305 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
4306 * It expects P to be the first byte of a single alternative and END one
4307 * byte past the last. The alternative can contain groups. */
4308
4309 static boolean
alt_match_null_string_p(p,end,reg_info)4310 alt_match_null_string_p(p, end, reg_info)
4311 unsigned char *p, *end;
4312 register_info_type *reg_info;
4313 {
4314 int mcnt;
4315 unsigned char *p1 = p;
4316
4317 while (p1 < end) {
4318 /* Skip over opcodes that can match nothing, and break when we get
4319 * to one that can't. */
4320
4321 switch ((re_opcode_t) * p1) {
4322 /* It's a loop. */
4323 case on_failure_jump:
4324 p1++;
4325 EXTRACT_NUMBER_AND_INCR(mcnt, p1);
4326 p1 += mcnt;
4327 break;
4328
4329 default:
4330 if (!common_op_match_null_string_p(&p1, end, reg_info))
4331 return false;
4332 }
4333 } /* while p1 < end */
4334
4335 return true;
4336 } /* alt_match_null_string_p */
4337
4338
4339 /* Deals with the ops common to group_match_null_string_p and
4340 * alt_match_null_string_p.
4341 *
4342 * Sets P to one after the op and its arguments, if any. */
4343
4344 static boolean
common_op_match_null_string_p(p,end,reg_info)4345 common_op_match_null_string_p(p, end, reg_info)
4346 unsigned char **p, *end;
4347 register_info_type *reg_info;
4348 {
4349 int mcnt;
4350 boolean ret;
4351 int reg_no;
4352 unsigned char *p1 = *p;
4353
4354 switch ((re_opcode_t) * p1++) {
4355 case no_op:
4356 case begline:
4357 case endline:
4358 case begbuf:
4359 case endbuf:
4360 case wordbeg:
4361 case wordend:
4362 case wordbound:
4363 case notwordbound:
4364 #ifdef emacs
4365 case before_dot:
4366 case at_dot:
4367 case after_dot:
4368 #endif
4369 break;
4370
4371 case start_memory:
4372 reg_no = *p1;
4373 assert(reg_no > 0 && reg_no <= MAX_REGNUM);
4374 ret = group_match_null_string_p(&p1, end, reg_info);
4375
4376 /* Have to set this here in case we're checking a group which
4377 * contains a group and a back reference to it. */
4378
4379 if (REG_MATCH_NULL_STRING_P(reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
4380 REG_MATCH_NULL_STRING_P(reg_info[reg_no]) = ret;
4381
4382 if (!ret)
4383 return false;
4384 break;
4385
4386 /* If this is an optimized succeed_n for zero times, make the jump. */
4387 case jump:
4388 EXTRACT_NUMBER_AND_INCR(mcnt, p1);
4389 if (mcnt >= 0)
4390 p1 += mcnt;
4391 else
4392 return false;
4393 break;
4394
4395 case succeed_n:
4396 /* Get to the number of times to succeed. */
4397 p1 += 2;
4398 EXTRACT_NUMBER_AND_INCR(mcnt, p1);
4399
4400 if (mcnt == 0) {
4401 p1 -= 4;
4402 EXTRACT_NUMBER_AND_INCR(mcnt, p1);
4403 p1 += mcnt;
4404 } else
4405 return false;
4406 break;
4407
4408 case duplicate:
4409 if (!REG_MATCH_NULL_STRING_P(reg_info[*p1]))
4410 return false;
4411 break;
4412
4413 case set_number_at:
4414 p1 += 4;
4415
4416 default:
4417 /* All other opcodes mean we cannot match the empty string. */
4418 return false;
4419 }
4420
4421 *p = p1;
4422 return true;
4423 } /* common_op_match_null_string_p */
4424
4425
4426 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
4427 * bytes; nonzero otherwise. */
4428
4429 static int
bcmp_translate(s1,s2,len,translate)4430 bcmp_translate(s1, s2, len, translate)
4431 unsigned char *s1, *s2;
4432 register int len;
4433 char *translate;
4434 {
4435 register unsigned char *p1 = s1, *p2 = s2;
4436 while (len) {
4437 if (translate[*p1++] != translate[*p2++])
4438 return 1;
4439 len--;
4440 }
4441 return 0;
4442 }
4443
4444 /* Entry points for GNU code. */
4445
4446 /* re_compile_pattern is the GNU regular expression compiler: it
4447 * compiles PATTERN (of length SIZE) and puts the result in BUFP.
4448 * Returns 0 if the pattern was valid, otherwise an error string.
4449 *
4450 * Assumes the `allocated' (and perhaps `buffer') and `translate' fields
4451 * are set in BUFP on entry.
4452 *
4453 * We call regex_compile to do the actual compilation. */
4454
4455 const char *
re_compile_pattern(pattern,length,bufp)4456 re_compile_pattern(pattern, length, bufp)
4457 const char *pattern;
4458 int length;
4459 struct re_pattern_buffer *bufp;
4460 {
4461 reg_errcode_t ret;
4462
4463 /* GNU code is written to assume at least RE_NREGS registers will be set
4464 * (and at least one extra will be -1). */
4465 bufp->regs_allocated = REGS_UNALLOCATED;
4466
4467 /* And GNU code determines whether or not to get register information
4468 * by passing null for the REGS argument to re_match, etc., not by
4469 * setting no_sub. */
4470 bufp->no_sub = 0;
4471
4472 /* Match anchors at newline. */
4473 bufp->newline_anchor = 1;
4474
4475 ret = regex_compile(pattern, length, re_syntax_options, bufp);
4476
4477 return re_error_msg[(int) ret];
4478 }
4479
4480 /* Entry points compatible with 4.2 BSD regex library. We don't define
4481 * them if this is an Emacs or POSIX compilation. */
4482
4483 #if !defined (emacs) && !defined (_POSIX_SOURCE)
4484
4485 /* BSD has one and only one pattern buffer. */
4486 static struct re_pattern_buffer re_comp_buf;
4487
4488 char *
re_comp(s)4489 re_comp(s)
4490 const char *s;
4491 {
4492 reg_errcode_t ret;
4493
4494 if (!s) {
4495 if (!re_comp_buf.buffer)
4496 return "No previous regular expression";
4497 return 0;
4498 }
4499 if (!re_comp_buf.buffer) {
4500 re_comp_buf.buffer = (unsigned char *) malloc(200);
4501 if (re_comp_buf.buffer == NULL)
4502 return "Memory exhausted";
4503 re_comp_buf.allocated = 200;
4504
4505 re_comp_buf.fastmap = (char *) malloc(1 << BYTEWIDTH);
4506 if (re_comp_buf.fastmap == NULL)
4507 return "Memory exhausted";
4508 }
4509 /* Since `re_exec' always passes NULL for the `regs' argument, we
4510 * don't need to initialize the pattern buffer fields which affect it. */
4511
4512 /* Match anchors at newlines. */
4513 re_comp_buf.newline_anchor = 1;
4514
4515 ret = regex_compile(s, strlen(s), re_syntax_options, &re_comp_buf);
4516
4517 /* Yes, we're discarding `const' here. */
4518 return (char *) re_error_msg[(int) ret];
4519 }
4520
4521
4522 int
re_exec(s)4523 re_exec(s)
4524 const char *s;
4525 {
4526 const int len = strlen(s);
4527 return
4528 0 <= re_search(&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
4529 }
4530
4531 #endif /* not emacs and not _POSIX_SOURCE */
4532
4533 /* POSIX.2 functions. Don't define these for Emacs. */
4534
4535 #ifndef emacs
4536
4537 /* regcomp takes a regular expression as a string and compiles it.
4538 *
4539 * PREG is a regex_t *. We do not expect any fields to be initialized,
4540 * since POSIX says we shouldn't. Thus, we set
4541 *
4542 * `buffer' to the compiled pattern;
4543 * `used' to the length of the compiled pattern;
4544 * `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
4545 * REG_EXTENDED bit in CFLAGS is set; otherwise, to
4546 * RE_SYNTAX_POSIX_BASIC;
4547 * `newline_anchor' to REG_NEWLINE being set in CFLAGS;
4548 * `fastmap' and `fastmap_accurate' to zero;
4549 * `re_nsub' to the number of subexpressions in PATTERN.
4550 *
4551 * PATTERN is the address of the pattern string.
4552 *
4553 * CFLAGS is a series of bits which affect compilation.
4554 *
4555 * If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
4556 * use POSIX basic syntax.
4557 *
4558 * If REG_NEWLINE is set, then . and [^...] don't match newline.
4559 * Also, regexec will try a match beginning after every newline.
4560 *
4561 * If REG_ICASE is set, then we considers upper- and lowercase
4562 * versions of letters to be equivalent when matching.
4563 *
4564 * If REG_NOSUB is set, then when PREG is passed to regexec, that
4565 * routine will report only success or failure, and nothing about the
4566 * registers.
4567 *
4568 * It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
4569 * the return codes and their meanings.) */
4570
4571 int
regcomp(preg,pattern,cflags)4572 regcomp(preg, pattern, cflags)
4573 regex_t *preg;
4574 const char *pattern;
4575 int cflags;
4576 {
4577 reg_errcode_t ret;
4578 unsigned syntax
4579 = (cflags & REG_EXTENDED) ?
4580 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
4581
4582 /* regex_compile will allocate the space for the compiled pattern. */
4583 preg->buffer = 0;
4584 preg->allocated = 0;
4585
4586 /* Don't bother to use a fastmap when searching. This simplifies the
4587 * REG_NEWLINE case: if we used a fastmap, we'd have to put all the
4588 * characters after newlines into the fastmap. This way, we just try
4589 * every character. */
4590 preg->fastmap = 0;
4591
4592 if (cflags & REG_ICASE) {
4593 unsigned i;
4594
4595 preg->translate = (char *) malloc(CHAR_SET_SIZE);
4596 if (preg->translate == NULL)
4597 return (int) REG_ESPACE;
4598
4599 /* Map uppercase characters to corresponding lowercase ones. */
4600 for (i = 0; i < CHAR_SET_SIZE; i++)
4601 preg->translate[i] = ISUPPER(i) ? tolower(i) : i;
4602 } else
4603 preg->translate = NULL;
4604
4605 /* If REG_NEWLINE is set, newlines are treated differently. */
4606 if (cflags & REG_NEWLINE) { /* REG_NEWLINE implies neither . nor [^...] match newline. */
4607 syntax &= ~RE_DOT_NEWLINE;
4608 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
4609 /* It also changes the matching behavior. */
4610 preg->newline_anchor = 1;
4611 } else
4612 preg->newline_anchor = 0;
4613
4614 preg->no_sub = !!(cflags & REG_NOSUB);
4615
4616 /* POSIX says a null character in the pattern terminates it, so we
4617 * can use strlen here in compiling the pattern. */
4618 ret = regex_compile(pattern, strlen(pattern), syntax, preg);
4619
4620 /* POSIX doesn't distinguish between an unmatched open-group and an
4621 * unmatched close-group: both are REG_EPAREN. */
4622 if (ret == REG_ERPAREN)
4623 ret = REG_EPAREN;
4624
4625 return (int) ret;
4626 }
4627
4628
4629 /* regexec searches for a given pattern, specified by PREG, in the
4630 * string STRING.
4631 *
4632 * If NMATCH is zero or REG_NOSUB was set in the cflags argument to
4633 * `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
4634 * least NMATCH elements, and we set them to the offsets of the
4635 * corresponding matched substrings.
4636 *
4637 * EFLAGS specifies `execution flags' which affect matching: if
4638 * REG_NOTBOL is set, then ^ does not match at the beginning of the
4639 * string; if REG_NOTEOL is set, then $ does not match at the end.
4640 *
4641 * We return 0 if we find a match and REG_NOMATCH if not. */
4642
4643 int
regexec(preg,string,nmatch,pmatch,eflags)4644 regexec(preg, string, nmatch, pmatch, eflags)
4645 const regex_t *preg;
4646 const char *string;
4647 size_t nmatch;
4648 regmatch_t pmatch[];
4649 int eflags;
4650 {
4651 int ret;
4652 struct re_registers regs;
4653 regex_t private_preg;
4654 int len = strlen(string);
4655 boolean want_reg_info = !preg->no_sub && nmatch > 0;
4656
4657 private_preg = *preg;
4658
4659 private_preg.not_bol = !!(eflags & REG_NOTBOL);
4660 private_preg.not_eol = !!(eflags & REG_NOTEOL);
4661
4662 /* The user has told us exactly how many registers to return
4663 * information about, via `nmatch'. We have to pass that on to the
4664 * matching routines. */
4665 private_preg.regs_allocated = REGS_FIXED;
4666
4667 if (want_reg_info) {
4668 regs.num_regs = nmatch;
4669 regs.start = TALLOC(nmatch, regoff_t);
4670 if (regs.start == NULL)
4671 return (int) REG_NOMATCH;
4672 regs.end = TALLOC(nmatch, regoff_t);
4673 if (regs.end == NULL) {
4674 free(regs.start);
4675 return (int) REG_NOMATCH;
4676 }
4677 }
4678 /* Perform the searching operation. */
4679 ret = re_search(&private_preg, string, len,
4680 /* start: */ 0, /* range: */ len,
4681 want_reg_info ? ®s : (struct re_registers *) 0);
4682
4683 /* Copy the register information to the POSIX structure. */
4684 if (want_reg_info) {
4685 if (ret >= 0) {
4686 unsigned r;
4687
4688 for (r = 0; r < nmatch; r++) {
4689 pmatch[r].rm_so = regs.start[r];
4690 pmatch[r].rm_eo = regs.end[r];
4691 }
4692 }
4693 /* If we needed the temporary register info, free the space now. */
4694 free(regs.start);
4695 free(regs.end);
4696 }
4697 /* We want zero return to mean success, unlike `re_search'. */
4698 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
4699 }
4700
4701
4702 /* Returns a message corresponding to an error code, ERRCODE, returned
4703 * from either regcomp or regexec. We don't use PREG here. */
4704
4705 size_t
regerror(errcode,preg,errbuf,errbuf_size)4706 regerror(errcode, preg, errbuf, errbuf_size)
4707 int errcode;
4708 const regex_t *preg;
4709 char *errbuf;
4710 size_t errbuf_size;
4711 {
4712 const char *msg;
4713 size_t msg_size;
4714
4715 if (errcode < 0
4716 || errcode >= (sizeof(re_error_msg) / sizeof(re_error_msg[0])))
4717 /* Only error codes returned by the rest of the code should be passed
4718 * to this routine. If we are given anything else, or if other regex
4719 * code generates an invalid error code, then the program has a bug.
4720 * Dump core so we can fix it. */
4721 abort();
4722
4723 msg = re_error_msg[errcode];
4724
4725 /* POSIX doesn't require that we do anything in this case, but why
4726 * not be nice. */
4727 if (!msg)
4728 msg = "Success";
4729
4730 msg_size = strlen(msg) + 1; /* Includes the null. */
4731
4732 if (errbuf_size != 0) {
4733 if (msg_size > errbuf_size) {
4734 strncpy(errbuf, msg, errbuf_size - 1);
4735 errbuf[errbuf_size - 1] = 0;
4736 } else
4737 strcpy(errbuf, msg);
4738 }
4739 return msg_size;
4740 }
4741
4742
4743 /* Free dynamically allocated space used by PREG. */
4744
4745 void
regfree(preg)4746 regfree(preg)
4747 regex_t *preg;
4748 {
4749 if (preg->buffer != NULL)
4750 free(preg->buffer);
4751 preg->buffer = NULL;
4752
4753 preg->allocated = 0;
4754 preg->used = 0;
4755
4756 if (preg->fastmap != NULL)
4757 free(preg->fastmap);
4758 preg->fastmap = NULL;
4759 preg->fastmap_accurate = 0;
4760
4761 if (preg->translate != NULL)
4762 free(preg->translate);
4763 preg->translate = NULL;
4764 }
4765
4766 #endif /* not emacs */
4767
4768 /*
4769 * Local variables:
4770 * make-backup-files: t
4771 * version-control: t
4772 * trim-versions-without-asking: nil
4773 * End:
4774 */
4775