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