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 	    return REG_ESPACE;
1155 
1156 	bufp->allocated = INIT_BUF_SIZE;
1157     }
1158     begalt = b = bufp->buffer;
1159 
1160     /* Loop through the uncompiled pattern until we're at the end.  */
1161     while (p != pend) {
1162 	PATFETCH(c);
1163 
1164 	switch (c) {
1165 	case '^':
1166 	    {
1167 		if (		/* If at start of pattern, it's an operator.  */
1168 		    p == pattern + 1
1169 		/* If context independent, it's an operator.  */
1170 		    || syntax & RE_CONTEXT_INDEP_ANCHORS
1171 		/* Otherwise, depends on what's come before.  */
1172 		    || at_begline_loc_p(pattern, p, syntax))
1173 		    BUF_PUSH(begline);
1174 		else
1175 		    goto normal_char;
1176 	    }
1177 	    break;
1178 
1179 
1180 	case '$':
1181 	    {
1182 		if (		/* If at end of pattern, it's an operator.  */
1183 		    p == pend
1184 		/* If context independent, it's an operator.  */
1185 		    || syntax & RE_CONTEXT_INDEP_ANCHORS
1186 		/* Otherwise, depends on what's next.  */
1187 		    || at_endline_loc_p(p, pend, syntax))
1188 		    BUF_PUSH(endline);
1189 		else
1190 		    goto normal_char;
1191 	    }
1192 	    break;
1193 
1194 
1195 	case '+':
1196 	case '?':
1197 	    if ((syntax & RE_BK_PLUS_QM)
1198 		|| (syntax & RE_LIMITED_OPS))
1199 		goto normal_char;
1200 	  handle_plus:
1201 	case '*':
1202 	    /* If there is no previous pattern... */
1203 	    if (!laststart) {
1204 		if (syntax & RE_CONTEXT_INVALID_OPS)
1205 		    return REG_BADRPT;
1206 		else if (!(syntax & RE_CONTEXT_INDEP_OPS))
1207 		    goto normal_char;
1208 	    } {
1209 		/* Are we optimizing this jump?  */
1210 		boolean keep_string_p = false;
1211 
1212 		/* 1 means zero (many) matches is allowed.  */
1213 		char zero_times_ok = 0, many_times_ok = 0;
1214 
1215 		/* If there is a sequence of repetition chars, collapse it
1216 		 * down to just one (the right one).  We can't combine
1217 		 * interval operators with these because of, e.g., `a{2}*',
1218 		 * which should only match an even number of `a's.  */
1219 
1220 		for (;;) {
1221 		    zero_times_ok |= c != '+';
1222 		    many_times_ok |= c != '?';
1223 
1224 		    if (p == pend)
1225 			break;
1226 
1227 		    PATFETCH(c);
1228 
1229 		    if (c == '*'
1230 			|| (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')));
1231 
1232 		    else if (syntax & RE_BK_PLUS_QM && c == '\\') {
1233 			if (p == pend)
1234 			    return REG_EESCAPE;
1235 
1236 			PATFETCH(c1);
1237 			if (!(c1 == '+' || c1 == '?')) {
1238 			    PATUNFETCH;
1239 			    PATUNFETCH;
1240 			    break;
1241 			}
1242 			c = c1;
1243 		    } else {
1244 			PATUNFETCH;
1245 			break;
1246 		    }
1247 
1248 		    /* If we get here, we found another repeat character.  */
1249 		}
1250 
1251 		/* Star, etc. applied to an empty pattern is equivalent
1252 		 * to an empty pattern.  */
1253 		if (!laststart)
1254 		    break;
1255 
1256 		/* Now we know whether or not zero matches is allowed
1257 		 * and also whether or not two or more matches is allowed.  */
1258 		if (many_times_ok) {	/* More than one repetition is allowed, so put in at the
1259 					 * end a backward relative jump from `b' to before the next
1260 					 * jump we're going to put in below (which jumps from
1261 					 * laststart to after this jump).
1262 					 *
1263 					 * But if we are at the `*' in the exact sequence `.*\n',
1264 					 * insert an unconditional jump backwards to the .,
1265 					 * instead of the beginning of the loop.  This way we only
1266 					 * push a failure point once, instead of every time
1267 					 * through the loop.  */
1268 		    assert(p - 1 > pattern);
1269 
1270 		    /* Allocate the space for the jump.  */
1271 		    GET_BUFFER_SPACE(3);
1272 
1273 		    /* We know we are not at the first character of the pattern,
1274 		     * because laststart was nonzero.  And we've already
1275 		     * incremented `p', by the way, to be the character after
1276 		     * the `*'.  Do we have to do something analogous here
1277 		     * for null bytes, because of RE_DOT_NOT_NULL?  */
1278 		    if (TRANSLATE(*(p - 2)) == TRANSLATE('.')
1279 			&& zero_times_ok
1280 			&& p < pend && TRANSLATE(*p) == TRANSLATE('\n')
1281 			&& !(syntax & RE_DOT_NEWLINE)) {	/* We have .*\n.  */
1282 			STORE_JUMP(jump, b, laststart);
1283 			keep_string_p = true;
1284 		    } else
1285 			/* Anything else.  */
1286 			STORE_JUMP(maybe_pop_jump, b, laststart - 3);
1287 
1288 		    /* We've added more stuff to the buffer.  */
1289 		    b += 3;
1290 		}
1291 		/* On failure, jump from laststart to b + 3, which will be the
1292 		 * end of the buffer after this jump is inserted.  */
1293 		GET_BUFFER_SPACE(3);
1294 		INSERT_JUMP(keep_string_p ? on_failure_keep_string_jump
1295 		    : on_failure_jump,
1296 		    laststart, b + 3);
1297 		pending_exact = 0;
1298 		b += 3;
1299 
1300 		if (!zero_times_ok) {
1301 		    /* At least one repetition is required, so insert a
1302 		     * `dummy_failure_jump' before the initial
1303 		     * `on_failure_jump' instruction of the loop. This
1304 		     * effects a skip over that instruction the first time
1305 		     * we hit that loop.  */
1306 		    GET_BUFFER_SPACE(3);
1307 		    INSERT_JUMP(dummy_failure_jump, laststart, laststart + 6);
1308 		    b += 3;
1309 		}
1310 	    }
1311 	    break;
1312 
1313 
1314 	case '.':
1315 	    laststart = b;
1316 	    BUF_PUSH(anychar);
1317 	    break;
1318 
1319 
1320 	case '[':
1321 	    {
1322 		boolean had_char_class = false;
1323 
1324 		if (p == pend)
1325 		    return REG_EBRACK;
1326 
1327 		/* Ensure that we have enough space to push a charset: the
1328 		 * opcode, the length count, and the bitset; 34 bytes in all.  */
1329 		GET_BUFFER_SPACE(34);
1330 
1331 		laststart = b;
1332 
1333 		/* We test `*p == '^' twice, instead of using an if
1334 		 * statement, so we only need one BUF_PUSH.  */
1335 		BUF_PUSH(*p == '^' ? charset_not : charset);
1336 		if (*p == '^')
1337 		    p++;
1338 
1339 		/* Remember the first position in the bracket expression.  */
1340 		p1 = p;
1341 
1342 		/* Push the number of bytes in the bitmap.  */
1343 		BUF_PUSH((1 << BYTEWIDTH) / BYTEWIDTH);
1344 
1345 		/* Clear the whole map.  */
1346 		bzero(b, (1 << BYTEWIDTH) / BYTEWIDTH);
1347 
1348 		/* charset_not matches newline according to a syntax bit.  */
1349 		if ((re_opcode_t) b[-2] == charset_not
1350 		    && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
1351 		    SET_LIST_BIT('\n');
1352 
1353 		/* Read in characters and ranges, setting map bits.  */
1354 		for (;;) {
1355 		    if (p == pend)
1356 			return REG_EBRACK;
1357 
1358 		    PATFETCH(c);
1359 
1360 		    /* \ might escape characters inside [...] and [^...].  */
1361 		    if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\') {
1362 			if (p == pend)
1363 			    return REG_EESCAPE;
1364 
1365 			PATFETCH(c1);
1366 			SET_LIST_BIT(c1);
1367 			continue;
1368 		    }
1369 		    /* Could be the end of the bracket expression.  If it's
1370 		     * not (i.e., when the bracket expression is `[]' so
1371 		     * far), the ']' character bit gets set way below.  */
1372 		    if (c == ']' && p != p1 + 1)
1373 			break;
1374 
1375 		    /* Look ahead to see if it's a range when the last thing
1376 		     * was a character class.  */
1377 		    if (had_char_class && c == '-' && *p != ']')
1378 			return REG_ERANGE;
1379 
1380 		    /* Look ahead to see if it's a range when the last thing
1381 		     * was a character: if this is a hyphen not at the
1382 		     * beginning or the end of a list, then it's the range
1383 		     * operator.  */
1384 		    if (c == '-'
1385 			&& !(p - 2 >= pattern && p[-2] == '[')
1386 			&& !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
1387 			&& *p != ']') {
1388 			reg_errcode_t ret
1389 			= compile_range(&p, pend, translate, syntax, b);
1390 			if (ret != REG_NOERROR)
1391 			    return ret;
1392 		    } else if (p[0] == '-' && p[1] != ']') {	/* This handles ranges made up of characters only.  */
1393 			reg_errcode_t ret;
1394 
1395 			/* Move past the `-'.  */
1396 			PATFETCH(c1);
1397 
1398 			ret = compile_range(&p, pend, translate, syntax, b);
1399 			if (ret != REG_NOERROR)
1400 			    return ret;
1401 		    }
1402 		    /* See if we're at the beginning of a possible character
1403 		     * class.  */
1404 
1405 		    else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':') {	/* Leave room for the null.  */
1406 			char str[CHAR_CLASS_MAX_LENGTH + 1];
1407 
1408 			PATFETCH(c);
1409 			c1 = 0;
1410 
1411 			/* If pattern is `[[:'.  */
1412 			if (p == pend)
1413 			    return REG_EBRACK;
1414 
1415 			for (;;) {
1416 			    PATFETCH(c);
1417 			    if (c == ':' || c == ']' || p == pend
1418 				|| c1 == CHAR_CLASS_MAX_LENGTH)
1419 				break;
1420 			    str[c1++] = c;
1421 			}
1422 			str[c1] = '\0';
1423 
1424 			/* If isn't a word bracketed by `[:' and:`]':
1425 			 * undo the ending character, the letters, and leave
1426 			 * the leading `:' and `[' (but set bits for them).  */
1427 			if (c == ':' && *p == ']') {
1428 			    int ch;
1429 			    boolean is_alnum = STREQ(str, "alnum");
1430 			    boolean is_alpha = STREQ(str, "alpha");
1431 			    boolean is_blank = STREQ(str, "blank");
1432 			    boolean is_cntrl = STREQ(str, "cntrl");
1433 			    boolean is_digit = STREQ(str, "digit");
1434 			    boolean is_graph = STREQ(str, "graph");
1435 			    boolean is_lower = STREQ(str, "lower");
1436 			    boolean is_print = STREQ(str, "print");
1437 			    boolean is_punct = STREQ(str, "punct");
1438 			    boolean is_space = STREQ(str, "space");
1439 			    boolean is_upper = STREQ(str, "upper");
1440 			    boolean is_xdigit = STREQ(str, "xdigit");
1441 
1442 			    if (!IS_CHAR_CLASS(str))
1443 				return REG_ECTYPE;
1444 
1445 			    /* Throw away the ] at the end of the character
1446 			     * class.  */
1447 			    PATFETCH(c);
1448 
1449 			    if (p == pend)
1450 				return REG_EBRACK;
1451 
1452 			    for (ch = 0; ch < 1 << BYTEWIDTH; ch++) {
1453 				if ((is_alnum && ISALNUM(ch))
1454 				    || (is_alpha && ISALPHA(ch))
1455 				    || (is_blank && ISBLANK(ch))
1456 				    || (is_cntrl && ISCNTRL(ch))
1457 				    || (is_digit && ISDIGIT(ch))
1458 				    || (is_graph && ISGRAPH(ch))
1459 				    || (is_lower && ISLOWER(ch))
1460 				    || (is_print && ISPRINT(ch))
1461 				    || (is_punct && ISPUNCT(ch))
1462 				    || (is_space && ISSPACE(ch))
1463 				    || (is_upper && ISUPPER(ch))
1464 				    || (is_xdigit && ISXDIGIT(ch)))
1465 				    SET_LIST_BIT(ch);
1466 			    }
1467 			    had_char_class = true;
1468 			} else {
1469 			    c1++;
1470 			    while (c1--)
1471 				PATUNFETCH;
1472 			    SET_LIST_BIT('[');
1473 			    SET_LIST_BIT(':');
1474 			    had_char_class = false;
1475 			}
1476 		    } else {
1477 			had_char_class = false;
1478 			SET_LIST_BIT(c);
1479 		    }
1480 		}
1481 
1482 		/* Discard any (non)matching list bytes that are all 0 at the
1483 		 * end of the map.  Decrease the map-length byte too.  */
1484 		while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
1485 		    b[-1]--;
1486 		b += b[-1];
1487 	    }
1488 	    break;
1489 
1490 
1491 	case '(':
1492 	    if (syntax & RE_NO_BK_PARENS)
1493 		goto handle_open;
1494 	    else
1495 		goto normal_char;
1496 
1497 
1498 	case ')':
1499 	    if (syntax & RE_NO_BK_PARENS)
1500 		goto handle_close;
1501 	    else
1502 		goto normal_char;
1503 
1504 
1505 	case '\n':
1506 	    if (syntax & RE_NEWLINE_ALT)
1507 		goto handle_alt;
1508 	    else
1509 		goto normal_char;
1510 
1511 
1512 	case '|':
1513 	    if (syntax & RE_NO_BK_VBAR)
1514 		goto handle_alt;
1515 	    else
1516 		goto normal_char;
1517 
1518 
1519 	case '{':
1520 	    if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
1521 		goto handle_interval;
1522 	    else
1523 		goto normal_char;
1524 
1525 
1526 	case '\\':
1527 	    if (p == pend)
1528 		return REG_EESCAPE;
1529 
1530 	    /* Do not translate the character after the \, so that we can
1531 	     * distinguish, e.g., \B from \b, even if we normally would
1532 	     * translate, e.g., B to b.  */
1533 	    PATFETCH_RAW(c);
1534 
1535 	    switch (c) {
1536 	    case '(':
1537 		if (syntax & RE_NO_BK_PARENS)
1538 		    goto normal_backslash;
1539 
1540 	      handle_open:
1541 		bufp->re_nsub++;
1542 		regnum++;
1543 
1544 		if (COMPILE_STACK_FULL) {
1545 		    RETALLOC(compile_stack.stack, compile_stack.size << 1,
1546 			compile_stack_elt_t);
1547 		    if (compile_stack.stack == NULL)
1548 			return REG_ESPACE;
1549 
1550 		    compile_stack.size <<= 1;
1551 		}
1552 		/* These are the values to restore when we hit end of this
1553 		 * group.  They are all relative offsets, so that if the
1554 		 * whole pattern moves because of realloc, they will still
1555 		 * be valid.  */
1556 		COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
1557 		COMPILE_STACK_TOP.fixup_alt_jump
1558 		    = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
1559 		COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
1560 		COMPILE_STACK_TOP.regnum = regnum;
1561 
1562 		/* We will eventually replace the 0 with the number of
1563 		 * groups inner to this one.  But do not push a
1564 		 * start_memory for groups beyond the last one we can
1565 		 * represent in the compiled pattern.  */
1566 		if (regnum <= MAX_REGNUM) {
1567 		    COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
1568 		    BUF_PUSH_3(start_memory, regnum, 0);
1569 		}
1570 		compile_stack.avail++;
1571 
1572 		fixup_alt_jump = 0;
1573 		laststart = 0;
1574 		begalt = b;
1575 		/* If we've reached MAX_REGNUM groups, then this open
1576 		 * won't actually generate any code, so we'll have to
1577 		 * clear pending_exact explicitly.  */
1578 		pending_exact = 0;
1579 		break;
1580 
1581 
1582 	    case ')':
1583 		if (syntax & RE_NO_BK_PARENS)
1584 		    goto normal_backslash;
1585 
1586 		if (COMPILE_STACK_EMPTY)
1587 		    if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
1588 			goto normal_backslash;
1589 		    else
1590 			return REG_ERPAREN;
1591 
1592 	      handle_close:
1593 		if (fixup_alt_jump) {	/* Push a dummy failure point at the end of the
1594 					 * alternative for a possible future
1595 					 * `pop_failure_jump' to pop.  See comments at
1596 					 * `push_dummy_failure' in `re_match_2'.  */
1597 		    BUF_PUSH(push_dummy_failure);
1598 
1599 		    /* We allocated space for this jump when we assigned
1600 		     * to `fixup_alt_jump', in the `handle_alt' case below.  */
1601 		    STORE_JUMP(jump_past_alt, fixup_alt_jump, b - 1);
1602 		}
1603 		/* See similar code for backslashed left paren above.  */
1604 		if (COMPILE_STACK_EMPTY)
1605 		    if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
1606 			goto normal_char;
1607 		    else
1608 			return REG_ERPAREN;
1609 
1610 		/* Since we just checked for an empty stack above, this
1611 		 * ``can't happen''.  */
1612 		assert(compile_stack.avail != 0);
1613 		{
1614 		    /* We don't just want to restore into `regnum', because
1615 		     * later groups should continue to be numbered higher,
1616 		     * as in `(ab)c(de)' -- the second group is #2.  */
1617 		    regnum_t this_group_regnum;
1618 
1619 		    compile_stack.avail--;
1620 		    begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
1621 		    fixup_alt_jump
1622 			= COMPILE_STACK_TOP.fixup_alt_jump
1623 			? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
1624 			: 0;
1625 		    laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
1626 		    this_group_regnum = COMPILE_STACK_TOP.regnum;
1627 		    /* If we've reached MAX_REGNUM groups, then this open
1628 		     * won't actually generate any code, so we'll have to
1629 		     * clear pending_exact explicitly.  */
1630 		    pending_exact = 0;
1631 
1632 		    /* We're at the end of the group, so now we know how many
1633 		     * groups were inside this one.  */
1634 		    if (this_group_regnum <= MAX_REGNUM) {
1635 			unsigned char *inner_group_loc
1636 			= bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
1637 
1638 			*inner_group_loc = regnum - this_group_regnum;
1639 			BUF_PUSH_3(stop_memory, this_group_regnum,
1640 			    regnum - this_group_regnum);
1641 		    }
1642 		}
1643 		break;
1644 
1645 
1646 	    case '|':		/* `\|'.  */
1647 		if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
1648 		    goto normal_backslash;
1649 	      handle_alt:
1650 		if (syntax & RE_LIMITED_OPS)
1651 		    goto normal_char;
1652 
1653 		/* Insert before the previous alternative a jump which
1654 		 * jumps to this alternative if the former fails.  */
1655 		GET_BUFFER_SPACE(3);
1656 		INSERT_JUMP(on_failure_jump, begalt, b + 6);
1657 		pending_exact = 0;
1658 		b += 3;
1659 
1660 		/* The alternative before this one has a jump after it
1661 		 * which gets executed if it gets matched.  Adjust that
1662 		 * jump so it will jump to this alternative's analogous
1663 		 * jump (put in below, which in turn will jump to the next
1664 		 * (if any) alternative's such jump, etc.).  The last such
1665 		 * jump jumps to the correct final destination.  A picture:
1666 		 * _____ _____
1667 		 * |   | |   |
1668 		 * |   v |   v
1669 		 * a | b   | c
1670 		 *
1671 		 * If we are at `b', then fixup_alt_jump right now points to a
1672 		 * three-byte space after `a'.  We'll put in the jump, set
1673 		 * fixup_alt_jump to right after `b', and leave behind three
1674 		 * bytes which we'll fill in when we get to after `c'.  */
1675 
1676 		if (fixup_alt_jump)
1677 		    STORE_JUMP(jump_past_alt, fixup_alt_jump, b);
1678 
1679 		/* Mark and leave space for a jump after this alternative,
1680 		 * to be filled in later either by next alternative or
1681 		 * when know we're at the end of a series of alternatives.  */
1682 		fixup_alt_jump = b;
1683 		GET_BUFFER_SPACE(3);
1684 		b += 3;
1685 
1686 		laststart = 0;
1687 		begalt = b;
1688 		break;
1689 
1690 
1691 	    case '{':
1692 		/* If \{ is a literal.  */
1693 		if (!(syntax & RE_INTERVALS)
1694 		/* If we're at `\{' and it's not the open-interval
1695 		 * operator.  */
1696 		    || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
1697 		    || (p - 2 == pattern && p == pend))
1698 		    goto normal_backslash;
1699 
1700 	      handle_interval:
1701 		{
1702 		    /* If got here, then the syntax allows intervals.  */
1703 
1704 		    /* At least (most) this many matches must be made.  */
1705 		    int lower_bound = -1, upper_bound = -1;
1706 
1707 		    beg_interval = p - 1;
1708 
1709 		    if (p == pend) {
1710 			if (syntax & RE_NO_BK_BRACES)
1711 			    goto unfetch_interval;
1712 			else
1713 			    return REG_EBRACE;
1714 		    }
1715 		    GET_UNSIGNED_NUMBER(lower_bound);
1716 
1717 		    if (c == ',') {
1718 			GET_UNSIGNED_NUMBER(upper_bound);
1719 			if (upper_bound < 0)
1720 			    upper_bound = RE_DUP_MAX;
1721 		    } else
1722 			/* Interval such as `{1}' => match exactly once. */
1723 			upper_bound = lower_bound;
1724 
1725 		    if (lower_bound < 0 || upper_bound > RE_DUP_MAX
1726 			|| lower_bound > upper_bound) {
1727 			if (syntax & RE_NO_BK_BRACES)
1728 			    goto unfetch_interval;
1729 			else
1730 			    return REG_BADBR;
1731 		    }
1732 		    if (!(syntax & RE_NO_BK_BRACES)) {
1733 			if (c != '\\')
1734 			    return REG_EBRACE;
1735 
1736 			PATFETCH(c);
1737 		    }
1738 		    if (c != '}') {
1739 			if (syntax & RE_NO_BK_BRACES)
1740 			    goto unfetch_interval;
1741 			else
1742 			    return REG_BADBR;
1743 		    }
1744 		    /* We just parsed a valid interval.  */
1745 
1746 		    /* If it's invalid to have no preceding re.  */
1747 		    if (!laststart) {
1748 			if (syntax & RE_CONTEXT_INVALID_OPS)
1749 			    return REG_BADRPT;
1750 			else if (syntax & RE_CONTEXT_INDEP_OPS)
1751 			    laststart = b;
1752 			else
1753 			    goto unfetch_interval;
1754 		    }
1755 		    /* If the upper bound is zero, don't want to succeed at
1756 		     * all; jump from `laststart' to `b + 3', which will be
1757 		     * the end of the buffer after we insert the jump.  */
1758 		    if (upper_bound == 0) {
1759 			GET_BUFFER_SPACE(3);
1760 			INSERT_JUMP(jump, laststart, b + 3);
1761 			b += 3;
1762 		    }
1763 		    /* Otherwise, we have a nontrivial interval.  When
1764 		     * we're all done, the pattern will look like:
1765 		     * set_number_at <jump count> <upper bound>
1766 		     * set_number_at <succeed_n count> <lower bound>
1767 		     * succeed_n <after jump addr> <succed_n count>
1768 		     * <body of loop>
1769 		     * jump_n <succeed_n addr> <jump count>
1770 		     * (The upper bound and `jump_n' are omitted if
1771 		     * `upper_bound' is 1, though.)  */
1772 		    else {	/* If the upper bound is > 1, we need to insert
1773 				 * more at the end of the loop.  */
1774 			unsigned nbytes = 10 + (upper_bound > 1) * 10;
1775 
1776 			GET_BUFFER_SPACE(nbytes);
1777 
1778 			/* Initialize lower bound of the `succeed_n', even
1779 			 * though it will be set during matching by its
1780 			 * attendant `set_number_at' (inserted next),
1781 			 * because `re_compile_fastmap' needs to know.
1782 			 * Jump to the `jump_n' we might insert below.  */
1783 			INSERT_JUMP2(succeed_n, laststart,
1784 			    b + 5 + (upper_bound > 1) * 5,
1785 			    lower_bound);
1786 			b += 5;
1787 
1788 			/* Code to initialize the lower bound.  Insert
1789 			 * before the `succeed_n'.  The `5' is the last two
1790 			 * bytes of this `set_number_at', plus 3 bytes of
1791 			 * the following `succeed_n'.  */
1792 			insert_op2(set_number_at, laststart, 5, lower_bound, b);
1793 			b += 5;
1794 
1795 			if (upper_bound > 1) {	/* More than one repetition is allowed, so
1796 						 * append a backward jump to the `succeed_n'
1797 						 * that starts this interval.
1798 						 *
1799 						 * When we've reached this during matching,
1800 						 * we'll have matched the interval once, so
1801 						 * jump back only `upper_bound - 1' times.  */
1802 			    STORE_JUMP2(jump_n, b, laststart + 5,
1803 				upper_bound - 1);
1804 			    b += 5;
1805 
1806 			    /* The location we want to set is the second
1807 			     * parameter of the `jump_n'; that is `b-2' as
1808 			     * an absolute address.  `laststart' will be
1809 			     * the `set_number_at' we're about to insert;
1810 			     * `laststart+3' the number to set, the source
1811 			     * for the relative address.  But we are
1812 			     * inserting into the middle of the pattern --
1813 			     * so everything is getting moved up by 5.
1814 			     * Conclusion: (b - 2) - (laststart + 3) + 5,
1815 			     * i.e., b - laststart.
1816 			     *
1817 			     * We insert this at the beginning of the loop
1818 			     * so that if we fail during matching, we'll
1819 			     * reinitialize the bounds.  */
1820 			    insert_op2(set_number_at, laststart, b - laststart,
1821 				upper_bound - 1, b);
1822 			    b += 5;
1823 			}
1824 		    }
1825 		    pending_exact = 0;
1826 		    beg_interval = NULL;
1827 		}
1828 		break;
1829 
1830 	      unfetch_interval:
1831 		/* If an invalid interval, match the characters as literals.  */
1832 		assert(beg_interval);
1833 		p = beg_interval;
1834 		beg_interval = NULL;
1835 
1836 		/* normal_char and normal_backslash need `c'.  */
1837 		PATFETCH(c);
1838 
1839 		if (!(syntax & RE_NO_BK_BRACES)) {
1840 		    if (p > pattern && p[-1] == '\\')
1841 			goto normal_backslash;
1842 		}
1843 		goto normal_char;
1844 
1845 #ifdef emacs
1846 		/* There is no way to specify the before_dot and after_dot
1847 		 * operators.  rms says this is ok.  --karl  */
1848 	    case '=':
1849 		BUF_PUSH(at_dot);
1850 		break;
1851 
1852 	    case 's':
1853 		laststart = b;
1854 		PATFETCH(c);
1855 		BUF_PUSH_2(syntaxspec, syntax_spec_code[c]);
1856 		break;
1857 
1858 	    case 'S':
1859 		laststart = b;
1860 		PATFETCH(c);
1861 		BUF_PUSH_2(notsyntaxspec, syntax_spec_code[c]);
1862 		break;
1863 #endif /* emacs */
1864 
1865 
1866 	    case 'w':
1867 		laststart = b;
1868 		BUF_PUSH(wordchar);
1869 		break;
1870 
1871 
1872 	    case 'W':
1873 		laststart = b;
1874 		BUF_PUSH(notwordchar);
1875 		break;
1876 
1877 
1878 	    case '<':
1879 		BUF_PUSH(wordbeg);
1880 		break;
1881 
1882 	    case '>':
1883 		BUF_PUSH(wordend);
1884 		break;
1885 
1886 	    case 'b':
1887 		BUF_PUSH(wordbound);
1888 		break;
1889 
1890 	    case 'B':
1891 		BUF_PUSH(notwordbound);
1892 		break;
1893 
1894 	    case '`':
1895 		BUF_PUSH(begbuf);
1896 		break;
1897 
1898 	    case '\'':
1899 		BUF_PUSH(endbuf);
1900 		break;
1901 
1902 	    case '1':
1903 	    case '2':
1904 	    case '3':
1905 	    case '4':
1906 	    case '5':
1907 	    case '6':
1908 	    case '7':
1909 	    case '8':
1910 	    case '9':
1911 		if (syntax & RE_NO_BK_REFS)
1912 		    goto normal_char;
1913 
1914 		c1 = c - '0';
1915 
1916 		if (c1 > regnum)
1917 		    return REG_ESUBREG;
1918 
1919 		/* Can't back reference to a subexpression if inside of it.  */
1920 		if (group_in_compile_stack(compile_stack, c1))
1921 		    goto normal_char;
1922 
1923 		laststart = b;
1924 		BUF_PUSH_2(duplicate, c1);
1925 		break;
1926 
1927 
1928 	    case '+':
1929 	    case '?':
1930 		if (syntax & RE_BK_PLUS_QM)
1931 		    goto handle_plus;
1932 		else
1933 		    goto normal_backslash;
1934 
1935 	    default:
1936 	      normal_backslash:
1937 		/* You might think it would be useful for \ to mean
1938 		 * not to translate; but if we don't translate it
1939 		 * it will never match anything.  */
1940 		c = TRANSLATE(c);
1941 		goto normal_char;
1942 	    }
1943 	    break;
1944 
1945 
1946 	default:
1947 	    /* Expects the character in `c'.  */
1948 	  normal_char:
1949 	    /* If no exactn currently being built.  */
1950 	    if (!pending_exact
1951 
1952 	    /* If last exactn not at current position.  */
1953 		|| pending_exact + *pending_exact + 1 != b
1954 
1955 	    /* We have only one byte following the exactn for the count.  */
1956 		|| *pending_exact == (1 << BYTEWIDTH) - 1
1957 
1958 	    /* If followed by a repetition operator.  */
1959 		|| *p == '*' || *p == '^'
1960 		|| ((syntax & RE_BK_PLUS_QM)
1961 		    ? *p == '\\' && (p[1] == '+' || p[1] == '?')
1962 		    : (*p == '+' || *p == '?'))
1963 		|| ((syntax & RE_INTERVALS)
1964 		    && ((syntax & RE_NO_BK_BRACES)
1965 			? *p == '{'
1966 			: (p[0] == '\\' && p[1] == '{')))) {
1967 		/* Start building a new exactn.  */
1968 
1969 		laststart = b;
1970 
1971 		BUF_PUSH_2(exactn, 0);
1972 		pending_exact = b - 1;
1973 	    }
1974 	    BUF_PUSH(c);
1975 	    (*pending_exact)++;
1976 	    break;
1977 	}			/* switch (c) */
1978     }				/* while p != pend */
1979 
1980 
1981     /* Through the pattern now.  */
1982 
1983     if (fixup_alt_jump)
1984 	STORE_JUMP(jump_past_alt, fixup_alt_jump, b);
1985 
1986     if (!COMPILE_STACK_EMPTY)
1987 	return REG_EPAREN;
1988 
1989     free(compile_stack.stack);
1990 
1991     /* We have succeeded; set the length of the buffer.  */
1992     bufp->used = b - bufp->buffer;
1993 
1994 #ifdef DEBUG
1995     if (debug) {
1996 	DEBUG_PRINT1("\nCompiled pattern: ");
1997 	print_compiled_pattern(bufp);
1998     }
1999 #endif /* DEBUG */
2000 
2001     return REG_NOERROR;
2002 }				/* regex_compile */
2003 
2004 /* Subroutines for `regex_compile'.  */
2005 
2006 /* Store OP at LOC followed by two-byte integer parameter ARG.  */
2007 
2008 static void
store_op1(op,loc,arg)2009 store_op1(op, loc, arg)
2010      re_opcode_t op;
2011      unsigned char *loc;
2012      int arg;
2013 {
2014     *loc = (unsigned char) op;
2015     STORE_NUMBER(loc + 1, arg);
2016 }
2017 
2018 
2019 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2.  */
2020 
2021 static void
store_op2(op,loc,arg1,arg2)2022 store_op2(op, loc, arg1, arg2)
2023      re_opcode_t op;
2024      unsigned char *loc;
2025      int arg1, arg2;
2026 {
2027     *loc = (unsigned char) op;
2028     STORE_NUMBER(loc + 1, arg1);
2029     STORE_NUMBER(loc + 3, arg2);
2030 }
2031 
2032 
2033 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
2034  * for OP followed by two-byte integer parameter ARG.  */
2035 
2036 static void
insert_op1(op,loc,arg,end)2037 insert_op1(op, loc, arg, end)
2038      re_opcode_t op;
2039      unsigned char *loc;
2040      int arg;
2041      unsigned char *end;
2042 {
2043     register unsigned char *pfrom = end;
2044     register unsigned char *pto = end + 3;
2045 
2046     while (pfrom != loc)
2047 	*--pto = *--pfrom;
2048 
2049     store_op1(op, loc, arg);
2050 }
2051 
2052 
2053 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2.  */
2054 
2055 static void
insert_op2(op,loc,arg1,arg2,end)2056 insert_op2(op, loc, arg1, arg2, end)
2057      re_opcode_t op;
2058      unsigned char *loc;
2059      int arg1, arg2;
2060      unsigned char *end;
2061 {
2062     register unsigned char *pfrom = end;
2063     register unsigned char *pto = end + 5;
2064 
2065     while (pfrom != loc)
2066 	*--pto = *--pfrom;
2067 
2068     store_op2(op, loc, arg1, arg2);
2069 }
2070 
2071 
2072 /* P points to just after a ^ in PATTERN.  Return true if that ^ comes
2073  * after an alternative or a begin-subexpression.  We assume there is at
2074  * least one character before the ^.  */
2075 
2076 static boolean
at_begline_loc_p(pattern,p,syntax)2077 at_begline_loc_p(pattern, p, syntax)
2078      const char *pattern, *p;
2079      reg_syntax_t syntax;
2080 {
2081     const char *prev = p - 2;
2082     boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
2083 
2084     return
2085     /* After a subexpression?  */
2086 	(*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
2087     /* After an alternative?  */
2088 	|| (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
2089 }
2090 
2091 
2092 /* The dual of at_begline_loc_p.  This one is for $.  We assume there is
2093  * at least one character after the $, i.e., `P < PEND'.  */
2094 
2095 static boolean
at_endline_loc_p(p,pend,syntax)2096 at_endline_loc_p(p, pend, syntax)
2097      const char *p, *pend;
2098      int syntax;
2099 {
2100     const char *next = p;
2101     boolean next_backslash = *next == '\\';
2102     const char *next_next = p + 1 < pend ? p + 1 : NULL;
2103 
2104     return
2105     /* Before a subexpression?  */
2106 	(syntax & RE_NO_BK_PARENS ? *next == ')'
2107 	: next_backslash && next_next && *next_next == ')')
2108     /* Before an alternative?  */
2109 	|| (syntax & RE_NO_BK_VBAR ? *next == '|'
2110 	: next_backslash && next_next && *next_next == '|');
2111 }
2112 
2113 
2114 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
2115  * false if it's not.  */
2116 
2117 static boolean
group_in_compile_stack(compile_stack,regnum)2118 group_in_compile_stack(compile_stack, regnum)
2119      compile_stack_type compile_stack;
2120      regnum_t regnum;
2121 {
2122     int this_element;
2123 
2124     for (this_element = compile_stack.avail - 1;
2125 	this_element >= 0;
2126 	this_element--)
2127 	if (compile_stack.stack[this_element].regnum == regnum)
2128 	    return true;
2129 
2130     return false;
2131 }
2132 
2133 
2134 /* Read the ending character of a range (in a bracket expression) from the
2135  * uncompiled pattern *P_PTR (which ends at PEND).  We assume the
2136  * starting character is in `P[-2]'.  (`P[-1]' is the character `-'.)
2137  * Then we set the translation of all bits between the starting and
2138  * ending characters (inclusive) in the compiled pattern B.
2139  *
2140  * Return an error code.
2141  *
2142  * We use these short variable names so we can use the same macros as
2143  * `regex_compile' itself.  */
2144 
2145 static reg_errcode_t
compile_range(p_ptr,pend,translate,syntax,b)2146 compile_range(p_ptr, pend, translate, syntax, b)
2147      const char **p_ptr, *pend;
2148      char *translate;
2149      reg_syntax_t syntax;
2150      unsigned char *b;
2151 {
2152     unsigned this_char;
2153 
2154     const char *p = *p_ptr;
2155     int range_start, range_end;
2156 
2157     if (p == pend)
2158 	return REG_ERANGE;
2159 
2160     /* Even though the pattern is a signed `char *', we need to fetch
2161      * with unsigned char *'s; if the high bit of the pattern character
2162      * is set, the range endpoints will be negative if we fetch using a
2163      * signed char *.
2164      *
2165      * We also want to fetch the endpoints without translating them; the
2166      * appropriate translation is done in the bit-setting loop below.  */
2167     range_start = ((unsigned char *) p)[-2];
2168     range_end = ((unsigned char *) p)[0];
2169 
2170     /* Have to increment the pointer into the pattern string, so the
2171      * caller isn't still at the ending character.  */
2172     (*p_ptr)++;
2173 
2174     /* If the start is after the end, the range is empty.  */
2175     if (range_start > range_end)
2176 	return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
2177 
2178     /* Here we see why `this_char' has to be larger than an `unsigned
2179      * char' -- the range is inclusive, so if `range_end' == 0xff
2180      * (assuming 8-bit characters), we would otherwise go into an infinite
2181      * loop, since all characters <= 0xff.  */
2182     for (this_char = range_start; this_char <= range_end; this_char++) {
2183 	SET_LIST_BIT(TRANSLATE(this_char));
2184     }
2185 
2186     return REG_NOERROR;
2187 }
2188 
2189 /* Failure stack declarations and macros; both re_compile_fastmap and
2190  * re_match_2 use a failure stack.  These have to be macros because of
2191  * REGEX_ALLOCATE.  */
2192 
2193 
2194 /* Number of failure points for which to initially allocate space
2195  * when matching.  If this number is exceeded, we allocate more
2196  * space, so it is not a hard limit.  */
2197 #ifndef INIT_FAILURE_ALLOC
2198 #define INIT_FAILURE_ALLOC 5
2199 #endif
2200 
2201 /* Roughly the maximum number of failure points on the stack.  Would be
2202  * exactly that if always used MAX_FAILURE_SPACE each time we failed.
2203  * This is a variable only so users of regex can assign to it; we never
2204  * change it ourselves.  */
2205 int re_max_failures = 2000;
2206 
2207 typedef const unsigned char *fail_stack_elt_t;
2208 
2209 typedef struct {
2210     fail_stack_elt_t *stack;
2211     unsigned size;
2212     unsigned avail;		/* Offset of next open position.  */
2213 } fail_stack_type;
2214 
2215 #define FAIL_STACK_EMPTY()     (fail_stack.avail == 0)
2216 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
2217 #define FAIL_STACK_FULL()      (fail_stack.avail == fail_stack.size)
2218 #define FAIL_STACK_TOP()       (fail_stack.stack[fail_stack.avail])
2219 
2220 
2221 /* Initialize `fail_stack'.  Do `return -2' if the alloc fails.  */
2222 
2223 #define INIT_FAIL_STACK()						\
2224   do {									\
2225     fail_stack.stack = (fail_stack_elt_t *)				\
2226       REGEX_ALLOCATE (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t));	\
2227 									\
2228     if (fail_stack.stack == NULL)					\
2229       return -2;							\
2230 									\
2231     fail_stack.size = INIT_FAILURE_ALLOC;				\
2232     fail_stack.avail = 0;						\
2233   } while (0)
2234 
2235 
2236 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
2237  *
2238  * Return 1 if succeeds, and 0 if either ran out of memory
2239  * allocating space for it or it was already too large.
2240  *
2241  * REGEX_REALLOCATE requires `destination' be declared.   */
2242 
2243 #define DOUBLE_FAIL_STACK(fail_stack)					\
2244   ((fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS		\
2245    ? 0									\
2246    : ((fail_stack).stack = (fail_stack_elt_t *)				\
2247         REGEX_REALLOCATE ((fail_stack).stack, 				\
2248           (fail_stack).size * sizeof (fail_stack_elt_t),		\
2249           ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)),	\
2250 									\
2251       (fail_stack).stack == NULL					\
2252       ? 0								\
2253       : ((fail_stack).size <<= 1, 					\
2254          1)))
2255 
2256 
2257 /* Push PATTERN_OP on FAIL_STACK.
2258  *
2259  * Return 1 if was able to do so and 0 if ran out of memory allocating
2260  * space to do so.  */
2261 #define PUSH_PATTERN_OP(pattern_op, fail_stack)				\
2262   ((FAIL_STACK_FULL ()							\
2263     && !DOUBLE_FAIL_STACK (fail_stack))					\
2264     ? 0									\
2265     : ((fail_stack).stack[(fail_stack).avail++] = pattern_op,		\
2266        1))
2267 
2268 /* This pushes an item onto the failure stack.  Must be a four-byte
2269  * value.  Assumes the variable `fail_stack'.  Probably should only
2270  * be called from within `PUSH_FAILURE_POINT'.  */
2271 #define PUSH_FAILURE_ITEM(item)						\
2272   fail_stack.stack[fail_stack.avail++] = (fail_stack_elt_t) item
2273 
2274 /* The complement operation.  Assumes `fail_stack' is nonempty.  */
2275 #define POP_FAILURE_ITEM() fail_stack.stack[--fail_stack.avail]
2276 
2277 /* Used to omit pushing failure point id's when we're not debugging.  */
2278 #ifdef DEBUG
2279 #define DEBUG_PUSH PUSH_FAILURE_ITEM
2280 #define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_ITEM ()
2281 #else
2282 #define DEBUG_PUSH(item)
2283 #define DEBUG_POP(item_addr)
2284 #endif
2285 
2286 
2287 /* Push the information about the state we will need
2288  * if we ever fail back to it.
2289  *
2290  * Requires variables fail_stack, regstart, regend, reg_info, and
2291  * num_regs be declared.  DOUBLE_FAIL_STACK requires `destination' be
2292  * declared.
2293  *
2294  * Does `return FAILURE_CODE' if runs out of memory.  */
2295 
2296 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code)	\
2297   do {									\
2298     char *destination;							\
2299     /* Must be int, so when we don't save any registers, the arithmetic	\
2300        of 0 + -1 isn't done as unsigned.  */				\
2301     int this_reg;							\
2302     									\
2303     DEBUG_STATEMENT (failure_id++);					\
2304     DEBUG_STATEMENT (nfailure_points_pushed++);				\
2305     DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id);		\
2306     DEBUG_PRINT2 ("  Before push, next avail: %d\n", (fail_stack).avail);\
2307     DEBUG_PRINT2 ("                     size: %d\n", (fail_stack).size);\
2308 									\
2309     DEBUG_PRINT2 ("  slots needed: %d\n", NUM_FAILURE_ITEMS);		\
2310     DEBUG_PRINT2 ("     available: %d\n", REMAINING_AVAIL_SLOTS);	\
2311 									\
2312     /* Ensure we have enough space allocated for what we will push.  */	\
2313     while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS)			\
2314       {									\
2315         if (!DOUBLE_FAIL_STACK (fail_stack))			\
2316           return failure_code;						\
2317 									\
2318         DEBUG_PRINT2 ("\n  Doubled stack; size now: %d\n",		\
2319 		       (fail_stack).size);				\
2320         DEBUG_PRINT2 ("  slots available: %d\n", REMAINING_AVAIL_SLOTS);\
2321       }									\
2322 									\
2323     /* Push the info, starting with the registers.  */			\
2324     DEBUG_PRINT1 ("\n");						\
2325 									\
2326     for (this_reg = lowest_active_reg; this_reg <= highest_active_reg;	\
2327          this_reg++)							\
2328       {									\
2329 	DEBUG_PRINT2 ("  Pushing reg: %d\n", this_reg);			\
2330         DEBUG_STATEMENT (num_regs_pushed++);				\
2331 									\
2332 	DEBUG_PRINT2 ("    start: 0x%x\n", regstart[this_reg]);		\
2333         PUSH_FAILURE_ITEM (regstart[this_reg]);				\
2334                                                                         \
2335 	DEBUG_PRINT2 ("    end: 0x%x\n", regend[this_reg]);		\
2336         PUSH_FAILURE_ITEM (regend[this_reg]);				\
2337 									\
2338 	DEBUG_PRINT2 ("    info: 0x%x\n      ", reg_info[this_reg]);	\
2339         DEBUG_PRINT2 (" match_null=%d",					\
2340                       REG_MATCH_NULL_STRING_P (reg_info[this_reg]));	\
2341         DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg]));	\
2342         DEBUG_PRINT2 (" matched_something=%d",				\
2343                       MATCHED_SOMETHING (reg_info[this_reg]));		\
2344         DEBUG_PRINT2 (" ever_matched=%d",				\
2345                       EVER_MATCHED_SOMETHING (reg_info[this_reg]));	\
2346 	DEBUG_PRINT1 ("\n");						\
2347         PUSH_FAILURE_ITEM (reg_info[this_reg].word);			\
2348       }									\
2349 									\
2350     DEBUG_PRINT2 ("  Pushing  low active reg: %d\n", lowest_active_reg);\
2351     PUSH_FAILURE_ITEM (lowest_active_reg);				\
2352 									\
2353     DEBUG_PRINT2 ("  Pushing high active reg: %d\n", highest_active_reg);\
2354     PUSH_FAILURE_ITEM (highest_active_reg);				\
2355 									\
2356     DEBUG_PRINT2 ("  Pushing pattern 0x%x: ", pattern_place);		\
2357     DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend);		\
2358     PUSH_FAILURE_ITEM (pattern_place);					\
2359 									\
2360     DEBUG_PRINT2 ("  Pushing string 0x%x: `", string_place);		\
2361     DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2,   \
2362 				 size2);				\
2363     DEBUG_PRINT1 ("'\n");						\
2364     PUSH_FAILURE_ITEM (string_place);					\
2365 									\
2366     DEBUG_PRINT2 ("  Pushing failure id: %u\n", failure_id);		\
2367     DEBUG_PUSH (failure_id);						\
2368   } while (0)
2369 
2370 /* This is the number of items that are pushed and popped on the stack
2371  * for each register.  */
2372 #define NUM_REG_ITEMS  3
2373 
2374 /* Individual items aside from the registers.  */
2375 #ifdef DEBUG
2376 #define NUM_NONREG_ITEMS 5	/* Includes failure point id.  */
2377 #else
2378 #define NUM_NONREG_ITEMS 4
2379 #endif
2380 
2381 /* We push at most this many items on the stack.  */
2382 #define MAX_FAILURE_ITEMS ((num_regs - 1) * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
2383 
2384 /* We actually push this many items.  */
2385 #define NUM_FAILURE_ITEMS						\
2386   ((highest_active_reg - lowest_active_reg + 1) * NUM_REG_ITEMS 	\
2387     + NUM_NONREG_ITEMS)
2388 
2389 /* How many items can still be added to the stack without overflowing it.  */
2390 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
2391 
2392 
2393 /* Pops what PUSH_FAIL_STACK pushes.
2394  *
2395  * We restore into the parameters, all of which should be lvalues:
2396  * STR -- the saved data position.
2397  * PAT -- the saved pattern position.
2398  * LOW_REG, HIGH_REG -- the highest and lowest active registers.
2399  * REGSTART, REGEND -- arrays of string positions.
2400  * REG_INFO -- array of information about each subexpression.
2401  *
2402  * Also assumes the variables `fail_stack' and (if debugging), `bufp',
2403  * `pend', `string1', `size1', `string2', and `size2'.  */
2404 
2405 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
2406 {									\
2407   DEBUG_STATEMENT (fail_stack_elt_t failure_id;)			\
2408   int this_reg;								\
2409   const unsigned char *string_temp;					\
2410 									\
2411   assert (!FAIL_STACK_EMPTY ());					\
2412 									\
2413   /* Remove failure points and point to how many regs pushed.  */	\
2414   DEBUG_PRINT1 ("POP_FAILURE_POINT:\n");				\
2415   DEBUG_PRINT2 ("  Before pop, next avail: %d\n", fail_stack.avail);	\
2416   DEBUG_PRINT2 ("                    size: %d\n", fail_stack.size);	\
2417 									\
2418   assert (fail_stack.avail >= NUM_NONREG_ITEMS);			\
2419 									\
2420   DEBUG_POP (&failure_id);						\
2421   DEBUG_PRINT2 ("  Popping failure id: %u\n", failure_id);		\
2422 									\
2423   /* If the saved string location is NULL, it came from an		\
2424      on_failure_keep_string_jump opcode, and we want to throw away the	\
2425      saved NULL, thus retaining our current position in the string.  */	\
2426   string_temp = POP_FAILURE_ITEM ();					\
2427   if (string_temp != NULL)						\
2428     str = (const char *) string_temp;					\
2429 									\
2430   DEBUG_PRINT2 ("  Popping string 0x%x: `", str);			\
2431   DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2);	\
2432   DEBUG_PRINT1 ("'\n");							\
2433 									\
2434   pat = (unsigned char *) POP_FAILURE_ITEM ();				\
2435   DEBUG_PRINT2 ("  Popping pattern 0x%x: ", pat);			\
2436   DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend);			\
2437 									\
2438   /* Restore register info.  */						\
2439   high_reg = (unsigned long) POP_FAILURE_ITEM ();			\
2440   DEBUG_PRINT2 ("  Popping high active reg: %d\n", high_reg);		\
2441 									\
2442   low_reg = (unsigned long) POP_FAILURE_ITEM ();			\
2443   DEBUG_PRINT2 ("  Popping  low active reg: %d\n", low_reg);		\
2444 									\
2445   for (this_reg = high_reg; this_reg >= low_reg; this_reg--)		\
2446     {									\
2447       DEBUG_PRINT2 ("    Popping reg: %d\n", this_reg);			\
2448 									\
2449       reg_info[this_reg].word = POP_FAILURE_ITEM ();			\
2450       DEBUG_PRINT2 ("      info: 0x%x\n", reg_info[this_reg]);		\
2451 									\
2452       regend[this_reg] = (const char *) POP_FAILURE_ITEM ();		\
2453       DEBUG_PRINT2 ("      end: 0x%x\n", regend[this_reg]);		\
2454 									\
2455       regstart[this_reg] = (const char *) POP_FAILURE_ITEM ();		\
2456       DEBUG_PRINT2 ("      start: 0x%x\n", regstart[this_reg]);		\
2457     }									\
2458 									\
2459   DEBUG_STATEMENT (nfailure_points_popped++);				\
2460 }				/* POP_FAILURE_POINT */
2461 
2462 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
2463  * BUFP.  A fastmap records which of the (1 << BYTEWIDTH) possible
2464  * characters can start a string that matches the pattern.  This fastmap
2465  * is used by re_search to skip quickly over impossible starting points.
2466  *
2467  * The caller must supply the address of a (1 << BYTEWIDTH)-byte data
2468  * area as BUFP->fastmap.
2469  *
2470  * We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
2471  * the pattern buffer.
2472  *
2473  * Returns 0 if we succeed, -2 if an internal error.   */
2474 
2475 int
re_compile_fastmap(bufp)2476 re_compile_fastmap(bufp)
2477      struct re_pattern_buffer *bufp;
2478 {
2479     int j, k;
2480     fail_stack_type fail_stack;
2481 #ifndef REGEX_MALLOC
2482     char *destination;
2483 #endif
2484     /* We don't push any register information onto the failure stack.  */
2485     unsigned num_regs = 0;
2486 
2487     register char *fastmap = bufp->fastmap;
2488     unsigned char *pattern = bufp->buffer;
2489     unsigned long size = bufp->used;
2490     const unsigned char *p = pattern;
2491     register unsigned char *pend = pattern + size;
2492 
2493     /* Assume that each path through the pattern can be null until
2494      * proven otherwise.  We set this false at the bottom of switch
2495      * statement, to which we get only if a particular path doesn't
2496      * match the empty string.  */
2497     boolean path_can_be_null = true;
2498 
2499     /* We aren't doing a `succeed_n' to begin with.  */
2500     boolean succeed_n_p = false;
2501 
2502     assert(fastmap != NULL && p != NULL);
2503 
2504     INIT_FAIL_STACK();
2505     bzero(fastmap, 1 << BYTEWIDTH);	/* Assume nothing's valid.  */
2506     bufp->fastmap_accurate = 1;	/* It will be when we're done.  */
2507     bufp->can_be_null = 0;
2508 
2509     while (p != pend || !FAIL_STACK_EMPTY()) {
2510 	if (p == pend) {
2511 	    bufp->can_be_null |= path_can_be_null;
2512 
2513 	    /* Reset for next path.  */
2514 	    path_can_be_null = true;
2515 
2516 	    p = fail_stack.stack[--fail_stack.avail];
2517 	}
2518 	/* We should never be about to go beyond the end of the pattern.  */
2519 	assert(p < pend);
2520 
2521 #ifdef SWITCH_ENUM_BUG
2522 	switch ((int) ((re_opcode_t) * p++))
2523 #else
2524 	switch ((re_opcode_t) * p++)
2525 #endif
2526 	{
2527 
2528 	    /* I guess the idea here is to simply not bother with a fastmap
2529 	     * if a backreference is used, since it's too hard to figure out
2530 	     * the fastmap for the corresponding group.  Setting
2531 	     * `can_be_null' stops `re_search_2' from using the fastmap, so
2532 	     * that is all we do.  */
2533 	case duplicate:
2534 	    bufp->can_be_null = 1;
2535 	    return 0;
2536 
2537 
2538 	    /* Following are the cases which match a character.  These end
2539 	     * with `break'.  */
2540 
2541 	case exactn:
2542 	    fastmap[p[1]] = 1;
2543 	    break;
2544 
2545 
2546 	case charset:
2547 	    for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
2548 		if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
2549 		    fastmap[j] = 1;
2550 	    break;
2551 
2552 
2553 	case charset_not:
2554 	    /* Chars beyond end of map must be allowed.  */
2555 	    for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
2556 		fastmap[j] = 1;
2557 
2558 	    for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
2559 		if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
2560 		    fastmap[j] = 1;
2561 	    break;
2562 
2563 
2564 	case wordchar:
2565 	    for (j = 0; j < (1 << BYTEWIDTH); j++)
2566 		if (SYNTAX(j) == Sword)
2567 		    fastmap[j] = 1;
2568 	    break;
2569 
2570 
2571 	case notwordchar:
2572 	    for (j = 0; j < (1 << BYTEWIDTH); j++)
2573 		if (SYNTAX(j) != Sword)
2574 		    fastmap[j] = 1;
2575 	    break;
2576 
2577 
2578 	case anychar:
2579 	    /* `.' matches anything ...  */
2580 	    for (j = 0; j < (1 << BYTEWIDTH); j++)
2581 		fastmap[j] = 1;
2582 
2583 	    /* ... except perhaps newline.  */
2584 	    if (!(bufp->syntax & RE_DOT_NEWLINE))
2585 		fastmap['\n'] = 0;
2586 
2587 	    /* Return if we have already set `can_be_null'; if we have,
2588 	     * then the fastmap is irrelevant.  Something's wrong here.  */
2589 	    else if (bufp->can_be_null)
2590 		return 0;
2591 
2592 	    /* Otherwise, have to check alternative paths.  */
2593 	    break;
2594 
2595 
2596 #ifdef emacs
2597 	case syntaxspec:
2598 	    k = *p++;
2599 	    for (j = 0; j < (1 << BYTEWIDTH); j++)
2600 		if (SYNTAX(j) == (enum syntaxcode) k)
2601 		    fastmap[j] = 1;
2602 	    break;
2603 
2604 
2605 	case notsyntaxspec:
2606 	    k = *p++;
2607 	    for (j = 0; j < (1 << BYTEWIDTH); j++)
2608 		if (SYNTAX(j) != (enum syntaxcode) k)
2609 		    fastmap[j] = 1;
2610 	    break;
2611 
2612 
2613 	    /* All cases after this match the empty string.  These end with
2614 	     * `continue'.  */
2615 
2616 
2617 	case before_dot:
2618 	case at_dot:
2619 	case after_dot:
2620 	    continue;
2621 #endif /* not emacs */
2622 
2623 
2624 	case no_op:
2625 	case begline:
2626 	case endline:
2627 	case begbuf:
2628 	case endbuf:
2629 	case wordbound:
2630 	case notwordbound:
2631 	case wordbeg:
2632 	case wordend:
2633 	case push_dummy_failure:
2634 	    continue;
2635 
2636 
2637 	case jump_n:
2638 	case pop_failure_jump:
2639 	case maybe_pop_jump:
2640 	case jump:
2641 	case jump_past_alt:
2642 	case dummy_failure_jump:
2643 	    EXTRACT_NUMBER_AND_INCR(j, p);
2644 	    p += j;
2645 	    if (j > 0)
2646 		continue;
2647 
2648 	    /* Jump backward implies we just went through the body of a
2649 	     * loop and matched nothing.  Opcode jumped to should be
2650 	     * `on_failure_jump' or `succeed_n'.  Just treat it like an
2651 	     * ordinary jump.  For a * loop, it has pushed its failure
2652 	     * point already; if so, discard that as redundant.  */
2653 	    if ((re_opcode_t) * p != on_failure_jump
2654 		&& (re_opcode_t) * p != succeed_n)
2655 		continue;
2656 
2657 	    p++;
2658 	    EXTRACT_NUMBER_AND_INCR(j, p);
2659 	    p += j;
2660 
2661 	    /* If what's on the stack is where we are now, pop it.  */
2662 	    if (!FAIL_STACK_EMPTY()
2663 		&& fail_stack.stack[fail_stack.avail - 1] == p)
2664 		fail_stack.avail--;
2665 
2666 	    continue;
2667 
2668 
2669 	case on_failure_jump:
2670 	case on_failure_keep_string_jump:
2671 	  handle_on_failure_jump:
2672 	    EXTRACT_NUMBER_AND_INCR(j, p);
2673 
2674 	    /* For some patterns, e.g., `(a?)?', `p+j' here points to the
2675 	     * end of the pattern.  We don't want to push such a point,
2676 	     * since when we restore it above, entering the switch will
2677 	     * increment `p' past the end of the pattern.  We don't need
2678 	     * to push such a point since we obviously won't find any more
2679 	     * fastmap entries beyond `pend'.  Such a pattern can match
2680 	     * the null string, though.  */
2681 	    if (p + j < pend) {
2682 		if (!PUSH_PATTERN_OP(p + j, fail_stack))
2683 		    return -2;
2684 	    } else
2685 		bufp->can_be_null = 1;
2686 
2687 	    if (succeed_n_p) {
2688 		EXTRACT_NUMBER_AND_INCR(k, p);	/* Skip the n.  */
2689 		succeed_n_p = false;
2690 	    }
2691 	    continue;
2692 
2693 
2694 	case succeed_n:
2695 	    /* Get to the number of times to succeed.  */
2696 	    p += 2;
2697 
2698 	    /* Increment p past the n for when k != 0.  */
2699 	    EXTRACT_NUMBER_AND_INCR(k, p);
2700 	    if (k == 0) {
2701 		p -= 4;
2702 		succeed_n_p = true;	/* Spaghetti code alert.  */
2703 		goto handle_on_failure_jump;
2704 	    }
2705 	    continue;
2706 
2707 
2708 	case set_number_at:
2709 	    p += 4;
2710 	    continue;
2711 
2712 
2713 	case start_memory:
2714 	case stop_memory:
2715 	    p += 2;
2716 	    continue;
2717 
2718 
2719 	default:
2720 	    abort();		/* We have listed all the cases.  */
2721 	}			/* switch *p++ */
2722 
2723 	/* Getting here means we have found the possible starting
2724 	 * characters for one path of the pattern -- and that the empty
2725 	 * string does not match.  We need not follow this path further.
2726 	 * Instead, look at the next alternative (remembered on the
2727 	 * stack), or quit if no more.  The test at the top of the loop
2728 	 * does these things.  */
2729 	path_can_be_null = false;
2730 	p = pend;
2731     }				/* while p */
2732 
2733     /* Set `can_be_null' for the last path (also the first path, if the
2734      * pattern is empty).  */
2735     bufp->can_be_null |= path_can_be_null;
2736     return 0;
2737 }				/* re_compile_fastmap */
2738 
2739 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
2740  * ENDS.  Subsequent matches using PATTERN_BUFFER and REGS will use
2741  * this memory for recording register information.  STARTS and ENDS
2742  * must be allocated using the malloc library routine, and must each
2743  * be at least NUM_REGS * sizeof (regoff_t) bytes long.
2744  *
2745  * If NUM_REGS == 0, then subsequent matches should allocate their own
2746  * register data.
2747  *
2748  * Unless this function is called, the first search or match using
2749  * PATTERN_BUFFER will allocate its own register data, without
2750  * freeing the old data.  */
2751 
2752 void
re_set_registers(bufp,regs,num_regs,starts,ends)2753 re_set_registers(bufp, regs, num_regs, starts, ends)
2754      struct re_pattern_buffer *bufp;
2755      struct re_registers *regs;
2756      unsigned num_regs;
2757      regoff_t *starts, *ends;
2758 {
2759     if (num_regs) {
2760 	bufp->regs_allocated = REGS_REALLOCATE;
2761 	regs->num_regs = num_regs;
2762 	regs->start = starts;
2763 	regs->end = ends;
2764     } else {
2765 	bufp->regs_allocated = REGS_UNALLOCATED;
2766 	regs->num_regs = 0;
2767 	regs->start = regs->end = (regoff_t) 0;
2768     }
2769 }
2770 
2771 /* Searching routines.  */
2772 
2773 /* Like re_search_2, below, but only one string is specified, and
2774  * doesn't let you say where to stop matching. */
2775 
2776 int
re_search(bufp,string,size,startpos,range,regs)2777 re_search(bufp, string, size, startpos, range, regs)
2778      struct re_pattern_buffer *bufp;
2779      const char *string;
2780      int size, startpos, range;
2781      struct re_registers *regs;
2782 {
2783     return re_search_2(bufp, NULL, 0, string, size, startpos, range,
2784 	regs, size);
2785 }
2786 
2787 
2788 /* Using the compiled pattern in BUFP->buffer, first tries to match the
2789  * virtual concatenation of STRING1 and STRING2, starting first at index
2790  * STARTPOS, then at STARTPOS + 1, and so on.
2791  *
2792  * STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
2793  *
2794  * RANGE is how far to scan while trying to match.  RANGE = 0 means try
2795  * only at STARTPOS; in general, the last start tried is STARTPOS +
2796  * RANGE.
2797  *
2798  * In REGS, return the indices of the virtual concatenation of STRING1
2799  * and STRING2 that matched the entire BUFP->buffer and its contained
2800  * subexpressions.
2801  *
2802  * Do not consider matching one past the index STOP in the virtual
2803  * concatenation of STRING1 and STRING2.
2804  *
2805  * We return either the position in the strings at which the match was
2806  * found, -1 if no match, or -2 if error (such as failure
2807  * stack overflow).  */
2808 
2809 int
re_search_2(bufp,string1,size1,string2,size2,startpos,range,regs,stop)2810 re_search_2(bufp, string1, size1, string2, size2, startpos, range, regs, stop)
2811      struct re_pattern_buffer *bufp;
2812      const char *string1, *string2;
2813      int size1, size2;
2814      int startpos;
2815      int range;
2816      struct re_registers *regs;
2817      int stop;
2818 {
2819     int val;
2820     register char *fastmap = bufp->fastmap;
2821     register char *translate = bufp->translate;
2822     int total_size = size1 + size2;
2823     int endpos = startpos + range;
2824 
2825     /* Check for out-of-range STARTPOS.  */
2826     if (startpos < 0 || startpos > total_size)
2827 	return -1;
2828 
2829     /* Fix up RANGE if it might eventually take us outside
2830      * the virtual concatenation of STRING1 and STRING2.  */
2831     if (endpos < -1)
2832 	range = -1 - startpos;
2833     else if (endpos > total_size)
2834 	range = total_size - startpos;
2835 
2836     /* If the search isn't to be a backwards one, don't waste time in a
2837      * search for a pattern that must be anchored.  */
2838     if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0) {
2839 	if (startpos > 0)
2840 	    return -1;
2841 	else
2842 	    range = 1;
2843     }
2844     /* Update the fastmap now if not correct already.  */
2845     if (fastmap && !bufp->fastmap_accurate)
2846 	if (re_compile_fastmap(bufp) == -2)
2847 	    return -2;
2848 
2849     /* Loop through the string, looking for a place to start matching.  */
2850     for (;;) {
2851 	/* If a fastmap is supplied, skip quickly over characters that
2852 	 * cannot be the start of a match.  If the pattern can match the
2853 	 * null string, however, we don't need to skip characters; we want
2854 	 * the first null string.  */
2855 	if (fastmap && startpos < total_size && !bufp->can_be_null) {
2856 	    if (range > 0) {	/* Searching forwards.  */
2857 		register const char *d;
2858 		register int lim = 0;
2859 		int irange = range;
2860 
2861 		if (startpos < size1 && startpos + range >= size1)
2862 		    lim = range - (size1 - startpos);
2863 
2864 		d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
2865 
2866 		/* Written out as an if-else to avoid testing `translate'
2867 		 * inside the loop.  */
2868 		if (translate)
2869 		    while (range > lim
2870 			&& !fastmap[(unsigned char)
2871 			    translate[(unsigned char) *d++]])
2872 			range--;
2873 		else
2874 		    while (range > lim && !fastmap[(unsigned char) *d++])
2875 			range--;
2876 
2877 		startpos += irange - range;
2878 	    } else {		/* Searching backwards.  */
2879 		register char c = (size1 == 0 || startpos >= size1
2880 		    ? string2[startpos - size1]
2881 		    : string1[startpos]);
2882 
2883 		if (!fastmap[(unsigned char) TRANSLATE(c)])
2884 		    goto advance;
2885 	    }
2886 	}
2887 	/* If can't match the null string, and that's all we have left, fail.  */
2888 	if (range >= 0 && startpos == total_size && fastmap
2889 	    && !bufp->can_be_null)
2890 	    return -1;
2891 
2892 	val = re_match_2(bufp, string1, size1, string2, size2,
2893 	    startpos, regs, stop);
2894 	if (val >= 0)
2895 	    return startpos;
2896 
2897 	if (val == -2)
2898 	    return -2;
2899 
2900       advance:
2901 	if (!range)
2902 	    break;
2903 	else if (range > 0) {
2904 	    range--;
2905 	    startpos++;
2906 	} else {
2907 	    range++;
2908 	    startpos--;
2909 	}
2910     }
2911     return -1;
2912 }				/* re_search_2 */
2913 
2914 /* Declarations and macros for re_match_2.  */
2915 
2916 static int bcmp_translate();
2917 static boolean alt_match_null_string_p(), common_op_match_null_string_p(),
2918         group_match_null_string_p();
2919 
2920 /* Structure for per-register (a.k.a. per-group) information.
2921  * This must not be longer than one word, because we push this value
2922  * onto the failure stack.  Other register information, such as the
2923  * starting and ending positions (which are addresses), and the list of
2924  * inner groups (which is a bits list) are maintained in separate
2925  * variables.
2926  *
2927  * We are making a (strictly speaking) nonportable assumption here: that
2928  * the compiler will pack our bit fields into something that fits into
2929  * the type of `word', i.e., is something that fits into one item on the
2930  * failure stack.  */
2931 typedef union {
2932     fail_stack_elt_t word;
2933     struct {
2934 	/* This field is one if this group can match the empty string,
2935 	 * zero if not.  If not yet determined,  `MATCH_NULL_UNSET_VALUE'.  */
2936 #define MATCH_NULL_UNSET_VALUE 3
2937 	unsigned match_null_string_p:2;
2938 	unsigned is_active:1;
2939 	unsigned matched_something:1;
2940 	unsigned ever_matched_something:1;
2941     } bits;
2942 } register_info_type;
2943 
2944 #define REG_MATCH_NULL_STRING_P(R)  ((R).bits.match_null_string_p)
2945 #define IS_ACTIVE(R)  ((R).bits.is_active)
2946 #define MATCHED_SOMETHING(R)  ((R).bits.matched_something)
2947 #define EVER_MATCHED_SOMETHING(R)  ((R).bits.ever_matched_something)
2948 
2949 
2950 /* Call this when have matched a real character; it sets `matched' flags
2951  * for the subexpressions which we are currently inside.  Also records
2952  * that those subexprs have matched.  */
2953 #define SET_REGS_MATCHED()						\
2954   do									\
2955     {									\
2956       unsigned r;							\
2957       for (r = lowest_active_reg; r <= highest_active_reg; r++)		\
2958         {								\
2959           MATCHED_SOMETHING (reg_info[r])				\
2960             = EVER_MATCHED_SOMETHING (reg_info[r])			\
2961             = 1;							\
2962         }								\
2963     }									\
2964   while (0)
2965 
2966 
2967 /* This converts PTR, a pointer into one of the search strings `string1'
2968  * and `string2' into an offset from the beginning of that string.  */
2969 #define POINTER_TO_OFFSET(ptr)						\
2970   (FIRST_STRING_P (ptr) ? (ptr) - string1 : (ptr) - string2 + size1)
2971 
2972 /* Registers are set to a sentinel when they haven't yet matched.  */
2973 #define REG_UNSET_VALUE ((char *) -1)
2974 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
2975 
2976 
2977 /* Macros for dealing with the split strings in re_match_2.  */
2978 
2979 #define MATCHING_IN_FIRST_STRING  (dend == end_match_1)
2980 
2981 /* Call before fetching a character with *d.  This switches over to
2982  * string2 if necessary.  */
2983 #define PREFETCH()							\
2984   while (d == dend)						    	\
2985     {									\
2986       /* End of string2 => fail.  */					\
2987       if (dend == end_match_2) 						\
2988         goto fail;							\
2989       /* End of string1 => advance to string2.  */ 			\
2990       d = string2;						        \
2991       dend = end_match_2;						\
2992     }
2993 
2994 
2995 /* Test if at very beginning or at very end of the virtual concatenation
2996  * of `string1' and `string2'.  If only one string, it's `string2'.  */
2997 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
2998 #define AT_STRINGS_END(d) ((d) == end2)
2999 
3000 
3001 /* Test if D points to a character which is word-constituent.  We have
3002  * two special cases to check for: if past the end of string1, look at
3003  * the first character in string2; and if before the beginning of
3004  * string2, look at the last character in string1.  */
3005 #define WORDCHAR_P(d)							\
3006   (SYNTAX ((d) == end1 ? *string2					\
3007            : (d) == string2 - 1 ? *(end1 - 1) : *(d))			\
3008    == Sword)
3009 
3010 /* Test if the character before D and the one at D differ with respect
3011  * to being word-constituent.  */
3012 #define AT_WORD_BOUNDARY(d)						\
3013   (AT_STRINGS_BEG (d) || AT_STRINGS_END (d)				\
3014    || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
3015 
3016 
3017 /* Free everything we malloc.  */
3018 #ifdef REGEX_MALLOC
3019 #define FREE_VAR(var) if (var) free (var); var = NULL
3020 #define FREE_VARIABLES()						\
3021   do {									\
3022     FREE_VAR (fail_stack.stack);					\
3023     FREE_VAR (regstart);						\
3024     FREE_VAR (regend);							\
3025     FREE_VAR (old_regstart);						\
3026     FREE_VAR (old_regend);						\
3027     FREE_VAR (best_regstart);						\
3028     FREE_VAR (best_regend);						\
3029     FREE_VAR (reg_info);						\
3030     FREE_VAR (reg_dummy);						\
3031     FREE_VAR (reg_info_dummy);						\
3032   } while (0)
3033 #else /* not REGEX_MALLOC */
3034 /* Some MIPS systems (at least) want this to free alloca'd storage.  */
3035 #define FREE_VARIABLES() alloca (0)
3036 #endif /* not REGEX_MALLOC */
3037 
3038 
3039 /* These values must meet several constraints.  They must not be valid
3040  * register values; since we have a limit of 255 registers (because
3041  * we use only one byte in the pattern for the register number), we can
3042  * use numbers larger than 255.  They must differ by 1, because of
3043  * NUM_FAILURE_ITEMS above.  And the value for the lowest register must
3044  * be larger than the value for the highest register, so we do not try
3045  * to actually save any registers when none are active.  */
3046 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
3047 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
3048 
3049 /* Matching routines.  */
3050 
3051 #ifndef emacs			/* Emacs never uses this.  */
3052 /* re_match is like re_match_2 except it takes only a single string.  */
3053 
3054 int
re_match(bufp,string,size,pos,regs)3055 re_match(bufp, string, size, pos, regs)
3056      struct re_pattern_buffer *bufp;
3057      const char *string;
3058      int size, pos;
3059      struct re_registers *regs;
3060 {
3061     return re_match_2(bufp, NULL, 0, string, size, pos, regs, size);
3062 }
3063 #endif /* not emacs */
3064 
3065 
3066 /* re_match_2 matches the compiled pattern in BUFP against the
3067  * the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
3068  * and SIZE2, respectively).  We start matching at POS, and stop
3069  * matching at STOP.
3070  *
3071  * If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
3072  * store offsets for the substring each group matched in REGS.  See the
3073  * documentation for exactly how many groups we fill.
3074  *
3075  * We return -1 if no match, -2 if an internal error (such as the
3076  * failure stack overflowing).  Otherwise, we return the length of the
3077  * matched substring.  */
3078 
3079 int
re_match_2(bufp,string1,size1,string2,size2,pos,regs,stop)3080 re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop)
3081      struct re_pattern_buffer *bufp;
3082      const char *string1, *string2;
3083      int size1, size2;
3084      int pos;
3085      struct re_registers *regs;
3086      int stop;
3087 {
3088     /* General temporaries.  */
3089     int mcnt;
3090     unsigned char *p1;
3091 
3092     /* Just past the end of the corresponding string.  */
3093     const char *end1, *end2;
3094 
3095     /* Pointers into string1 and string2, just past the last characters in
3096      * each to consider matching.  */
3097     const char *end_match_1, *end_match_2;
3098 
3099     /* Where we are in the data, and the end of the current string.  */
3100     const char *d, *dend;
3101 
3102     /* Where we are in the pattern, and the end of the pattern.  */
3103     unsigned char *p = bufp->buffer;
3104     register unsigned char *pend = p + bufp->used;
3105 
3106     /* We use this to map every character in the string.  */
3107     char *translate = bufp->translate;
3108 
3109     /* Failure point stack.  Each place that can handle a failure further
3110      * down the line pushes a failure point on this stack.  It consists of
3111      * restart, regend, and reg_info for all registers corresponding to
3112      * the subexpressions we're currently inside, plus the number of such
3113      * registers, and, finally, two char *'s.  The first char * is where
3114      * to resume scanning the pattern; the second one is where to resume
3115      * scanning the strings.  If the latter is zero, the failure point is
3116      * a ``dummy''; if a failure happens and the failure point is a dummy,
3117      * it gets discarded and the next next one is tried.  */
3118     fail_stack_type fail_stack;
3119 #ifdef DEBUG
3120     static unsigned failure_id = 0;
3121     unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
3122 #endif
3123 
3124     /* We fill all the registers internally, independent of what we
3125      * return, for use in backreferences.  The number here includes
3126      * an element for register zero.  */
3127     unsigned num_regs = bufp->re_nsub + 1;
3128 
3129     /* The currently active registers.  */
3130     unsigned long lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3131     unsigned long highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3132 
3133     /* Information on the contents of registers. These are pointers into
3134      * the input strings; they record just what was matched (on this
3135      * attempt) by a subexpression part of the pattern, that is, the
3136      * regnum-th regstart pointer points to where in the pattern we began
3137      * matching and the regnum-th regend points to right after where we
3138      * stopped matching the regnum-th subexpression.  (The zeroth register
3139      * keeps track of what the whole pattern matches.)  */
3140     const char **regstart = NULL, **regend = NULL;
3141 
3142     /* If a group that's operated upon by a repetition operator fails to
3143      * match anything, then the register for its start will need to be
3144      * restored because it will have been set to wherever in the string we
3145      * are when we last see its open-group operator.  Similarly for a
3146      * register's end.  */
3147     const char **old_regstart = NULL, **old_regend = NULL;
3148 
3149     /* The is_active field of reg_info helps us keep track of which (possibly
3150      * nested) subexpressions we are currently in. The matched_something
3151      * field of reg_info[reg_num] helps us tell whether or not we have
3152      * matched any of the pattern so far this time through the reg_num-th
3153      * subexpression.  These two fields get reset each time through any
3154      * loop their register is in.  */
3155     register_info_type *reg_info = NULL;
3156 
3157     /* The following record the register info as found in the above
3158      * variables when we find a match better than any we've seen before.
3159      * This happens as we backtrack through the failure points, which in
3160      * turn happens only if we have not yet matched the entire string. */
3161     unsigned best_regs_set = false;
3162     const char **best_regstart = NULL, **best_regend = NULL;
3163 
3164     /* Logically, this is `best_regend[0]'.  But we don't want to have to
3165      * allocate space for that if we're not allocating space for anything
3166      * else (see below).  Also, we never need info about register 0 for
3167      * any of the other register vectors, and it seems rather a kludge to
3168      * treat `best_regend' differently than the rest.  So we keep track of
3169      * the end of the best match so far in a separate variable.  We
3170      * initialize this to NULL so that when we backtrack the first time
3171      * and need to test it, it's not garbage.  */
3172     const char *match_end = NULL;
3173 
3174     /* Used when we pop values we don't care about.  */
3175     const char **reg_dummy = NULL;
3176     register_info_type *reg_info_dummy = NULL;
3177 
3178 #ifdef DEBUG
3179     /* Counts the total number of registers pushed.  */
3180     unsigned num_regs_pushed = 0;
3181 #endif
3182 
3183     DEBUG_PRINT1("\n\nEntering re_match_2.\n");
3184 
3185     INIT_FAIL_STACK();
3186 
3187     /* Do not bother to initialize all the register variables if there are
3188      * no groups in the pattern, as it takes a fair amount of time.  If
3189      * there are groups, we include space for register 0 (the whole
3190      * pattern), even though we never use it, since it simplifies the
3191      * array indexing.  We should fix this.  */
3192     if (bufp->re_nsub) {
3193 	regstart = REGEX_TALLOC(num_regs, const char *);
3194 	regend = REGEX_TALLOC(num_regs, const char *);
3195 	old_regstart = REGEX_TALLOC(num_regs, const char *);
3196 	old_regend = REGEX_TALLOC(num_regs, const char *);
3197 	best_regstart = REGEX_TALLOC(num_regs, const char *);
3198 	best_regend = REGEX_TALLOC(num_regs, const char *);
3199 	reg_info = REGEX_TALLOC(num_regs, register_info_type);
3200 	reg_dummy = REGEX_TALLOC(num_regs, const char *);
3201 	reg_info_dummy = REGEX_TALLOC(num_regs, register_info_type);
3202 
3203 	if (!(regstart && regend && old_regstart && old_regend && reg_info
3204 		&& best_regstart && best_regend && reg_dummy && reg_info_dummy)) {
3205 	    FREE_VARIABLES();
3206 	    return -2;
3207 	}
3208     }
3209 #ifdef REGEX_MALLOC
3210     else {
3211 	/* We must initialize all our variables to NULL, so that
3212 	 * `FREE_VARIABLES' doesn't try to free them.  */
3213 	regstart = regend = old_regstart = old_regend = best_regstart
3214 	    = best_regend = reg_dummy = NULL;
3215 	reg_info = reg_info_dummy = (register_info_type *) NULL;
3216     }
3217 #endif /* REGEX_MALLOC */
3218 
3219     /* The starting position is bogus.  */
3220     if (pos < 0 || pos > size1 + size2) {
3221 	FREE_VARIABLES();
3222 	return -1;
3223     }
3224     /* Initialize subexpression text positions to -1 to mark ones that no
3225      * start_memory/stop_memory has been seen for. Also initialize the
3226      * register information struct.  */
3227     for (mcnt = 1; mcnt < num_regs; mcnt++) {
3228 	regstart[mcnt] = regend[mcnt]
3229 	    = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
3230 
3231 	REG_MATCH_NULL_STRING_P(reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
3232 	IS_ACTIVE(reg_info[mcnt]) = 0;
3233 	MATCHED_SOMETHING(reg_info[mcnt]) = 0;
3234 	EVER_MATCHED_SOMETHING(reg_info[mcnt]) = 0;
3235     }
3236 
3237     /* We move `string1' into `string2' if the latter's empty -- but not if
3238      * `string1' is null.  */
3239     if (size2 == 0 && string1 != NULL) {
3240 	string2 = string1;
3241 	size2 = size1;
3242 	string1 = 0;
3243 	size1 = 0;
3244     }
3245     end1 = string1 + size1;
3246     end2 = string2 + size2;
3247 
3248     /* Compute where to stop matching, within the two strings.  */
3249     if (stop <= size1) {
3250 	end_match_1 = string1 + stop;
3251 	end_match_2 = string2;
3252     } else {
3253 	end_match_1 = end1;
3254 	end_match_2 = string2 + stop - size1;
3255     }
3256 
3257     /* `p' scans through the pattern as `d' scans through the data.
3258      * `dend' is the end of the input string that `d' points within.  `d'
3259      * is advanced into the following input string whenever necessary, but
3260      * this happens before fetching; therefore, at the beginning of the
3261      * loop, `d' can be pointing at the end of a string, but it cannot
3262      * equal `string2'.  */
3263     if (size1 > 0 && pos <= size1) {
3264 	d = string1 + pos;
3265 	dend = end_match_1;
3266     } else {
3267 	d = string2 + pos - size1;
3268 	dend = end_match_2;
3269     }
3270 
3271     DEBUG_PRINT1("The compiled pattern is: ");
3272     DEBUG_PRINT_COMPILED_PATTERN(bufp, p, pend);
3273     DEBUG_PRINT1("The string to match is: `");
3274     DEBUG_PRINT_DOUBLE_STRING(d, string1, size1, string2, size2);
3275     DEBUG_PRINT1("'\n");
3276 
3277     /* This loops over pattern commands.  It exits by returning from the
3278      * function if the match is complete, or it drops through if the match
3279      * fails at this starting point in the input data.  */
3280     for (;;) {
3281 	DEBUG_PRINT2("\n0x%x: ", p);
3282 
3283 	if (p == pend) {	/* End of pattern means we might have succeeded.  */
3284 	    DEBUG_PRINT1("end of pattern ... ");
3285 
3286 	    /* If we haven't matched the entire string, and we want the
3287 	     * longest match, try backtracking.  */
3288 	    if (d != end_match_2) {
3289 		DEBUG_PRINT1("backtracking.\n");
3290 
3291 		if (!FAIL_STACK_EMPTY()) {	/* More failure points to try.  */
3292 		    boolean same_str_p = (FIRST_STRING_P(match_end)
3293 			== MATCHING_IN_FIRST_STRING);
3294 
3295 		    /* If exceeds best match so far, save it.  */
3296 		    if (!best_regs_set
3297 			|| (same_str_p && d > match_end)
3298 			|| (!same_str_p && !MATCHING_IN_FIRST_STRING)) {
3299 			best_regs_set = true;
3300 			match_end = d;
3301 
3302 			DEBUG_PRINT1("\nSAVING match as best so far.\n");
3303 
3304 			for (mcnt = 1; mcnt < num_regs; mcnt++) {
3305 			    best_regstart[mcnt] = regstart[mcnt];
3306 			    best_regend[mcnt] = regend[mcnt];
3307 			}
3308 		    }
3309 		    goto fail;
3310 		}
3311 		/* If no failure points, don't restore garbage.  */
3312 		else if (best_regs_set) {
3313 		  restore_best_regs:
3314 		    /* Restore best match.  It may happen that `dend ==
3315 		     * end_match_1' while the restored d is in string2.
3316 		     * For example, the pattern `x.*y.*z' against the
3317 		     * strings `x-' and `y-z-', if the two strings are
3318 		     * not consecutive in memory.  */
3319 		    DEBUG_PRINT1("Restoring best registers.\n");
3320 
3321 		    d = match_end;
3322 		    dend = ((d >= string1 && d <= end1)
3323 			? end_match_1 : end_match_2);
3324 
3325 		    for (mcnt = 1; mcnt < num_regs; mcnt++) {
3326 			regstart[mcnt] = best_regstart[mcnt];
3327 			regend[mcnt] = best_regend[mcnt];
3328 		    }
3329 		}
3330 	    }			/* d != end_match_2 */
3331 	    DEBUG_PRINT1("Accepting match.\n");
3332 
3333 	    /* If caller wants register contents data back, do it.  */
3334 	    if (regs && !bufp->no_sub) {
3335 		/* Have the register data arrays been allocated?  */
3336 		if (bufp->regs_allocated == REGS_UNALLOCATED) {		/* No.  So allocate them with malloc.  We need one
3337 									 * extra element beyond `num_regs' for the `-1' marker
3338 									 * GNU code uses.  */
3339 		    regs->num_regs = MAX(RE_NREGS, num_regs + 1);
3340 		    regs->start = TALLOC(regs->num_regs, regoff_t);
3341 		    regs->end = TALLOC(regs->num_regs, regoff_t);
3342 		    if (regs->start == NULL || regs->end == NULL)
3343 			return -2;
3344 		    bufp->regs_allocated = REGS_REALLOCATE;
3345 		} else if (bufp->regs_allocated == REGS_REALLOCATE) {	/* Yes.  If we need more elements than were already
3346 									 * allocated, reallocate them.  If we need fewer, just
3347 									 * leave it alone.  */
3348 		    if (regs->num_regs < num_regs + 1) {
3349 			regs->num_regs = num_regs + 1;
3350 			RETALLOC(regs->start, regs->num_regs, regoff_t);
3351 			RETALLOC(regs->end, regs->num_regs, regoff_t);
3352 			if (regs->start == NULL || regs->end == NULL)
3353 			    return -2;
3354 		    }
3355 		} else
3356 		    assert(bufp->regs_allocated == REGS_FIXED);
3357 
3358 		/* Convert the pointer data in `regstart' and `regend' to
3359 		 * indices.  Register zero has to be set differently,
3360 		 * since we haven't kept track of any info for it.  */
3361 		if (regs->num_regs > 0) {
3362 		    regs->start[0] = pos;
3363 		    regs->end[0] = (MATCHING_IN_FIRST_STRING ? d - string1
3364 			: d - string2 + size1);
3365 		}
3366 		/* Go through the first `min (num_regs, regs->num_regs)'
3367 		 * registers, since that is all we initialized.  */
3368 		for (mcnt = 1; mcnt < MIN(num_regs, regs->num_regs); mcnt++) {
3369 		    if (REG_UNSET(regstart[mcnt]) || REG_UNSET(regend[mcnt]))
3370 			regs->start[mcnt] = regs->end[mcnt] = -1;
3371 		    else {
3372 			regs->start[mcnt] = POINTER_TO_OFFSET(regstart[mcnt]);
3373 			regs->end[mcnt] = POINTER_TO_OFFSET(regend[mcnt]);
3374 		    }
3375 		}
3376 
3377 		/* If the regs structure we return has more elements than
3378 		 * were in the pattern, set the extra elements to -1.  If
3379 		 * we (re)allocated the registers, this is the case,
3380 		 * because we always allocate enough to have at least one
3381 		 * -1 at the end.  */
3382 		for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
3383 		    regs->start[mcnt] = regs->end[mcnt] = -1;
3384 	    }			/* regs && !bufp->no_sub */
3385 	    FREE_VARIABLES();
3386 	    DEBUG_PRINT4("%u failure points pushed, %u popped (%u remain).\n",
3387 		nfailure_points_pushed, nfailure_points_popped,
3388 		nfailure_points_pushed - nfailure_points_popped);
3389 	    DEBUG_PRINT2("%u registers pushed.\n", num_regs_pushed);
3390 
3391 	    mcnt = d - pos - (MATCHING_IN_FIRST_STRING
3392 		? string1
3393 		: string2 - size1);
3394 
3395 	    DEBUG_PRINT2("Returning %d from re_match_2.\n", mcnt);
3396 
3397 	    return mcnt;
3398 	}
3399 	/* Otherwise match next pattern command.  */
3400 #ifdef SWITCH_ENUM_BUG
3401 	switch ((int) ((re_opcode_t) * p++))
3402 #else
3403 	switch ((re_opcode_t) * p++)
3404 #endif
3405 	{
3406 	    /* Ignore these.  Used to ignore the n of succeed_n's which
3407 	     * currently have n == 0.  */
3408 	case no_op:
3409 	    DEBUG_PRINT1("EXECUTING no_op.\n");
3410 	    break;
3411 
3412 
3413 	    /* Match the next n pattern characters exactly.  The following
3414 	     * byte in the pattern defines n, and the n bytes after that
3415 	     * are the characters to match.  */
3416 	case exactn:
3417 	    mcnt = *p++;
3418 	    DEBUG_PRINT2("EXECUTING exactn %d.\n", mcnt);
3419 
3420 	    /* This is written out as an if-else so we don't waste time
3421 	     * testing `translate' inside the loop.  */
3422 	    if (translate) {
3423 		do {
3424 		    PREFETCH();
3425 		    if (translate[(unsigned char) *d++] != (char) *p++)
3426 			goto fail;
3427 		}
3428 		while (--mcnt);
3429 	    } else {
3430 		do {
3431 		    PREFETCH();
3432 		    if (*d++ != (char) *p++)
3433 			goto fail;
3434 		}
3435 		while (--mcnt);
3436 	    }
3437 	    SET_REGS_MATCHED();
3438 	    break;
3439 
3440 
3441 	    /* Match any character except possibly a newline or a null.  */
3442 	case anychar:
3443 	    DEBUG_PRINT1("EXECUTING anychar.\n");
3444 
3445 	    PREFETCH();
3446 
3447 	    if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE(*d) == '\n')
3448 		|| (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE(*d) == '\000'))
3449 		goto fail;
3450 
3451 	    SET_REGS_MATCHED();
3452 	    DEBUG_PRINT2("  Matched `%d'.\n", *d);
3453 	    d++;
3454 	    break;
3455 
3456 
3457 	case charset:
3458 	case charset_not:
3459 	    {
3460 		register unsigned char c;
3461 		boolean not = (re_opcode_t) * (p - 1) == charset_not;
3462 
3463 		DEBUG_PRINT2("EXECUTING charset%s.\n", not ? "_not" : "");
3464 
3465 		PREFETCH();
3466 		c = TRANSLATE(*d);	/* The character to match.  */
3467 
3468 		/* Cast to `unsigned' instead of `unsigned char' in case the
3469 		 * bit list is a full 32 bytes long.  */
3470 		if (c < (unsigned) (*p * BYTEWIDTH)
3471 		    && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
3472 		    not = !not;
3473 
3474 		p += 1 + *p;
3475 
3476 		if (!not)
3477 		    goto fail;
3478 
3479 		SET_REGS_MATCHED();
3480 		d++;
3481 		break;
3482 	    }
3483 
3484 
3485 	    /* The beginning of a group is represented by start_memory.
3486 	     * The arguments are the register number in the next byte, and the
3487 	     * number of groups inner to this one in the next.  The text
3488 	     * matched within the group is recorded (in the internal
3489 	     * registers data structure) under the register number.  */
3490 	case start_memory:
3491 	    DEBUG_PRINT3("EXECUTING start_memory %d (%d):\n", *p, p[1]);
3492 
3493 	    /* Find out if this group can match the empty string.  */
3494 	    p1 = p;		/* To send to group_match_null_string_p.  */
3495 
3496 	    if (REG_MATCH_NULL_STRING_P(reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
3497 		REG_MATCH_NULL_STRING_P(reg_info[*p])
3498 		    = group_match_null_string_p(&p1, pend, reg_info);
3499 
3500 	    /* Save the position in the string where we were the last time
3501 	     * we were at this open-group operator in case the group is
3502 	     * operated upon by a repetition operator, e.g., with `(a*)*b'
3503 	     * against `ab'; then we want to ignore where we are now in
3504 	     * the string in case this attempt to match fails.  */
3505 	    old_regstart[*p] = REG_MATCH_NULL_STRING_P(reg_info[*p])
3506 		? REG_UNSET(regstart[*p]) ? d : regstart[*p]
3507 		: regstart[*p];
3508 	    DEBUG_PRINT2("  old_regstart: %d\n",
3509 		POINTER_TO_OFFSET(old_regstart[*p]));
3510 
3511 	    regstart[*p] = d;
3512 	    DEBUG_PRINT2("  regstart: %d\n", POINTER_TO_OFFSET(regstart[*p]));
3513 
3514 	    IS_ACTIVE(reg_info[*p]) = 1;
3515 	    MATCHED_SOMETHING(reg_info[*p]) = 0;
3516 
3517 	    /* This is the new highest active register.  */
3518 	    highest_active_reg = *p;
3519 
3520 	    /* If nothing was active before, this is the new lowest active
3521 	     * register.  */
3522 	    if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
3523 		lowest_active_reg = *p;
3524 
3525 	    /* Move past the register number and inner group count.  */
3526 	    p += 2;
3527 	    break;
3528 
3529 
3530 	    /* The stop_memory opcode represents the end of a group.  Its
3531 	     * arguments are the same as start_memory's: the register
3532 	     * number, and the number of inner groups.  */
3533 	case stop_memory:
3534 	    DEBUG_PRINT3("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
3535 
3536 	    /* We need to save the string position the last time we were at
3537 	     * this close-group operator in case the group is operated
3538 	     * upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
3539 	     * against `aba'; then we want to ignore where we are now in
3540 	     * the string in case this attempt to match fails.  */
3541 	    old_regend[*p] = REG_MATCH_NULL_STRING_P(reg_info[*p])
3542 		? REG_UNSET(regend[*p]) ? d : regend[*p]
3543 		: regend[*p];
3544 	    DEBUG_PRINT2("      old_regend: %d\n",
3545 		POINTER_TO_OFFSET(old_regend[*p]));
3546 
3547 	    regend[*p] = d;
3548 	    DEBUG_PRINT2("      regend: %d\n", POINTER_TO_OFFSET(regend[*p]));
3549 
3550 	    /* This register isn't active anymore.  */
3551 	    IS_ACTIVE(reg_info[*p]) = 0;
3552 
3553 	    /* If this was the only register active, nothing is active
3554 	     * anymore.  */
3555 	    if (lowest_active_reg == highest_active_reg) {
3556 		lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3557 		highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3558 	    } else {		/* We must scan for the new highest active register, since
3559 				 * it isn't necessarily one less than now: consider
3560 				 * (a(b)c(d(e)f)g).  When group 3 ends, after the f), the
3561 				 * new highest active register is 1.  */
3562 		unsigned char r = *p - 1;
3563 		while (r > 0 && !IS_ACTIVE(reg_info[r]))
3564 		    r--;
3565 
3566 		/* If we end up at register zero, that means that we saved
3567 		 * the registers as the result of an `on_failure_jump', not
3568 		 * a `start_memory', and we jumped to past the innermost
3569 		 * `stop_memory'.  For example, in ((.)*) we save
3570 		 * registers 1 and 2 as a result of the *, but when we pop
3571 		 * back to the second ), we are at the stop_memory 1.
3572 		 * Thus, nothing is active.  */
3573 		if (r == 0) {
3574 		    lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3575 		    highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3576 		} else
3577 		    highest_active_reg = r;
3578 	    }
3579 
3580 	    /* If just failed to match something this time around with a
3581 	     * group that's operated on by a repetition operator, try to
3582 	     * force exit from the ``loop'', and restore the register
3583 	     * information for this group that we had before trying this
3584 	     * last match.  */
3585 	    if ((!MATCHED_SOMETHING(reg_info[*p])
3586 		    || (re_opcode_t) p[-3] == start_memory)
3587 		&& (p + 2) < pend) {
3588 		boolean is_a_jump_n = false;
3589 
3590 		p1 = p + 2;
3591 		mcnt = 0;
3592 		switch ((re_opcode_t) * p1++) {
3593 		case jump_n:
3594 		    is_a_jump_n = true;
3595 		case pop_failure_jump:
3596 		case maybe_pop_jump:
3597 		case jump:
3598 		case dummy_failure_jump:
3599 		    EXTRACT_NUMBER_AND_INCR(mcnt, p1);
3600 		    if (is_a_jump_n)
3601 			p1 += 2;
3602 		    break;
3603 
3604 		default:
3605 		    /* do nothing */ ;
3606 		}
3607 		p1 += mcnt;
3608 
3609 		/* If the next operation is a jump backwards in the pattern
3610 		 * to an on_failure_jump right before the start_memory
3611 		 * corresponding to this stop_memory, exit from the loop
3612 		 * by forcing a failure after pushing on the stack the
3613 		 * on_failure_jump's jump in the pattern, and d.  */
3614 		if (mcnt < 0 && (re_opcode_t) * p1 == on_failure_jump
3615 		    && (re_opcode_t) p1[3] == start_memory && p1[4] == *p) {
3616 		    /* If this group ever matched anything, then restore
3617 		     * what its registers were before trying this last
3618 		     * failed match, e.g., with `(a*)*b' against `ab' for
3619 		     * regstart[1], and, e.g., with `((a*)*(b*)*)*'
3620 		     * against `aba' for regend[3].
3621 		     *
3622 		     * Also restore the registers for inner groups for,
3623 		     * e.g., `((a*)(b*))*' against `aba' (register 3 would
3624 		     * otherwise get trashed).  */
3625 
3626 		    if (EVER_MATCHED_SOMETHING(reg_info[*p])) {
3627 			unsigned r;
3628 
3629 			EVER_MATCHED_SOMETHING(reg_info[*p]) = 0;
3630 
3631 			/* Restore this and inner groups' (if any) registers.  */
3632 			for (r = *p; r < *p + *(p + 1); r++) {
3633 			    regstart[r] = old_regstart[r];
3634 
3635 			    /* xx why this test?  */
3636 			    if ((long) old_regend[r] >= (long) regstart[r])
3637 				regend[r] = old_regend[r];
3638 			}
3639 		    }
3640 		    p1++;
3641 		    EXTRACT_NUMBER_AND_INCR(mcnt, p1);
3642 		    PUSH_FAILURE_POINT(p1 + mcnt, d, -2);
3643 
3644 		    goto fail;
3645 		}
3646 	    }
3647 	    /* Move past the register number and the inner group count.  */
3648 	    p += 2;
3649 	    break;
3650 
3651 
3652 	    /* \<digit> has been turned into a `duplicate' command which is
3653 	     * followed by the numeric value of <digit> as the register number.  */
3654 	case duplicate:
3655 	    {
3656 		register const char *d2, *dend2;
3657 		int regno = *p++;	/* Get which register to match against.  */
3658 		DEBUG_PRINT2("EXECUTING duplicate %d.\n", regno);
3659 
3660 		/* Can't back reference a group which we've never matched.  */
3661 		if (REG_UNSET(regstart[regno]) || REG_UNSET(regend[regno]))
3662 		    goto fail;
3663 
3664 		/* Where in input to try to start matching.  */
3665 		d2 = regstart[regno];
3666 
3667 		/* Where to stop matching; if both the place to start and
3668 		 * the place to stop matching are in the same string, then
3669 		 * set to the place to stop, otherwise, for now have to use
3670 		 * the end of the first string.  */
3671 
3672 		dend2 = ((FIRST_STRING_P(regstart[regno])
3673 			== FIRST_STRING_P(regend[regno]))
3674 		    ? regend[regno] : end_match_1);
3675 		for (;;) {
3676 		    /* If necessary, advance to next segment in register
3677 		     * contents.  */
3678 		    while (d2 == dend2) {
3679 			if (dend2 == end_match_2)
3680 			    break;
3681 			if (dend2 == regend[regno])
3682 			    break;
3683 
3684 			/* End of string1 => advance to string2. */
3685 			d2 = string2;
3686 			dend2 = regend[regno];
3687 		    }
3688 		    /* At end of register contents => success */
3689 		    if (d2 == dend2)
3690 			break;
3691 
3692 		    /* If necessary, advance to next segment in data.  */
3693 		    PREFETCH();
3694 
3695 		    /* How many characters left in this segment to match.  */
3696 		    mcnt = dend - d;
3697 
3698 		    /* Want how many consecutive characters we can match in
3699 		     * one shot, so, if necessary, adjust the count.  */
3700 		    if (mcnt > dend2 - d2)
3701 			mcnt = dend2 - d2;
3702 
3703 		    /* Compare that many; failure if mismatch, else move
3704 		     * past them.  */
3705 		    if (translate
3706 			? bcmp_translate(d, d2, mcnt, translate)
3707 			: bcmp(d, d2, mcnt))
3708 			goto fail;
3709 		    d += mcnt, d2 += mcnt;
3710 		}
3711 	    }
3712 	    break;
3713 
3714 
3715 	    /* begline matches the empty string at the beginning of the string
3716 	     * (unless `not_bol' is set in `bufp'), and, if
3717 	     * `newline_anchor' is set, after newlines.  */
3718 	case begline:
3719 	    DEBUG_PRINT1("EXECUTING begline.\n");
3720 
3721 	    if (AT_STRINGS_BEG(d)) {
3722 		if (!bufp->not_bol)
3723 		    break;
3724 	    } else if (d[-1] == '\n' && bufp->newline_anchor) {
3725 		break;
3726 	    }
3727 	    /* In all other cases, we fail.  */
3728 	    goto fail;
3729 
3730 
3731 	    /* endline is the dual of begline.  */
3732 	case endline:
3733 	    DEBUG_PRINT1("EXECUTING endline.\n");
3734 
3735 	    if (AT_STRINGS_END(d)) {
3736 		if (!bufp->not_eol)
3737 		    break;
3738 	    }
3739 	    /* We have to ``prefetch'' the next character.  */
3740 	    else if ((d == end1 ? *string2 : *d) == '\n'
3741 		&& bufp->newline_anchor) {
3742 		break;
3743 	    }
3744 	    goto fail;
3745 
3746 
3747 	    /* Match at the very beginning of the data.  */
3748 	case begbuf:
3749 	    DEBUG_PRINT1("EXECUTING begbuf.\n");
3750 	    if (AT_STRINGS_BEG(d))
3751 		break;
3752 	    goto fail;
3753 
3754 
3755 	    /* Match at the very end of the data.  */
3756 	case endbuf:
3757 	    DEBUG_PRINT1("EXECUTING endbuf.\n");
3758 	    if (AT_STRINGS_END(d))
3759 		break;
3760 	    goto fail;
3761 
3762 
3763 	    /* on_failure_keep_string_jump is used to optimize `.*\n'.  It
3764 	     * pushes NULL as the value for the string on the stack.  Then
3765 	     * `pop_failure_point' will keep the current value for the
3766 	     * string, instead of restoring it.  To see why, consider
3767 	     * matching `foo\nbar' against `.*\n'.  The .* matches the foo;
3768 	     * then the . fails against the \n.  But the next thing we want
3769 	     * to do is match the \n against the \n; if we restored the
3770 	     * string value, we would be back at the foo.
3771 	     *
3772 	     * Because this is used only in specific cases, we don't need to
3773 	     * check all the things that `on_failure_jump' does, to make
3774 	     * sure the right things get saved on the stack.  Hence we don't
3775 	     * share its code.  The only reason to push anything on the
3776 	     * stack at all is that otherwise we would have to change
3777 	     * `anychar's code to do something besides goto fail in this
3778 	     * case; that seems worse than this.  */
3779 	case on_failure_keep_string_jump:
3780 	    DEBUG_PRINT1("EXECUTING on_failure_keep_string_jump");
3781 
3782 	    EXTRACT_NUMBER_AND_INCR(mcnt, p);
3783 	    DEBUG_PRINT3(" %d (to 0x%x):\n", mcnt, p + mcnt);
3784 
3785 	    PUSH_FAILURE_POINT(p + mcnt, NULL, -2);
3786 	    break;
3787 
3788 
3789 	    /* Uses of on_failure_jump:
3790 	     *
3791 	     * Each alternative starts with an on_failure_jump that points
3792 	     * to the beginning of the next alternative.  Each alternative
3793 	     * except the last ends with a jump that in effect jumps past
3794 	     * the rest of the alternatives.  (They really jump to the
3795 	     * ending jump of the following alternative, because tensioning
3796 	     * these jumps is a hassle.)
3797 	     *
3798 	     * Repeats start with an on_failure_jump that points past both
3799 	     * the repetition text and either the following jump or
3800 	     * pop_failure_jump back to this on_failure_jump.  */
3801 	case on_failure_jump:
3802 	  on_failure:
3803 	    DEBUG_PRINT1("EXECUTING on_failure_jump");
3804 
3805 	    EXTRACT_NUMBER_AND_INCR(mcnt, p);
3806 	    DEBUG_PRINT3(" %d (to 0x%x)", mcnt, p + mcnt);
3807 
3808 	    /* If this on_failure_jump comes right before a group (i.e.,
3809 	     * the original * applied to a group), save the information
3810 	     * for that group and all inner ones, so that if we fail back
3811 	     * to this point, the group's information will be correct.
3812 	     * For example, in \(a*\)*\1, we need the preceding group,
3813 	     * and in \(\(a*\)b*\)\2, we need the inner group.  */
3814 
3815 	    /* We can't use `p' to check ahead because we push
3816 	     * a failure point to `p + mcnt' after we do this.  */
3817 	    p1 = p;
3818 
3819 	    /* We need to skip no_op's before we look for the
3820 	     * start_memory in case this on_failure_jump is happening as
3821 	     * the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
3822 	     * against aba.  */
3823 	    while (p1 < pend && (re_opcode_t) * p1 == no_op)
3824 		p1++;
3825 
3826 	    if (p1 < pend && (re_opcode_t) * p1 == start_memory) {
3827 		/* We have a new highest active register now.  This will
3828 		 * get reset at the start_memory we are about to get to,
3829 		 * but we will have saved all the registers relevant to
3830 		 * this repetition op, as described above.  */
3831 		highest_active_reg = *(p1 + 1) + *(p1 + 2);
3832 		if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
3833 		    lowest_active_reg = *(p1 + 1);
3834 	    }
3835 	    DEBUG_PRINT1(":\n");
3836 	    PUSH_FAILURE_POINT(p + mcnt, d, -2);
3837 	    break;
3838 
3839 
3840 	    /* A smart repeat ends with `maybe_pop_jump'.
3841 	     * We change it to either `pop_failure_jump' or `jump'.  */
3842 	case maybe_pop_jump:
3843 	    EXTRACT_NUMBER_AND_INCR(mcnt, p);
3844 	    DEBUG_PRINT2("EXECUTING maybe_pop_jump %d.\n", mcnt);
3845 	    {
3846 		register unsigned char *p2 = p;
3847 
3848 		/* Compare the beginning of the repeat with what in the
3849 		 * pattern follows its end. If we can establish that there
3850 		 * is nothing that they would both match, i.e., that we
3851 		 * would have to backtrack because of (as in, e.g., `a*a')
3852 		 * then we can change to pop_failure_jump, because we'll
3853 		 * never have to backtrack.
3854 		 *
3855 		 * This is not true in the case of alternatives: in
3856 		 * `(a|ab)*' we do need to backtrack to the `ab' alternative
3857 		 * (e.g., if the string was `ab').  But instead of trying to
3858 		 * detect that here, the alternative has put on a dummy
3859 		 * failure point which is what we will end up popping.  */
3860 
3861 		/* Skip over open/close-group commands.  */
3862 		while (p2 + 2 < pend
3863 		    && ((re_opcode_t) * p2 == stop_memory
3864 			|| (re_opcode_t) * p2 == start_memory))
3865 		    p2 += 3;	/* Skip over args, too.  */
3866 
3867 		/* If we're at the end of the pattern, we can change.  */
3868 		if (p2 == pend) {
3869 		    /* Consider what happens when matching ":\(.*\)"
3870 		     * against ":/".  I don't really understand this code
3871 		     * yet.  */
3872 		    p[-3] = (unsigned char) pop_failure_jump;
3873 		    DEBUG_PRINT1
3874 			("  End of pattern: change to `pop_failure_jump'.\n");
3875 		} else if ((re_opcode_t) * p2 == exactn
3876 		    || (bufp->newline_anchor && (re_opcode_t) * p2 == endline)) {
3877 		    register unsigned char c
3878 		    = *p2 == (unsigned char) endline ? '\n' : p2[2];
3879 		    p1 = p + mcnt;
3880 
3881 		    /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
3882 		     * to the `maybe_finalize_jump' of this case.  Examine what
3883 		     * follows.  */
3884 		    if ((re_opcode_t) p1[3] == exactn && p1[5] != c) {
3885 			p[-3] = (unsigned char) pop_failure_jump;
3886 			DEBUG_PRINT3("  %c != %c => pop_failure_jump.\n",
3887 			    c, p1[5]);
3888 		    } else if ((re_opcode_t) p1[3] == charset
3889 			|| (re_opcode_t) p1[3] == charset_not) {
3890 			int not = (re_opcode_t) p1[3] == charset_not;
3891 
3892 			if (c < (unsigned char) (p1[4] * BYTEWIDTH)
3893 			    && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
3894 			    not = !not;
3895 
3896 			/* `not' is equal to 1 if c would match, which means
3897 			 * that we can't change to pop_failure_jump.  */
3898 			if (!not) {
3899 			    p[-3] = (unsigned char) pop_failure_jump;
3900 			    DEBUG_PRINT1("  No match => pop_failure_jump.\n");
3901 			}
3902 		    }
3903 		}
3904 	    }
3905 	    p -= 2;		/* Point at relative address again.  */
3906 	    if ((re_opcode_t) p[-1] != pop_failure_jump) {
3907 		p[-1] = (unsigned char) jump;
3908 		DEBUG_PRINT1("  Match => jump.\n");
3909 		goto unconditional_jump;
3910 	    }
3911 	    /* Note fall through.  */
3912 
3913 
3914 	    /* The end of a simple repeat has a pop_failure_jump back to
3915 	     * its matching on_failure_jump, where the latter will push a
3916 	     * failure point.  The pop_failure_jump takes off failure
3917 	     * points put on by this pop_failure_jump's matching
3918 	     * on_failure_jump; we got through the pattern to here from the
3919 	     * matching on_failure_jump, so didn't fail.  */
3920 	case pop_failure_jump:
3921 	    {
3922 		/* We need to pass separate storage for the lowest and
3923 		 * highest registers, even though we don't care about the
3924 		 * actual values.  Otherwise, we will restore only one
3925 		 * register from the stack, since lowest will == highest in
3926 		 * `pop_failure_point'.  */
3927 		unsigned long dummy_low_reg, dummy_high_reg;
3928 		unsigned char *pdummy;
3929 		const char *sdummy;
3930 
3931 		DEBUG_PRINT1("EXECUTING pop_failure_jump.\n");
3932 		POP_FAILURE_POINT(sdummy, pdummy,
3933 		    dummy_low_reg, dummy_high_reg,
3934 		    reg_dummy, reg_dummy, reg_info_dummy);
3935 	    }
3936 	    /* Note fall through.  */
3937 
3938 
3939 	    /* Unconditionally jump (without popping any failure points).  */
3940 	case jump:
3941 	  unconditional_jump:
3942 	    EXTRACT_NUMBER_AND_INCR(mcnt, p);	/* Get the amount to jump.  */
3943 	    DEBUG_PRINT2("EXECUTING jump %d ", mcnt);
3944 	    p += mcnt;		/* Do the jump.  */
3945 	    DEBUG_PRINT2("(to 0x%x).\n", p);
3946 	    break;
3947 
3948 
3949 	    /* We need this opcode so we can detect where alternatives end
3950 	     * in `group_match_null_string_p' et al.  */
3951 	case jump_past_alt:
3952 	    DEBUG_PRINT1("EXECUTING jump_past_alt.\n");
3953 	    goto unconditional_jump;
3954 
3955 
3956 	    /* Normally, the on_failure_jump pushes a failure point, which
3957 	     * then gets popped at pop_failure_jump.  We will end up at
3958 	     * pop_failure_jump, also, and with a pattern of, say, `a+', we
3959 	     * are skipping over the on_failure_jump, so we have to push
3960 	     * something meaningless for pop_failure_jump to pop.  */
3961 	case dummy_failure_jump:
3962 	    DEBUG_PRINT1("EXECUTING dummy_failure_jump.\n");
3963 	    /* It doesn't matter what we push for the string here.  What
3964 	     * the code at `fail' tests is the value for the pattern.  */
3965 	    PUSH_FAILURE_POINT(0, 0, -2);
3966 	    goto unconditional_jump;
3967 
3968 
3969 	    /* At the end of an alternative, we need to push a dummy failure
3970 	     * point in case we are followed by a `pop_failure_jump', because
3971 	     * we don't want the failure point for the alternative to be
3972 	     * popped.  For example, matching `(a|ab)*' against `aab'
3973 	     * requires that we match the `ab' alternative.  */
3974 	case push_dummy_failure:
3975 	    DEBUG_PRINT1("EXECUTING push_dummy_failure.\n");
3976 	    /* See comments just above at `dummy_failure_jump' about the
3977 	     * two zeroes.  */
3978 	    PUSH_FAILURE_POINT(0, 0, -2);
3979 	    break;
3980 
3981 	    /* Have to succeed matching what follows at least n times.
3982 	     * After that, handle like `on_failure_jump'.  */
3983 	case succeed_n:
3984 	    EXTRACT_NUMBER(mcnt, p + 2);
3985 	    DEBUG_PRINT2("EXECUTING succeed_n %d.\n", mcnt);
3986 
3987 	    assert(mcnt >= 0);
3988 	    /* Originally, this is how many times we HAVE to succeed.  */
3989 	    if (mcnt > 0) {
3990 		mcnt--;
3991 		p += 2;
3992 		STORE_NUMBER_AND_INCR(p, mcnt);
3993 		DEBUG_PRINT3("  Setting 0x%x to %d.\n", p, mcnt);
3994 	    } else if (mcnt == 0) {
3995 		DEBUG_PRINT2("  Setting two bytes from 0x%x to no_op.\n", p + 2);
3996 		p[2] = (unsigned char) no_op;
3997 		p[3] = (unsigned char) no_op;
3998 		goto on_failure;
3999 	    }
4000 	    break;
4001 
4002 	case jump_n:
4003 	    EXTRACT_NUMBER(mcnt, p + 2);
4004 	    DEBUG_PRINT2("EXECUTING jump_n %d.\n", mcnt);
4005 
4006 	    /* Originally, this is how many times we CAN jump.  */
4007 	    if (mcnt) {
4008 		mcnt--;
4009 		STORE_NUMBER(p + 2, mcnt);
4010 		goto unconditional_jump;
4011 	    }
4012 	    /* If don't have to jump any more, skip over the rest of command.  */
4013 	    else
4014 		p += 4;
4015 	    break;
4016 
4017 	case set_number_at:
4018 	    {
4019 		DEBUG_PRINT1("EXECUTING set_number_at.\n");
4020 
4021 		EXTRACT_NUMBER_AND_INCR(mcnt, p);
4022 		p1 = p + mcnt;
4023 		EXTRACT_NUMBER_AND_INCR(mcnt, p);
4024 		DEBUG_PRINT3("  Setting 0x%x to %d.\n", p1, mcnt);
4025 		STORE_NUMBER(p1, mcnt);
4026 		break;
4027 	    }
4028 
4029 	case wordbound:
4030 	    DEBUG_PRINT1("EXECUTING wordbound.\n");
4031 	    if (AT_WORD_BOUNDARY(d))
4032 		break;
4033 	    goto fail;
4034 
4035 	case notwordbound:
4036 	    DEBUG_PRINT1("EXECUTING notwordbound.\n");
4037 	    if (AT_WORD_BOUNDARY(d))
4038 		goto fail;
4039 	    break;
4040 
4041 	case wordbeg:
4042 	    DEBUG_PRINT1("EXECUTING wordbeg.\n");
4043 	    if (WORDCHAR_P(d) && (AT_STRINGS_BEG(d) || !WORDCHAR_P(d - 1)))
4044 		break;
4045 	    goto fail;
4046 
4047 	case wordend:
4048 	    DEBUG_PRINT1("EXECUTING wordend.\n");
4049 	    if (!AT_STRINGS_BEG(d) && WORDCHAR_P(d - 1)
4050 		&& (!WORDCHAR_P(d) || AT_STRINGS_END(d)))
4051 		break;
4052 	    goto fail;
4053 
4054 #ifdef emacs
4055 #ifdef emacs19
4056 	case before_dot:
4057 	    DEBUG_PRINT1("EXECUTING before_dot.\n");
4058 	    if (PTR_CHAR_POS((unsigned char *) d) >= point)
4059 		goto fail;
4060 	    break;
4061 
4062 	case at_dot:
4063 	    DEBUG_PRINT1("EXECUTING at_dot.\n");
4064 	    if (PTR_CHAR_POS((unsigned char *) d) != point)
4065 		goto fail;
4066 	    break;
4067 
4068 	case after_dot:
4069 	    DEBUG_PRINT1("EXECUTING after_dot.\n");
4070 	    if (PTR_CHAR_POS((unsigned char *) d) <= point)
4071 		goto fail;
4072 	    break;
4073 #else /* not emacs19 */
4074 	case at_dot:
4075 	    DEBUG_PRINT1("EXECUTING at_dot.\n");
4076 	    if (PTR_CHAR_POS((unsigned char *) d) + 1 != point)
4077 		goto fail;
4078 	    break;
4079 #endif /* not emacs19 */
4080 
4081 	case syntaxspec:
4082 	    DEBUG_PRINT2("EXECUTING syntaxspec %d.\n", mcnt);
4083 	    mcnt = *p++;
4084 	    goto matchsyntax;
4085 
4086 	case wordchar:
4087 	    DEBUG_PRINT1("EXECUTING Emacs wordchar.\n");
4088 	    mcnt = (int) Sword;
4089 	  matchsyntax:
4090 	    PREFETCH();
4091 	    if (SYNTAX(*d++) != (enum syntaxcode) mcnt)
4092 		goto fail;
4093 	    SET_REGS_MATCHED();
4094 	    break;
4095 
4096 	case notsyntaxspec:
4097 	    DEBUG_PRINT2("EXECUTING notsyntaxspec %d.\n", mcnt);
4098 	    mcnt = *p++;
4099 	    goto matchnotsyntax;
4100 
4101 	case notwordchar:
4102 	    DEBUG_PRINT1("EXECUTING Emacs notwordchar.\n");
4103 	    mcnt = (int) Sword;
4104 	  matchnotsyntax:
4105 	    PREFETCH();
4106 	    if (SYNTAX(*d++) == (enum syntaxcode) mcnt)
4107 		goto fail;
4108 	    SET_REGS_MATCHED();
4109 	    break;
4110 
4111 #else /* not emacs */
4112 	case wordchar:
4113 	    DEBUG_PRINT1("EXECUTING non-Emacs wordchar.\n");
4114 	    PREFETCH();
4115 	    if (!WORDCHAR_P(d))
4116 		goto fail;
4117 	    SET_REGS_MATCHED();
4118 	    d++;
4119 	    break;
4120 
4121 	case notwordchar:
4122 	    DEBUG_PRINT1("EXECUTING non-Emacs notwordchar.\n");
4123 	    PREFETCH();
4124 	    if (WORDCHAR_P(d))
4125 		goto fail;
4126 	    SET_REGS_MATCHED();
4127 	    d++;
4128 	    break;
4129 #endif /* not emacs */
4130 
4131 	default:
4132 	    abort();
4133 	}
4134 	continue;		/* Successfully executed one pattern command; keep going.  */
4135 
4136 
4137 	/* We goto here if a matching operation fails. */
4138       fail:
4139 	if (!FAIL_STACK_EMPTY()) {	/* A restart point is known.  Restore to that state.  */
4140 	    DEBUG_PRINT1("\nFAIL:\n");
4141 	    POP_FAILURE_POINT(d, p,
4142 		lowest_active_reg, highest_active_reg,
4143 		regstart, regend, reg_info);
4144 
4145 	    /* If this failure point is a dummy, try the next one.  */
4146 	    if (!p)
4147 		goto fail;
4148 
4149 	    /* If we failed to the end of the pattern, don't examine *p.  */
4150 	    assert(p <= pend);
4151 	    if (p < pend) {
4152 		boolean is_a_jump_n = false;
4153 
4154 		/* If failed to a backwards jump that's part of a repetition
4155 		 * loop, need to pop this failure point and use the next one.  */
4156 		switch ((re_opcode_t) * p) {
4157 		case jump_n:
4158 		    is_a_jump_n = true;
4159 		case maybe_pop_jump:
4160 		case pop_failure_jump:
4161 		case jump:
4162 		    p1 = p + 1;
4163 		    EXTRACT_NUMBER_AND_INCR(mcnt, p1);
4164 		    p1 += mcnt;
4165 
4166 		    if ((is_a_jump_n && (re_opcode_t) * p1 == succeed_n)
4167 			|| (!is_a_jump_n
4168 			    && (re_opcode_t) * p1 == on_failure_jump))
4169 			goto fail;
4170 		    break;
4171 		default:
4172 		    /* do nothing */ ;
4173 		}
4174 	    }
4175 	    if (d >= string1 && d <= end1)
4176 		dend = end_match_1;
4177 	} else
4178 	    break;		/* Matching at this starting point really fails.  */
4179     }				/* for (;;) */
4180 
4181     if (best_regs_set)
4182 	goto restore_best_regs;
4183 
4184     FREE_VARIABLES();
4185 
4186     return -1;			/* Failure to match.  */
4187 }				/* re_match_2 */
4188 
4189 /* Subroutine definitions for re_match_2.  */
4190 
4191 
4192 /* We are passed P pointing to a register number after a start_memory.
4193  *
4194  * Return true if the pattern up to the corresponding stop_memory can
4195  * match the empty string, and false otherwise.
4196  *
4197  * If we find the matching stop_memory, sets P to point to one past its number.
4198  * Otherwise, sets P to an undefined byte less than or equal to END.
4199  *
4200  * We don't handle duplicates properly (yet).  */
4201 
4202 static boolean
group_match_null_string_p(p,end,reg_info)4203 group_match_null_string_p(p, end, reg_info)
4204      unsigned char **p, *end;
4205      register_info_type *reg_info;
4206 {
4207     int mcnt;
4208     /* Point to after the args to the start_memory.  */
4209     unsigned char *p1 = *p + 2;
4210 
4211     while (p1 < end) {
4212 	/* Skip over opcodes that can match nothing, and return true or
4213 	 * false, as appropriate, when we get to one that can't, or to the
4214 	 * matching stop_memory.  */
4215 
4216 	switch ((re_opcode_t) * p1) {
4217 	    /* Could be either a loop or a series of alternatives.  */
4218 	case on_failure_jump:
4219 	    p1++;
4220 	    EXTRACT_NUMBER_AND_INCR(mcnt, p1);
4221 
4222 	    /* If the next operation is not a jump backwards in the
4223 	     * pattern.  */
4224 
4225 	    if (mcnt >= 0) {
4226 		/* Go through the on_failure_jumps of the alternatives,
4227 		 * seeing if any of the alternatives cannot match nothing.
4228 		 * The last alternative starts with only a jump,
4229 		 * whereas the rest start with on_failure_jump and end
4230 		 * with a jump, e.g., here is the pattern for `a|b|c':
4231 		 *
4232 		 * /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
4233 		 * /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
4234 		 * /exactn/1/c
4235 		 *
4236 		 * So, we have to first go through the first (n-1)
4237 		 * alternatives and then deal with the last one separately.  */
4238 
4239 
4240 		/* Deal with the first (n-1) alternatives, which start
4241 		 * with an on_failure_jump (see above) that jumps to right
4242 		 * past a jump_past_alt.  */
4243 
4244 		while ((re_opcode_t) p1[mcnt - 3] == jump_past_alt) {
4245 		    /* `mcnt' holds how many bytes long the alternative
4246 		     * is, including the ending `jump_past_alt' and
4247 		     * its number.  */
4248 
4249 		    if (!alt_match_null_string_p(p1, p1 + mcnt - 3,
4250 			    reg_info))
4251 			return false;
4252 
4253 		    /* Move to right after this alternative, including the
4254 		     * jump_past_alt.  */
4255 		    p1 += mcnt;
4256 
4257 		    /* Break if it's the beginning of an n-th alternative
4258 		     * that doesn't begin with an on_failure_jump.  */
4259 		    if ((re_opcode_t) * p1 != on_failure_jump)
4260 			break;
4261 
4262 		    /* Still have to check that it's not an n-th
4263 		     * alternative that starts with an on_failure_jump.  */
4264 		    p1++;
4265 		    EXTRACT_NUMBER_AND_INCR(mcnt, p1);
4266 		    if ((re_opcode_t) p1[mcnt - 3] != jump_past_alt) {
4267 			/* Get to the beginning of the n-th alternative.  */
4268 			p1 -= 3;
4269 			break;
4270 		    }
4271 		}
4272 
4273 		/* Deal with the last alternative: go back and get number
4274 		 * of the `jump_past_alt' just before it.  `mcnt' contains
4275 		 * the length of the alternative.  */
4276 		EXTRACT_NUMBER(mcnt, p1 - 2);
4277 
4278 		if (!alt_match_null_string_p(p1, p1 + mcnt, reg_info))
4279 		    return false;
4280 
4281 		p1 += mcnt;	/* Get past the n-th alternative.  */
4282 	    }			/* if mcnt > 0 */
4283 	    break;
4284 
4285 
4286 	case stop_memory:
4287 	    assert(p1[1] == **p);
4288 	    *p = p1 + 2;
4289 	    return true;
4290 
4291 
4292 	default:
4293 	    if (!common_op_match_null_string_p(&p1, end, reg_info))
4294 		return false;
4295 	}
4296     }				/* while p1 < end */
4297 
4298     return false;
4299 }				/* group_match_null_string_p */
4300 
4301 
4302 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
4303  * It expects P to be the first byte of a single alternative and END one
4304  * byte past the last. The alternative can contain groups.  */
4305 
4306 static boolean
alt_match_null_string_p(p,end,reg_info)4307 alt_match_null_string_p(p, end, reg_info)
4308      unsigned char *p, *end;
4309      register_info_type *reg_info;
4310 {
4311     int mcnt;
4312     unsigned char *p1 = p;
4313 
4314     while (p1 < end) {
4315 	/* Skip over opcodes that can match nothing, and break when we get
4316 	 * to one that can't.  */
4317 
4318 	switch ((re_opcode_t) * p1) {
4319 	    /* It's a loop.  */
4320 	case on_failure_jump:
4321 	    p1++;
4322 	    EXTRACT_NUMBER_AND_INCR(mcnt, p1);
4323 	    p1 += mcnt;
4324 	    break;
4325 
4326 	default:
4327 	    if (!common_op_match_null_string_p(&p1, end, reg_info))
4328 		return false;
4329 	}
4330     }				/* while p1 < end */
4331 
4332     return true;
4333 }				/* alt_match_null_string_p */
4334 
4335 
4336 /* Deals with the ops common to group_match_null_string_p and
4337  * alt_match_null_string_p.
4338  *
4339  * Sets P to one after the op and its arguments, if any.  */
4340 
4341 static boolean
common_op_match_null_string_p(p,end,reg_info)4342 common_op_match_null_string_p(p, end, reg_info)
4343      unsigned char **p, *end;
4344      register_info_type *reg_info;
4345 {
4346     int mcnt;
4347     boolean ret;
4348     int reg_no;
4349     unsigned char *p1 = *p;
4350 
4351     switch ((re_opcode_t) * p1++) {
4352     case no_op:
4353     case begline:
4354     case endline:
4355     case begbuf:
4356     case endbuf:
4357     case wordbeg:
4358     case wordend:
4359     case wordbound:
4360     case notwordbound:
4361 #ifdef emacs
4362     case before_dot:
4363     case at_dot:
4364     case after_dot:
4365 #endif
4366 	break;
4367 
4368     case start_memory:
4369 	reg_no = *p1;
4370 	assert(reg_no > 0 && reg_no <= MAX_REGNUM);
4371 	ret = group_match_null_string_p(&p1, end, reg_info);
4372 
4373 	/* Have to set this here in case we're checking a group which
4374 	 * contains a group and a back reference to it.  */
4375 
4376 	if (REG_MATCH_NULL_STRING_P(reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
4377 	    REG_MATCH_NULL_STRING_P(reg_info[reg_no]) = ret;
4378 
4379 	if (!ret)
4380 	    return false;
4381 	break;
4382 
4383 	/* If this is an optimized succeed_n for zero times, make the jump.  */
4384     case jump:
4385 	EXTRACT_NUMBER_AND_INCR(mcnt, p1);
4386 	if (mcnt >= 0)
4387 	    p1 += mcnt;
4388 	else
4389 	    return false;
4390 	break;
4391 
4392     case succeed_n:
4393 	/* Get to the number of times to succeed.  */
4394 	p1 += 2;
4395 	EXTRACT_NUMBER_AND_INCR(mcnt, p1);
4396 
4397 	if (mcnt == 0) {
4398 	    p1 -= 4;
4399 	    EXTRACT_NUMBER_AND_INCR(mcnt, p1);
4400 	    p1 += mcnt;
4401 	} else
4402 	    return false;
4403 	break;
4404 
4405     case duplicate:
4406 	if (!REG_MATCH_NULL_STRING_P(reg_info[*p1]))
4407 	    return false;
4408 	break;
4409 
4410     case set_number_at:
4411 	p1 += 4;
4412 
4413     default:
4414 	/* All other opcodes mean we cannot match the empty string.  */
4415 	return false;
4416     }
4417 
4418     *p = p1;
4419     return true;
4420 }				/* common_op_match_null_string_p */
4421 
4422 
4423 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
4424  * bytes; nonzero otherwise.  */
4425 
4426 static int
bcmp_translate(s1,s2,len,translate)4427 bcmp_translate(s1, s2, len, translate)
4428      unsigned char *s1, *s2;
4429      register int len;
4430      char *translate;
4431 {
4432     register unsigned char *p1 = s1, *p2 = s2;
4433     while (len) {
4434 	if (translate[*p1++] != translate[*p2++])
4435 	    return 1;
4436 	len--;
4437     }
4438     return 0;
4439 }
4440 
4441 /* Entry points for GNU code.  */
4442 
4443 /* re_compile_pattern is the GNU regular expression compiler: it
4444  * compiles PATTERN (of length SIZE) and puts the result in BUFP.
4445  * Returns 0 if the pattern was valid, otherwise an error string.
4446  *
4447  * Assumes the `allocated' (and perhaps `buffer') and `translate' fields
4448  * are set in BUFP on entry.
4449  *
4450  * We call regex_compile to do the actual compilation.  */
4451 
4452 const char *
re_compile_pattern(pattern,length,bufp)4453 re_compile_pattern(pattern, length, bufp)
4454      const char *pattern;
4455      int length;
4456      struct re_pattern_buffer *bufp;
4457 {
4458     reg_errcode_t ret;
4459 
4460     /* GNU code is written to assume at least RE_NREGS registers will be set
4461      * (and at least one extra will be -1).  */
4462     bufp->regs_allocated = REGS_UNALLOCATED;
4463 
4464     /* And GNU code determines whether or not to get register information
4465      * by passing null for the REGS argument to re_match, etc., not by
4466      * setting no_sub.  */
4467     bufp->no_sub = 0;
4468 
4469     /* Match anchors at newline.  */
4470     bufp->newline_anchor = 1;
4471 
4472     ret = regex_compile(pattern, length, re_syntax_options, bufp);
4473 
4474     return re_error_msg[(int) ret];
4475 }
4476 
4477 /* Entry points compatible with 4.2 BSD regex library.  We don't define
4478  * them if this is an Emacs or POSIX compilation.  */
4479 
4480 #if !defined (emacs) && !defined (_POSIX_SOURCE)
4481 
4482 /* BSD has one and only one pattern buffer.  */
4483 static struct re_pattern_buffer re_comp_buf;
4484 
4485 char *
re_comp(s)4486 re_comp(s)
4487      const char *s;
4488 {
4489     reg_errcode_t ret;
4490 
4491     if (!s) {
4492 	if (!re_comp_buf.buffer)
4493 	    return "No previous regular expression";
4494 	return 0;
4495     }
4496     if (!re_comp_buf.buffer) {
4497 	re_comp_buf.buffer = (unsigned char *) malloc(200);
4498 	if (re_comp_buf.buffer == NULL)
4499 	    return "Memory exhausted";
4500 	re_comp_buf.allocated = 200;
4501 
4502 	re_comp_buf.fastmap = (char *) malloc(1 << BYTEWIDTH);
4503 	if (re_comp_buf.fastmap == NULL)
4504 	    return "Memory exhausted";
4505     }
4506     /* Since `re_exec' always passes NULL for the `regs' argument, we
4507      * don't need to initialize the pattern buffer fields which affect it.  */
4508 
4509     /* Match anchors at newlines.  */
4510     re_comp_buf.newline_anchor = 1;
4511 
4512     ret = regex_compile(s, strlen(s), re_syntax_options, &re_comp_buf);
4513 
4514     /* Yes, we're discarding `const' here.  */
4515     return (char *) re_error_msg[(int) ret];
4516 }
4517 
4518 
4519 int
re_exec(s)4520 re_exec(s)
4521      const char *s;
4522 {
4523     const int len = strlen(s);
4524     return
4525 	0 <= re_search(&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
4526 }
4527 
4528 #endif /* not emacs and not _POSIX_SOURCE */
4529 
4530 /* POSIX.2 functions.  Don't define these for Emacs.  */
4531 
4532 #ifndef emacs
4533 
4534 /* regcomp takes a regular expression as a string and compiles it.
4535  *
4536  * PREG is a regex_t *.  We do not expect any fields to be initialized,
4537  * since POSIX says we shouldn't.  Thus, we set
4538  *
4539  * `buffer' to the compiled pattern;
4540  * `used' to the length of the compiled pattern;
4541  * `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
4542  * REG_EXTENDED bit in CFLAGS is set; otherwise, to
4543  * RE_SYNTAX_POSIX_BASIC;
4544  * `newline_anchor' to REG_NEWLINE being set in CFLAGS;
4545  * `fastmap' and `fastmap_accurate' to zero;
4546  * `re_nsub' to the number of subexpressions in PATTERN.
4547  *
4548  * PATTERN is the address of the pattern string.
4549  *
4550  * CFLAGS is a series of bits which affect compilation.
4551  *
4552  * If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
4553  * use POSIX basic syntax.
4554  *
4555  * If REG_NEWLINE is set, then . and [^...] don't match newline.
4556  * Also, regexec will try a match beginning after every newline.
4557  *
4558  * If REG_ICASE is set, then we considers upper- and lowercase
4559  * versions of letters to be equivalent when matching.
4560  *
4561  * If REG_NOSUB is set, then when PREG is passed to regexec, that
4562  * routine will report only success or failure, and nothing about the
4563  * registers.
4564  *
4565  * It returns 0 if it succeeds, nonzero if it doesn't.  (See regex.h for
4566  * the return codes and their meanings.)  */
4567 
4568 int
regcomp(preg,pattern,cflags)4569 regcomp(preg, pattern, cflags)
4570      regex_t *preg;
4571      const char *pattern;
4572      int cflags;
4573 {
4574     reg_errcode_t ret;
4575     unsigned syntax
4576     = (cflags & REG_EXTENDED) ?
4577     RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
4578 
4579     /* regex_compile will allocate the space for the compiled pattern.  */
4580     preg->buffer = 0;
4581     preg->allocated = 0;
4582 
4583     /* Don't bother to use a fastmap when searching.  This simplifies the
4584      * REG_NEWLINE case: if we used a fastmap, we'd have to put all the
4585      * characters after newlines into the fastmap.  This way, we just try
4586      * every character.  */
4587     preg->fastmap = 0;
4588 
4589     if (cflags & REG_ICASE) {
4590 	unsigned i;
4591 
4592 	preg->translate = (char *) malloc(CHAR_SET_SIZE);
4593 	if (preg->translate == NULL)
4594 	    return (int) REG_ESPACE;
4595 
4596 	/* Map uppercase characters to corresponding lowercase ones.  */
4597 	for (i = 0; i < CHAR_SET_SIZE; i++)
4598 	    preg->translate[i] = ISUPPER(i) ? tolower(i) : i;
4599     } else
4600 	preg->translate = NULL;
4601 
4602     /* If REG_NEWLINE is set, newlines are treated differently.  */
4603     if (cflags & REG_NEWLINE) {	/* REG_NEWLINE implies neither . nor [^...] match newline.  */
4604 	syntax &= ~RE_DOT_NEWLINE;
4605 	syntax |= RE_HAT_LISTS_NOT_NEWLINE;
4606 	/* It also changes the matching behavior.  */
4607 	preg->newline_anchor = 1;
4608     } else
4609 	preg->newline_anchor = 0;
4610 
4611     preg->no_sub = !!(cflags & REG_NOSUB);
4612 
4613     /* POSIX says a null character in the pattern terminates it, so we
4614      * can use strlen here in compiling the pattern.  */
4615     ret = regex_compile(pattern, strlen(pattern), syntax, preg);
4616 
4617     /* POSIX doesn't distinguish between an unmatched open-group and an
4618      * unmatched close-group: both are REG_EPAREN.  */
4619     if (ret == REG_ERPAREN)
4620 	ret = REG_EPAREN;
4621 
4622     return (int) ret;
4623 }
4624 
4625 
4626 /* regexec searches for a given pattern, specified by PREG, in the
4627  * string STRING.
4628  *
4629  * If NMATCH is zero or REG_NOSUB was set in the cflags argument to
4630  * `regcomp', we ignore PMATCH.  Otherwise, we assume PMATCH has at
4631  * least NMATCH elements, and we set them to the offsets of the
4632  * corresponding matched substrings.
4633  *
4634  * EFLAGS specifies `execution flags' which affect matching: if
4635  * REG_NOTBOL is set, then ^ does not match at the beginning of the
4636  * string; if REG_NOTEOL is set, then $ does not match at the end.
4637  *
4638  * We return 0 if we find a match and REG_NOMATCH if not.  */
4639 
4640 int
regexec(preg,string,nmatch,pmatch,eflags)4641 regexec(preg, string, nmatch, pmatch, eflags)
4642      const regex_t *preg;
4643      const char *string;
4644      size_t nmatch;
4645      regmatch_t pmatch[];
4646      int eflags;
4647 {
4648     int ret;
4649     struct re_registers regs;
4650     regex_t private_preg;
4651     int len = strlen(string);
4652     boolean want_reg_info = !preg->no_sub && nmatch > 0;
4653 
4654     private_preg = *preg;
4655 
4656     private_preg.not_bol = !!(eflags & REG_NOTBOL);
4657     private_preg.not_eol = !!(eflags & REG_NOTEOL);
4658 
4659     /* The user has told us exactly how many registers to return
4660      * information about, via `nmatch'.  We have to pass that on to the
4661      * matching routines.  */
4662     private_preg.regs_allocated = REGS_FIXED;
4663 
4664     if (want_reg_info) {
4665 	regs.num_regs = nmatch;
4666 	regs.start = TALLOC(nmatch, regoff_t);
4667 	regs.end = TALLOC(nmatch, regoff_t);
4668 	if (regs.start == NULL || regs.end == NULL)
4669 	    return (int) REG_NOMATCH;
4670     }
4671     /* Perform the searching operation.  */
4672     ret = re_search(&private_preg, string, len,
4673 	/* start: */ 0, /* range: */ len,
4674 	want_reg_info ? &regs : (struct re_registers *) 0);
4675 
4676     /* Copy the register information to the POSIX structure.  */
4677     if (want_reg_info) {
4678 	if (ret >= 0) {
4679 	    unsigned r;
4680 
4681 	    for (r = 0; r < nmatch; r++) {
4682 		pmatch[r].rm_so = regs.start[r];
4683 		pmatch[r].rm_eo = regs.end[r];
4684 	    }
4685 	}
4686 	/* If we needed the temporary register info, free the space now.  */
4687 	free(regs.start);
4688 	free(regs.end);
4689     }
4690     /* We want zero return to mean success, unlike `re_search'.  */
4691     return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
4692 }
4693 
4694 
4695 /* Returns a message corresponding to an error code, ERRCODE, returned
4696  * from either regcomp or regexec.   We don't use PREG here.  */
4697 
4698 size_t
regerror(errcode,preg,errbuf,errbuf_size)4699 regerror(errcode, preg, errbuf, errbuf_size)
4700      int errcode;
4701      const regex_t *preg;
4702      char *errbuf;
4703      size_t errbuf_size;
4704 {
4705     const char *msg;
4706     size_t msg_size;
4707 
4708     if (errcode < 0
4709 	|| errcode >= (sizeof(re_error_msg) / sizeof(re_error_msg[0])))
4710 	/* Only error codes returned by the rest of the code should be passed
4711 	 * to this routine.  If we are given anything else, or if other regex
4712 	 * code generates an invalid error code, then the program has a bug.
4713 	 * Dump core so we can fix it.  */
4714 	abort();
4715 
4716     msg = re_error_msg[errcode];
4717 
4718     /* POSIX doesn't require that we do anything in this case, but why
4719      * not be nice.  */
4720     if (!msg)
4721 	msg = "Success";
4722 
4723     msg_size = strlen(msg) + 1;	/* Includes the null.  */
4724 
4725     if (errbuf_size != 0) {
4726 	if (msg_size > errbuf_size) {
4727 	    strncpy(errbuf, msg, errbuf_size - 1);
4728 	    errbuf[errbuf_size - 1] = 0;
4729 	} else
4730 	    strcpy(errbuf, msg);
4731     }
4732     return msg_size;
4733 }
4734 
4735 
4736 /* Free dynamically allocated space used by PREG.  */
4737 
4738 void
regfree(preg)4739 regfree(preg)
4740      regex_t *preg;
4741 {
4742     if (preg->buffer != NULL)
4743 	free(preg->buffer);
4744     preg->buffer = NULL;
4745 
4746     preg->allocated = 0;
4747     preg->used = 0;
4748 
4749     if (preg->fastmap != NULL)
4750 	free(preg->fastmap);
4751     preg->fastmap = NULL;
4752     preg->fastmap_accurate = 0;
4753 
4754     if (preg->translate != NULL)
4755 	free(preg->translate);
4756     preg->translate = NULL;
4757 }
4758 
4759 #endif /* not emacs  */
4760 
4761 /*
4762  * Local variables:
4763  * make-backup-files: t
4764  * version-control: t
4765  * trim-versions-without-asking: nil
4766  * End:
4767  */
4768