OSDN Git Service

66f1ef8c6db359d1d423648811cca687ec1a4407
[pf3gnuchains/gcc-fork.git] / libiberty / regex.c
1 /* Extended regular expression matching and search library,
2    version 0.12.
3    (Implements POSIX draft P1003.2/D11.2, except for some of the
4    internationalization features.)
5    Copyright (C) 1993-1999, 2000, 2001, 2002 Free Software Foundation, Inc.
6    This file is part of the GNU C Library.
7
8    The GNU C Library is free software; you can redistribute it and/or
9    modify it under the terms of the GNU Lesser General Public
10    License as published by the Free Software Foundation; either
11    version 2.1 of the License, or (at your option) any later version.
12
13    The GNU C Library is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16    Lesser General Public License for more details.
17
18    You should have received a copy of the GNU Lesser General Public
19    License along with the GNU C Library; if not, write to the Free
20    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
21    02111-1307 USA.  */
22
23 /* This file has been modified for usage in libiberty.  It includes "xregex.h"
24    instead of <regex.h>.  The "xregex.h" header file renames all external
25    routines with an "x" prefix so they do not collide with the native regex
26    routines or with other components regex routines. */
27 /* AIX requires this to be the first thing in the file. */
28 #if defined _AIX && !defined __GNUC__ && !defined REGEX_MALLOC
29   #pragma alloca
30 #endif
31
32 #undef  _GNU_SOURCE
33 #define _GNU_SOURCE
34
35 #ifndef INSIDE_RECURSION
36 # ifdef HAVE_CONFIG_H
37 #  include <config.h>
38 # endif
39 #endif
40
41 #include <ansidecl.h>
42
43 #ifndef INSIDE_RECURSION
44
45 # if defined STDC_HEADERS && !defined emacs
46 #  include <stddef.h>
47 # else
48 /* We need this for `regex.h', and perhaps for the Emacs include files.  */
49 #  include <sys/types.h>
50 # endif
51
52 # define WIDE_CHAR_SUPPORT (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC)
53
54 /* For platform which support the ISO C amendement 1 functionality we
55    support user defined character classes.  */
56 # if defined _LIBC || WIDE_CHAR_SUPPORT
57 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>.  */
58 #  include <wchar.h>
59 #  include <wctype.h>
60 # endif
61
62 # ifdef _LIBC
63 /* We have to keep the namespace clean.  */
64 #  define regfree(preg) __regfree (preg)
65 #  define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
66 #  define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
67 #  define regerror(errcode, preg, errbuf, errbuf_size) \
68         __regerror(errcode, preg, errbuf, errbuf_size)
69 #  define re_set_registers(bu, re, nu, st, en) \
70         __re_set_registers (bu, re, nu, st, en)
71 #  define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
72         __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
73 #  define re_match(bufp, string, size, pos, regs) \
74         __re_match (bufp, string, size, pos, regs)
75 #  define re_search(bufp, string, size, startpos, range, regs) \
76         __re_search (bufp, string, size, startpos, range, regs)
77 #  define re_compile_pattern(pattern, length, bufp) \
78         __re_compile_pattern (pattern, length, bufp)
79 #  define re_set_syntax(syntax) __re_set_syntax (syntax)
80 #  define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
81         __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
82 #  define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
83
84 #  define btowc __btowc
85
86 /* We are also using some library internals.  */
87 #  include <locale/localeinfo.h>
88 #  include <locale/elem-hash.h>
89 #  include <langinfo.h>
90 #  include <locale/coll-lookup.h>
91 # endif
92
93 /* This is for other GNU distributions with internationalized messages.  */
94 # if (HAVE_LIBINTL_H && ENABLE_NLS) || defined _LIBC
95 #  include <libintl.h>
96 #  ifdef _LIBC
97 #   undef gettext
98 #   define gettext(msgid) __dcgettext ("libc", msgid, LC_MESSAGES)
99 #  endif
100 # else
101 #  define gettext(msgid) (msgid)
102 # endif
103
104 # ifndef gettext_noop
105 /* This define is so xgettext can find the internationalizable
106    strings.  */
107 #  define gettext_noop(String) String
108 # endif
109
110 /* The `emacs' switch turns on certain matching commands
111    that make sense only in Emacs. */
112 # ifdef emacs
113
114 #  include "lisp.h"
115 #  include "buffer.h"
116 #  include "syntax.h"
117
118 # else  /* not emacs */
119
120 /* If we are not linking with Emacs proper,
121    we can't use the relocating allocator
122    even if config.h says that we can.  */
123 #  undef REL_ALLOC
124
125 #  if defined STDC_HEADERS || defined _LIBC
126 #   include <stdlib.h>
127 #  else
128 char *malloc ();
129 char *realloc ();
130 #  endif
131
132 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
133    If nothing else has been done, use the method below.  */
134 #  ifdef INHIBIT_STRING_HEADER
135 #   if !(defined HAVE_BZERO && defined HAVE_BCOPY)
136 #    if !defined bzero && !defined bcopy
137 #     undef INHIBIT_STRING_HEADER
138 #    endif
139 #   endif
140 #  endif
141
142 /* This is the normal way of making sure we have a bcopy and a bzero.
143    This is used in most programs--a few other programs avoid this
144    by defining INHIBIT_STRING_HEADER.  */
145 #  ifndef INHIBIT_STRING_HEADER
146 #   if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
147 #    include <string.h>
148 #    ifndef bzero
149 #     ifndef _LIBC
150 #      define bzero(s, n)       (memset (s, '\0', n), (s))
151 #     else
152 #      define bzero(s, n)       __bzero (s, n)
153 #     endif
154 #    endif
155 #   else
156 #    include <strings.h>
157 #    ifndef memcmp
158 #     define memcmp(s1, s2, n)  bcmp (s1, s2, n)
159 #    endif
160 #    ifndef memcpy
161 #     define memcpy(d, s, n)    (bcopy (s, d, n), (d))
162 #    endif
163 #   endif
164 #  endif
165
166 /* Define the syntax stuff for \<, \>, etc.  */
167
168 /* This must be nonzero for the wordchar and notwordchar pattern
169    commands in re_match_2.  */
170 #  ifndef Sword
171 #   define Sword 1
172 #  endif
173
174 #  ifdef SWITCH_ENUM_BUG
175 #   define SWITCH_ENUM_CAST(x) ((int)(x))
176 #  else
177 #   define SWITCH_ENUM_CAST(x) (x)
178 #  endif
179
180 # endif /* not emacs */
181
182 # if defined _LIBC || HAVE_LIMITS_H
183 #  include <limits.h>
184 # endif
185
186 # ifndef MB_LEN_MAX
187 #  define MB_LEN_MAX 1
188 # endif
189 \f
190 /* Get the interface, including the syntax bits.  */
191 # include "xregex.h"  /* change for libiberty */
192
193 /* isalpha etc. are used for the character classes.  */
194 # include <ctype.h>
195
196 /* Jim Meyering writes:
197
198    "... Some ctype macros are valid only for character codes that
199    isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
200    using /bin/cc or gcc but without giving an ansi option).  So, all
201    ctype uses should be through macros like ISPRINT...  If
202    STDC_HEADERS is defined, then autoconf has verified that the ctype
203    macros don't need to be guarded with references to isascii. ...
204    Defining isascii to 1 should let any compiler worth its salt
205    eliminate the && through constant folding."
206    Solaris defines some of these symbols so we must undefine them first.  */
207
208 # undef ISASCII
209 # if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
210 #  define ISASCII(c) 1
211 # else
212 #  define ISASCII(c) isascii(c)
213 # endif
214
215 # ifdef isblank
216 #  define ISBLANK(c) (ISASCII (c) && isblank (c))
217 # else
218 #  define ISBLANK(c) ((c) == ' ' || (c) == '\t')
219 # endif
220 # ifdef isgraph
221 #  define ISGRAPH(c) (ISASCII (c) && isgraph (c))
222 # else
223 #  define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
224 # endif
225
226 # undef ISPRINT
227 # define ISPRINT(c) (ISASCII (c) && isprint (c))
228 # define ISDIGIT(c) (ISASCII (c) && isdigit (c))
229 # define ISALNUM(c) (ISASCII (c) && isalnum (c))
230 # define ISALPHA(c) (ISASCII (c) && isalpha (c))
231 # define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
232 # define ISLOWER(c) (ISASCII (c) && islower (c))
233 # define ISPUNCT(c) (ISASCII (c) && ispunct (c))
234 # define ISSPACE(c) (ISASCII (c) && isspace (c))
235 # define ISUPPER(c) (ISASCII (c) && isupper (c))
236 # define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
237
238 # ifdef _tolower
239 #  define TOLOWER(c) _tolower(c)
240 # else
241 #  define TOLOWER(c) tolower(c)
242 # endif
243
244 # ifndef NULL
245 #  define NULL (void *)0
246 # endif
247
248 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
249    since ours (we hope) works properly with all combinations of
250    machines, compilers, `char' and `unsigned char' argument types.
251    (Per Bothner suggested the basic approach.)  */
252 # undef SIGN_EXTEND_CHAR
253 # if __STDC__
254 #  define SIGN_EXTEND_CHAR(c) ((signed char) (c))
255 # else  /* not __STDC__ */
256 /* As in Harbison and Steele.  */
257 #  define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
258 # endif
259 \f
260 # ifndef emacs
261 /* How many characters in the character set.  */
262 #  define CHAR_SET_SIZE 256
263
264 #  ifdef SYNTAX_TABLE
265
266 extern char *re_syntax_table;
267
268 #  else /* not SYNTAX_TABLE */
269
270 static char re_syntax_table[CHAR_SET_SIZE];
271
272 static void init_syntax_once (void);
273
274 static void
275 init_syntax_once (void)
276 {
277    register int c;
278    static int done = 0;
279
280    if (done)
281      return;
282    bzero (re_syntax_table, sizeof re_syntax_table);
283
284    for (c = 0; c < CHAR_SET_SIZE; ++c)
285      if (ISALNUM (c))
286         re_syntax_table[c] = Sword;
287
288    re_syntax_table['_'] = Sword;
289
290    done = 1;
291 }
292
293 #  endif /* not SYNTAX_TABLE */
294
295 #  define SYNTAX(c) re_syntax_table[(unsigned char) (c)]
296
297 # endif /* emacs */
298 \f
299 /* Integer type for pointers.  */
300 # if !defined _LIBC && !defined HAVE_UINTPTR_T
301 typedef unsigned long int uintptr_t;
302 # endif
303
304 /* Should we use malloc or alloca?  If REGEX_MALLOC is not defined, we
305    use `alloca' instead of `malloc'.  This is because using malloc in
306    re_search* or re_match* could cause memory leaks when C-g is used in
307    Emacs; also, malloc is slower and causes storage fragmentation.  On
308    the other hand, malloc is more portable, and easier to debug.
309
310    Because we sometimes use alloca, some routines have to be macros,
311    not functions -- `alloca'-allocated space disappears at the end of the
312    function it is called in.  */
313
314 # ifdef REGEX_MALLOC
315
316 #  define REGEX_ALLOCATE malloc
317 #  define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
318 #  define REGEX_FREE free
319
320 # else /* not REGEX_MALLOC  */
321
322 /* Emacs already defines alloca, sometimes.  */
323 #  ifndef alloca
324
325 /* Make alloca work the best possible way.  */
326 #   ifdef __GNUC__
327 #    define alloca __builtin_alloca
328 #   else /* not __GNUC__ */
329 #    if HAVE_ALLOCA_H
330 #     include <alloca.h>
331 #    endif /* HAVE_ALLOCA_H */
332 #   endif /* not __GNUC__ */
333
334 #  endif /* not alloca */
335
336 #  define REGEX_ALLOCATE alloca
337
338 /* Assumes a `char *destination' variable.  */
339 #  define REGEX_REALLOCATE(source, osize, nsize)                        \
340   (destination = (char *) alloca (nsize),                               \
341    memcpy (destination, source, osize))
342
343 /* No need to do anything to free, after alloca.  */
344 #  define REGEX_FREE(arg) ((void)0) /* Do nothing!  But inhibit gcc warning.  */
345
346 # endif /* not REGEX_MALLOC */
347
348 /* Define how to allocate the failure stack.  */
349
350 # if defined REL_ALLOC && defined REGEX_MALLOC
351
352 #  define REGEX_ALLOCATE_STACK(size)                            \
353   r_alloc (&failure_stack_ptr, (size))
354 #  define REGEX_REALLOCATE_STACK(source, osize, nsize)          \
355   r_re_alloc (&failure_stack_ptr, (nsize))
356 #  define REGEX_FREE_STACK(ptr)                                 \
357   r_alloc_free (&failure_stack_ptr)
358
359 # else /* not using relocating allocator */
360
361 #  ifdef REGEX_MALLOC
362
363 #   define REGEX_ALLOCATE_STACK malloc
364 #   define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
365 #   define REGEX_FREE_STACK free
366
367 #  else /* not REGEX_MALLOC */
368
369 #   define REGEX_ALLOCATE_STACK alloca
370
371 #   define REGEX_REALLOCATE_STACK(source, osize, nsize)                 \
372    REGEX_REALLOCATE (source, osize, nsize)
373 /* No need to explicitly free anything.  */
374 #   define REGEX_FREE_STACK(arg)
375
376 #  endif /* not REGEX_MALLOC */
377 # endif /* not using relocating allocator */
378
379
380 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
381    `string1' or just past its end.  This works if PTR is NULL, which is
382    a good thing.  */
383 # define FIRST_STRING_P(ptr)                                    \
384   (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
385
386 /* (Re)Allocate N items of type T using malloc, or fail.  */
387 # define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
388 # define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
389 # define RETALLOC_IF(addr, n, t) \
390   if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
391 # define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
392
393 # define BYTEWIDTH 8 /* In bits.  */
394
395 # define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
396
397 # undef MAX
398 # undef MIN
399 # define MAX(a, b) ((a) > (b) ? (a) : (b))
400 # define MIN(a, b) ((a) < (b) ? (a) : (b))
401
402 typedef char boolean;
403 # define false 0
404 # define true 1
405
406 static reg_errcode_t byte_regex_compile (const char *pattern, size_t size,
407                                          reg_syntax_t syntax,
408                                          struct re_pattern_buffer *bufp);
409
410 static int byte_re_match_2_internal (struct re_pattern_buffer *bufp,
411                                      const char *string1, int size1,
412                                      const char *string2, int size2,
413                                      int pos,
414                                      struct re_registers *regs,
415                                      int stop);
416 static int byte_re_search_2 (struct re_pattern_buffer *bufp,
417                              const char *string1, int size1,
418                              const char *string2, int size2,
419                              int startpos, int range,
420                              struct re_registers *regs, int stop);
421 static int byte_re_compile_fastmap (struct re_pattern_buffer *bufp);
422
423 #ifdef MBS_SUPPORT
424 static reg_errcode_t wcs_regex_compile (const char *pattern, size_t size,
425                                         reg_syntax_t syntax,
426                                         struct re_pattern_buffer *bufp);
427
428
429 static int wcs_re_match_2_internal (struct re_pattern_buffer *bufp,
430                                     const char *cstring1, int csize1,
431                                     const char *cstring2, int csize2,
432                                     int pos,
433                                     struct re_registers *regs,
434                                     int stop,
435                                     wchar_t *string1, int size1,
436                                     wchar_t *string2, int size2,
437                                     int *mbs_offset1, int *mbs_offset2);
438 static int wcs_re_search_2 (struct re_pattern_buffer *bufp,
439                             const char *string1, int size1,
440                             const char *string2, int size2,
441                             int startpos, int range,
442                             struct re_registers *regs, int stop);
443 static int wcs_re_compile_fastmap (struct re_pattern_buffer *bufp);
444 #endif
445 \f
446 /* These are the command codes that appear in compiled regular
447    expressions.  Some opcodes are followed by argument bytes.  A
448    command code can specify any interpretation whatsoever for its
449    arguments.  Zero bytes may appear in the compiled regular expression.  */
450
451 typedef enum
452 {
453   no_op = 0,
454
455   /* Succeed right away--no more backtracking.  */
456   succeed,
457
458         /* Followed by one byte giving n, then by n literal bytes.  */
459   exactn,
460
461 # ifdef MBS_SUPPORT
462         /* Same as exactn, but contains binary data.  */
463   exactn_bin,
464 # endif
465
466         /* Matches any (more or less) character.  */
467   anychar,
468
469         /* Matches any one char belonging to specified set.  First
470            following byte is number of bitmap bytes.  Then come bytes
471            for a bitmap saying which chars are in.  Bits in each byte
472            are ordered low-bit-first.  A character is in the set if its
473            bit is 1.  A character too large to have a bit in the map is
474            automatically not in the set.  */
475         /* ifdef MBS_SUPPORT, following element is length of character
476            classes, length of collating symbols, length of equivalence
477            classes, length of character ranges, and length of characters.
478            Next, character class element, collating symbols elements,
479            equivalence class elements, range elements, and character
480            elements follow.
481            See regex_compile function.  */
482   charset,
483
484         /* Same parameters as charset, but match any character that is
485            not one of those specified.  */
486   charset_not,
487
488         /* Start remembering the text that is matched, for storing in a
489            register.  Followed by one byte with the register number, in
490            the range 0 to one less than the pattern buffer's re_nsub
491            field.  Then followed by one byte with the number of groups
492            inner to this one.  (This last has to be part of the
493            start_memory only because we need it in the on_failure_jump
494            of re_match_2.)  */
495   start_memory,
496
497         /* Stop remembering the text that is matched and store it in a
498            memory register.  Followed by one byte with the register
499            number, in the range 0 to one less than `re_nsub' in the
500            pattern buffer, and one byte with the number of inner groups,
501            just like `start_memory'.  (We need the number of inner
502            groups here because we don't have any easy way of finding the
503            corresponding start_memory when we're at a stop_memory.)  */
504   stop_memory,
505
506         /* Match a duplicate of something remembered. Followed by one
507            byte containing the register number.  */
508   duplicate,
509
510         /* Fail unless at beginning of line.  */
511   begline,
512
513         /* Fail unless at end of line.  */
514   endline,
515
516         /* Succeeds if at beginning of buffer (if emacs) or at beginning
517            of string to be matched (if not).  */
518   begbuf,
519
520         /* Analogously, for end of buffer/string.  */
521   endbuf,
522
523         /* Followed by two byte relative address to which to jump.  */
524   jump,
525
526         /* Same as jump, but marks the end of an alternative.  */
527   jump_past_alt,
528
529         /* Followed by two-byte relative address of place to resume at
530            in case of failure.  */
531         /* ifdef MBS_SUPPORT, the size of address is 1.  */
532   on_failure_jump,
533
534         /* Like on_failure_jump, but pushes a placeholder instead of the
535            current string position when executed.  */
536   on_failure_keep_string_jump,
537
538         /* Throw away latest failure point and then jump to following
539            two-byte relative address.  */
540         /* ifdef MBS_SUPPORT, the size of address is 1.  */
541   pop_failure_jump,
542
543         /* Change to pop_failure_jump if know won't have to backtrack to
544            match; otherwise change to jump.  This is used to jump
545            back to the beginning of a repeat.  If what follows this jump
546            clearly won't match what the repeat does, such that we can be
547            sure that there is no use backtracking out of repetitions
548            already matched, then we change it to a pop_failure_jump.
549            Followed by two-byte address.  */
550         /* ifdef MBS_SUPPORT, the size of address is 1.  */
551   maybe_pop_jump,
552
553         /* Jump to following two-byte address, and push a dummy failure
554            point. This failure point will be thrown away if an attempt
555            is made to use it for a failure.  A `+' construct makes this
556            before the first repeat.  Also used as an intermediary kind
557            of jump when compiling an alternative.  */
558         /* ifdef MBS_SUPPORT, the size of address is 1.  */
559   dummy_failure_jump,
560
561         /* Push a dummy failure point and continue.  Used at the end of
562            alternatives.  */
563   push_dummy_failure,
564
565         /* Followed by two-byte relative address and two-byte number n.
566            After matching N times, jump to the address upon failure.  */
567         /* ifdef MBS_SUPPORT, the size of address is 1.  */
568   succeed_n,
569
570         /* Followed by two-byte relative address, and two-byte number n.
571            Jump to the address N times, then fail.  */
572         /* ifdef MBS_SUPPORT, the size of address is 1.  */
573   jump_n,
574
575         /* Set the following two-byte relative address to the
576            subsequent two-byte number.  The address *includes* the two
577            bytes of number.  */
578         /* ifdef MBS_SUPPORT, the size of address is 1.  */
579   set_number_at,
580
581   wordchar,     /* Matches any word-constituent character.  */
582   notwordchar,  /* Matches any char that is not a word-constituent.  */
583
584   wordbeg,      /* Succeeds if at word beginning.  */
585   wordend,      /* Succeeds if at word end.  */
586
587   wordbound,    /* Succeeds if at a word boundary.  */
588   notwordbound  /* Succeeds if not at a word boundary.  */
589
590 # ifdef emacs
591   ,before_dot,  /* Succeeds if before point.  */
592   at_dot,       /* Succeeds if at point.  */
593   after_dot,    /* Succeeds if after point.  */
594
595         /* Matches any character whose syntax is specified.  Followed by
596            a byte which contains a syntax code, e.g., Sword.  */
597   syntaxspec,
598
599         /* Matches any character whose syntax is not that specified.  */
600   notsyntaxspec
601 # endif /* emacs */
602 } re_opcode_t;
603 #endif /* not INSIDE_RECURSION */
604 \f
605
606 #ifdef BYTE
607 # define CHAR_T char
608 # define UCHAR_T unsigned char
609 # define COMPILED_BUFFER_VAR bufp->buffer
610 # define OFFSET_ADDRESS_SIZE 2
611 # define PREFIX(name) byte_##name
612 # define ARG_PREFIX(name) name
613 # define PUT_CHAR(c) putchar (c)
614 #else
615 # ifdef WCHAR
616 #  define CHAR_T wchar_t
617 #  define UCHAR_T wchar_t
618 #  define COMPILED_BUFFER_VAR wc_buffer
619 #  define OFFSET_ADDRESS_SIZE 1 /* the size which STORE_NUMBER macro use */
620 #  define CHAR_CLASS_SIZE ((__alignof__(wctype_t)+sizeof(wctype_t))/sizeof(CHAR_T)+1)
621 #  define PREFIX(name) wcs_##name
622 #  define ARG_PREFIX(name) c##name
623 /* Should we use wide stream??  */
624 #  define PUT_CHAR(c) printf ("%C", c);
625 #  define TRUE 1
626 #  define FALSE 0
627 # else
628 #  ifdef MBS_SUPPORT
629 #   define WCHAR
630 #   define INSIDE_RECURSION
631 #   include "regex.c"
632 #   undef INSIDE_RECURSION
633 #  endif
634 #  define BYTE
635 #  define INSIDE_RECURSION
636 #  include "regex.c"
637 #  undef INSIDE_RECURSION
638 # endif
639 #endif
640
641 #ifdef INSIDE_RECURSION
642 /* Common operations on the compiled pattern.  */
643
644 /* Store NUMBER in two contiguous bytes starting at DESTINATION.  */
645 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element.  */
646
647 # ifdef WCHAR
648 #  define STORE_NUMBER(destination, number)                             \
649   do {                                                                  \
650     *(destination) = (UCHAR_T)(number);                         \
651   } while (0)
652 # else /* BYTE */
653 #  define STORE_NUMBER(destination, number)                             \
654   do {                                                                  \
655     (destination)[0] = (number) & 0377;                                 \
656     (destination)[1] = (number) >> 8;                                   \
657   } while (0)
658 # endif /* WCHAR */
659
660 /* Same as STORE_NUMBER, except increment DESTINATION to
661    the byte after where the number is stored.  Therefore, DESTINATION
662    must be an lvalue.  */
663 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element.  */
664
665 # define STORE_NUMBER_AND_INCR(destination, number)                     \
666   do {                                                                  \
667     STORE_NUMBER (destination, number);                                 \
668     (destination) += OFFSET_ADDRESS_SIZE;                               \
669   } while (0)
670
671 /* Put into DESTINATION a number stored in two contiguous bytes starting
672    at SOURCE.  */
673 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element.  */
674
675 # ifdef WCHAR
676 #  define EXTRACT_NUMBER(destination, source)                           \
677   do {                                                                  \
678     (destination) = *(source);                                          \
679   } while (0)
680 # else /* BYTE */
681 #  define EXTRACT_NUMBER(destination, source)                           \
682   do {                                                                  \
683     (destination) = *(source) & 0377;                                   \
684     (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8;           \
685   } while (0)
686 # endif
687
688 # ifdef DEBUG
689 static void PREFIX(extract_number) (int *dest, UCHAR_T *source);
690 static void
691 PREFIX(extract_number) (int *dest, UCHAR_T *source)
692 {
693 #  ifdef WCHAR
694   *dest = *source;
695 #  else /* BYTE */
696   int temp = SIGN_EXTEND_CHAR (*(source + 1));
697   *dest = *source & 0377;
698   *dest += temp << 8;
699 #  endif
700 }
701
702 #  ifndef EXTRACT_MACROS /* To debug the macros.  */
703 #   undef EXTRACT_NUMBER
704 #   define EXTRACT_NUMBER(dest, src) PREFIX(extract_number) (&dest, src)
705 #  endif /* not EXTRACT_MACROS */
706
707 # endif /* DEBUG */
708
709 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
710    SOURCE must be an lvalue.  */
711
712 # define EXTRACT_NUMBER_AND_INCR(destination, source)                   \
713   do {                                                                  \
714     EXTRACT_NUMBER (destination, source);                               \
715     (source) += OFFSET_ADDRESS_SIZE;                                    \
716   } while (0)
717
718 # ifdef DEBUG
719 static void PREFIX(extract_number_and_incr) (int *destination,
720                                              UCHAR_T **source);
721 static void
722 PREFIX(extract_number_and_incr) (int *destination, UCHAR_T **source)
723 {
724   PREFIX(extract_number) (destination, *source);
725   *source += OFFSET_ADDRESS_SIZE;
726 }
727
728 #  ifndef EXTRACT_MACROS
729 #   undef EXTRACT_NUMBER_AND_INCR
730 #   define EXTRACT_NUMBER_AND_INCR(dest, src) \
731   PREFIX(extract_number_and_incr) (&dest, &src)
732 #  endif /* not EXTRACT_MACROS */
733
734 # endif /* DEBUG */
735
736 \f
737
738 /* If DEBUG is defined, Regex prints many voluminous messages about what
739    it is doing (if the variable `debug' is nonzero).  If linked with the
740    main program in `iregex.c', you can enter patterns and strings
741    interactively.  And if linked with the main program in `main.c' and
742    the other test files, you can run the already-written tests.  */
743
744 # ifdef DEBUG
745
746 #  ifndef DEFINED_ONCE
747
748 /* We use standard I/O for debugging.  */
749 #   include <stdio.h>
750
751 /* It is useful to test things that ``must'' be true when debugging.  */
752 #   include <assert.h>
753
754 static int debug;
755
756 #   define DEBUG_STATEMENT(e) e
757 #   define DEBUG_PRINT1(x) if (debug) printf (x)
758 #   define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
759 #   define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
760 #   define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
761 #  endif /* not DEFINED_ONCE */
762
763 #  define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)                         \
764   if (debug) PREFIX(print_partial_compiled_pattern) (s, e)
765 #  define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)                \
766   if (debug) PREFIX(print_double_string) (w, s1, sz1, s2, sz2)
767
768
769 /* Print the fastmap in human-readable form.  */
770
771 #  ifndef DEFINED_ONCE
772 void
773 print_fastmap (char *fastmap)
774 {
775   unsigned was_a_range = 0;
776   unsigned i = 0;
777
778   while (i < (1 << BYTEWIDTH))
779     {
780       if (fastmap[i++])
781         {
782           was_a_range = 0;
783           putchar (i - 1);
784           while (i < (1 << BYTEWIDTH)  &&  fastmap[i])
785             {
786               was_a_range = 1;
787               i++;
788             }
789           if (was_a_range)
790             {
791               printf ("-");
792               putchar (i - 1);
793             }
794         }
795     }
796   putchar ('\n');
797 }
798 #  endif /* not DEFINED_ONCE */
799
800
801 /* Print a compiled pattern string in human-readable form, starting at
802    the START pointer into it and ending just before the pointer END.  */
803
804 void
805 PREFIX(print_partial_compiled_pattern) (UCHAR_T *start, UCHAR_T *end)
806 {
807   int mcnt, mcnt2;
808   UCHAR_T *p1;
809   UCHAR_T *p = start;
810   UCHAR_T *pend = end;
811
812   if (start == NULL)
813     {
814       printf ("(null)\n");
815       return;
816     }
817
818   /* Loop over pattern commands.  */
819   while (p < pend)
820     {
821 #  ifdef _LIBC
822       printf ("%td:\t", p - start);
823 #  else
824       printf ("%ld:\t", (long int) (p - start));
825 #  endif
826
827       switch ((re_opcode_t) *p++)
828         {
829         case no_op:
830           printf ("/no_op");
831           break;
832
833         case exactn:
834           mcnt = *p++;
835           printf ("/exactn/%d", mcnt);
836           do
837             {
838               putchar ('/');
839               PUT_CHAR (*p++);
840             }
841           while (--mcnt);
842           break;
843
844 #  ifdef MBS_SUPPORT
845         case exactn_bin:
846           mcnt = *p++;
847           printf ("/exactn_bin/%d", mcnt);
848           do
849             {
850               printf("/%lx", (long int) *p++);
851             }
852           while (--mcnt);
853           break;
854 #  endif /* MBS_SUPPORT */
855
856         case start_memory:
857           mcnt = *p++;
858           printf ("/start_memory/%d/%ld", mcnt, (long int) *p++);
859           break;
860
861         case stop_memory:
862           mcnt = *p++;
863           printf ("/stop_memory/%d/%ld", mcnt, (long int) *p++);
864           break;
865
866         case duplicate:
867           printf ("/duplicate/%ld", (long int) *p++);
868           break;
869
870         case anychar:
871           printf ("/anychar");
872           break;
873
874         case charset:
875         case charset_not:
876           {
877 #  ifdef WCHAR
878             int i, length;
879             wchar_t *workp = p;
880             printf ("/charset [%s",
881                     (re_opcode_t) *(workp - 1) == charset_not ? "^" : "");
882             p += 5;
883             length = *workp++; /* the length of char_classes */
884             for (i=0 ; i<length ; i++)
885               printf("[:%lx:]", (long int) *p++);
886             length = *workp++; /* the length of collating_symbol */
887             for (i=0 ; i<length ;)
888               {
889                 printf("[.");
890                 while(*p != 0)
891                   PUT_CHAR((i++,*p++));
892                 i++,p++;
893                 printf(".]");
894               }
895             length = *workp++; /* the length of equivalence_class */
896             for (i=0 ; i<length ;)
897               {
898                 printf("[=");
899                 while(*p != 0)
900                   PUT_CHAR((i++,*p++));
901                 i++,p++;
902                 printf("=]");
903               }
904             length = *workp++; /* the length of char_range */
905             for (i=0 ; i<length ; i++)
906               {
907                 wchar_t range_start = *p++;
908                 wchar_t range_end = *p++;
909                 printf("%C-%C", range_start, range_end);
910               }
911             length = *workp++; /* the length of char */
912             for (i=0 ; i<length ; i++)
913               printf("%C", *p++);
914             putchar (']');
915 #  else
916             register int c, last = -100;
917             register int in_range = 0;
918
919             printf ("/charset [%s",
920                     (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
921
922             assert (p + *p < pend);
923
924             for (c = 0; c < 256; c++)
925               if (c / 8 < *p
926                   && (p[1 + (c/8)] & (1 << (c % 8))))
927                 {
928                   /* Are we starting a range?  */
929                   if (last + 1 == c && ! in_range)
930                     {
931                       putchar ('-');
932                       in_range = 1;
933                     }
934                   /* Have we broken a range?  */
935                   else if (last + 1 != c && in_range)
936               {
937                       putchar (last);
938                       in_range = 0;
939                     }
940
941                   if (! in_range)
942                     putchar (c);
943
944                   last = c;
945               }
946
947             if (in_range)
948               putchar (last);
949
950             putchar (']');
951
952             p += 1 + *p;
953 #  endif /* WCHAR */
954           }
955           break;
956
957         case begline:
958           printf ("/begline");
959           break;
960
961         case endline:
962           printf ("/endline");
963           break;
964
965         case on_failure_jump:
966           PREFIX(extract_number_and_incr) (&mcnt, &p);
967 #  ifdef _LIBC
968           printf ("/on_failure_jump to %td", p + mcnt - start);
969 #  else
970           printf ("/on_failure_jump to %ld", (long int) (p + mcnt - start));
971 #  endif
972           break;
973
974         case on_failure_keep_string_jump:
975           PREFIX(extract_number_and_incr) (&mcnt, &p);
976 #  ifdef _LIBC
977           printf ("/on_failure_keep_string_jump to %td", p + mcnt - start);
978 #  else
979           printf ("/on_failure_keep_string_jump to %ld",
980                   (long int) (p + mcnt - start));
981 #  endif
982           break;
983
984         case dummy_failure_jump:
985           PREFIX(extract_number_and_incr) (&mcnt, &p);
986 #  ifdef _LIBC
987           printf ("/dummy_failure_jump to %td", p + mcnt - start);
988 #  else
989           printf ("/dummy_failure_jump to %ld", (long int) (p + mcnt - start));
990 #  endif
991           break;
992
993         case push_dummy_failure:
994           printf ("/push_dummy_failure");
995           break;
996
997         case maybe_pop_jump:
998           PREFIX(extract_number_and_incr) (&mcnt, &p);
999 #  ifdef _LIBC
1000           printf ("/maybe_pop_jump to %td", p + mcnt - start);
1001 #  else
1002           printf ("/maybe_pop_jump to %ld", (long int) (p + mcnt - start));
1003 #  endif
1004           break;
1005
1006         case pop_failure_jump:
1007           PREFIX(extract_number_and_incr) (&mcnt, &p);
1008 #  ifdef _LIBC
1009           printf ("/pop_failure_jump to %td", p + mcnt - start);
1010 #  else
1011           printf ("/pop_failure_jump to %ld", (long int) (p + mcnt - start));
1012 #  endif
1013           break;
1014
1015         case jump_past_alt:
1016           PREFIX(extract_number_and_incr) (&mcnt, &p);
1017 #  ifdef _LIBC
1018           printf ("/jump_past_alt to %td", p + mcnt - start);
1019 #  else
1020           printf ("/jump_past_alt to %ld", (long int) (p + mcnt - start));
1021 #  endif
1022           break;
1023
1024         case jump:
1025           PREFIX(extract_number_and_incr) (&mcnt, &p);
1026 #  ifdef _LIBC
1027           printf ("/jump to %td", p + mcnt - start);
1028 #  else
1029           printf ("/jump to %ld", (long int) (p + mcnt - start));
1030 #  endif
1031           break;
1032
1033         case succeed_n:
1034           PREFIX(extract_number_and_incr) (&mcnt, &p);
1035           p1 = p + mcnt;
1036           PREFIX(extract_number_and_incr) (&mcnt2, &p);
1037 #  ifdef _LIBC
1038           printf ("/succeed_n to %td, %d times", p1 - start, mcnt2);
1039 #  else
1040           printf ("/succeed_n to %ld, %d times",
1041                   (long int) (p1 - start), mcnt2);
1042 #  endif
1043           break;
1044
1045         case jump_n:
1046           PREFIX(extract_number_and_incr) (&mcnt, &p);
1047           p1 = p + mcnt;
1048           PREFIX(extract_number_and_incr) (&mcnt2, &p);
1049           printf ("/jump_n to %d, %d times", p1 - start, mcnt2);
1050           break;
1051
1052         case set_number_at:
1053           PREFIX(extract_number_and_incr) (&mcnt, &p);
1054           p1 = p + mcnt;
1055           PREFIX(extract_number_and_incr) (&mcnt2, &p);
1056 #  ifdef _LIBC
1057           printf ("/set_number_at location %td to %d", p1 - start, mcnt2);
1058 #  else
1059           printf ("/set_number_at location %ld to %d",
1060                   (long int) (p1 - start), mcnt2);
1061 #  endif
1062           break;
1063
1064         case wordbound:
1065           printf ("/wordbound");
1066           break;
1067
1068         case notwordbound:
1069           printf ("/notwordbound");
1070           break;
1071
1072         case wordbeg:
1073           printf ("/wordbeg");
1074           break;
1075
1076         case wordend:
1077           printf ("/wordend");
1078           break;
1079
1080 #  ifdef emacs
1081         case before_dot:
1082           printf ("/before_dot");
1083           break;
1084
1085         case at_dot:
1086           printf ("/at_dot");
1087           break;
1088
1089         case after_dot:
1090           printf ("/after_dot");
1091           break;
1092
1093         case syntaxspec:
1094           printf ("/syntaxspec");
1095           mcnt = *p++;
1096           printf ("/%d", mcnt);
1097           break;
1098
1099         case notsyntaxspec:
1100           printf ("/notsyntaxspec");
1101           mcnt = *p++;
1102           printf ("/%d", mcnt);
1103           break;
1104 #  endif /* emacs */
1105
1106         case wordchar:
1107           printf ("/wordchar");
1108           break;
1109
1110         case notwordchar:
1111           printf ("/notwordchar");
1112           break;
1113
1114         case begbuf:
1115           printf ("/begbuf");
1116           break;
1117
1118         case endbuf:
1119           printf ("/endbuf");
1120           break;
1121
1122         default:
1123           printf ("?%ld", (long int) *(p-1));
1124         }
1125
1126       putchar ('\n');
1127     }
1128
1129 #  ifdef _LIBC
1130   printf ("%td:\tend of pattern.\n", p - start);
1131 #  else
1132   printf ("%ld:\tend of pattern.\n", (long int) (p - start));
1133 #  endif
1134 }
1135
1136
1137 void
1138 PREFIX(print_compiled_pattern) (struct re_pattern_buffer *bufp)
1139 {
1140   UCHAR_T *buffer = (UCHAR_T*) bufp->buffer;
1141
1142   PREFIX(print_partial_compiled_pattern) (buffer, buffer
1143                                   + bufp->used / sizeof(UCHAR_T));
1144   printf ("%ld bytes used/%ld bytes allocated.\n",
1145           bufp->used, bufp->allocated);
1146
1147   if (bufp->fastmap_accurate && bufp->fastmap)
1148     {
1149       printf ("fastmap: ");
1150       print_fastmap (bufp->fastmap);
1151     }
1152
1153 #  ifdef _LIBC
1154   printf ("re_nsub: %Zd\t", bufp->re_nsub);
1155 #  else
1156   printf ("re_nsub: %ld\t", (long int) bufp->re_nsub);
1157 #  endif
1158   printf ("regs_alloc: %d\t", bufp->regs_allocated);
1159   printf ("can_be_null: %d\t", bufp->can_be_null);
1160   printf ("newline_anchor: %d\n", bufp->newline_anchor);
1161   printf ("no_sub: %d\t", bufp->no_sub);
1162   printf ("not_bol: %d\t", bufp->not_bol);
1163   printf ("not_eol: %d\t", bufp->not_eol);
1164   printf ("syntax: %lx\n", bufp->syntax);
1165   /* Perhaps we should print the translate table?  */
1166 }
1167
1168
1169 void
1170 PREFIX(print_double_string) (const CHAR_T *where, const CHAR_T *string1,
1171                              int size1, const CHAR_T *string2, int size2)
1172 {
1173   int this_char;
1174
1175   if (where == NULL)
1176     printf ("(null)");
1177   else
1178     {
1179       int cnt;
1180
1181       if (FIRST_STRING_P (where))
1182         {
1183           for (this_char = where - string1; this_char < size1; this_char++)
1184             PUT_CHAR (string1[this_char]);
1185
1186           where = string2;
1187         }
1188
1189       cnt = 0;
1190       for (this_char = where - string2; this_char < size2; this_char++)
1191         {
1192           PUT_CHAR (string2[this_char]);
1193           if (++cnt > 100)
1194             {
1195               fputs ("...", stdout);
1196               break;
1197             }
1198         }
1199     }
1200 }
1201
1202 #  ifndef DEFINED_ONCE
1203 void
1204 printchar (int c)
1205 {
1206   putc (c, stderr);
1207 }
1208 #  endif
1209
1210 # else /* not DEBUG */
1211
1212 #  ifndef DEFINED_ONCE
1213 #   undef assert
1214 #   define assert(e)
1215
1216 #   define DEBUG_STATEMENT(e)
1217 #   define DEBUG_PRINT1(x)
1218 #   define DEBUG_PRINT2(x1, x2)
1219 #   define DEBUG_PRINT3(x1, x2, x3)
1220 #   define DEBUG_PRINT4(x1, x2, x3, x4)
1221 #  endif /* not DEFINED_ONCE */
1222 #  define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1223 #  define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1224
1225 # endif /* not DEBUG */
1226
1227 \f
1228
1229 # ifdef WCHAR
1230 /* This  convert a multibyte string to a wide character string.
1231    And write their correspondances to offset_buffer(see below)
1232    and write whether each wchar_t is binary data to is_binary.
1233    This assume invalid multibyte sequences as binary data.
1234    We assume offset_buffer and is_binary is already allocated
1235    enough space.  */
1236
1237 static size_t convert_mbs_to_wcs (CHAR_T *dest, const unsigned char* src,
1238                                   size_t len, int *offset_buffer,
1239                                   char *is_binary);
1240 static size_t
1241 convert_mbs_to_wcs (CHAR_T *dest, const unsigned char*src, size_t len,
1242                     int *offset_buffer, char *is_binary)
1243      /* It hold correspondances between src(char string) and
1244         dest(wchar_t string) for optimization.
1245         e.g. src  = "xxxyzz"
1246              dest = {'X', 'Y', 'Z'}
1247               (each "xxx", "y" and "zz" represent one multibyte character
1248                corresponding to 'X', 'Y' and 'Z'.)
1249           offset_buffer = {0, 0+3("xxx"), 0+3+1("y"), 0+3+1+2("zz")}
1250                         = {0, 3, 4, 6}
1251      */
1252 {
1253   wchar_t *pdest = dest;
1254   const unsigned char *psrc = src;
1255   size_t wc_count = 0;
1256
1257   mbstate_t mbs;
1258   int i, consumed;
1259   size_t mb_remain = len;
1260   size_t mb_count = 0;
1261
1262   /* Initialize the conversion state.  */
1263   memset (&mbs, 0, sizeof (mbstate_t));
1264
1265   offset_buffer[0] = 0;
1266   for( ; mb_remain > 0 ; ++wc_count, ++pdest, mb_remain -= consumed,
1267          psrc += consumed)
1268     {
1269 #ifdef _LIBC
1270       consumed = __mbrtowc (pdest, psrc, mb_remain, &mbs);
1271 #else
1272       consumed = mbrtowc (pdest, psrc, mb_remain, &mbs);
1273 #endif
1274
1275       if (consumed <= 0)
1276         /* failed to convert. maybe src contains binary data.
1277            So we consume 1 byte manualy.  */
1278         {
1279           *pdest = *psrc;
1280           consumed = 1;
1281           is_binary[wc_count] = TRUE;
1282         }
1283       else
1284         is_binary[wc_count] = FALSE;
1285       /* In sjis encoding, we use yen sign as escape character in
1286          place of reverse solidus. So we convert 0x5c(yen sign in
1287          sjis) to not 0xa5(yen sign in UCS2) but 0x5c(reverse
1288          solidus in UCS2).  */
1289       if (consumed == 1 && (int) *psrc == 0x5c && (int) *pdest == 0xa5)
1290         *pdest = (wchar_t) *psrc;
1291
1292       offset_buffer[wc_count + 1] = mb_count += consumed;
1293     }
1294
1295   /* Fill remain of the buffer with sentinel.  */
1296   for (i = wc_count + 1 ; i <= len ; i++)
1297     offset_buffer[i] = mb_count + 1;
1298
1299   return wc_count;
1300 }
1301
1302 # endif /* WCHAR */
1303
1304 #else /* not INSIDE_RECURSION */
1305
1306 /* Set by `re_set_syntax' to the current regexp syntax to recognize.  Can
1307    also be assigned to arbitrarily: each pattern buffer stores its own
1308    syntax, so it can be changed between regex compilations.  */
1309 /* This has no initializer because initialized variables in Emacs
1310    become read-only after dumping.  */
1311 reg_syntax_t re_syntax_options;
1312
1313
1314 /* Specify the precise syntax of regexps for compilation.  This provides
1315    for compatibility for various utilities which historically have
1316    different, incompatible syntaxes.
1317
1318    The argument SYNTAX is a bit mask comprised of the various bits
1319    defined in regex.h.  We return the old syntax.  */
1320
1321 reg_syntax_t
1322 re_set_syntax (reg_syntax_t syntax)
1323 {
1324   reg_syntax_t ret = re_syntax_options;
1325
1326   re_syntax_options = syntax;
1327 # ifdef DEBUG
1328   if (syntax & RE_DEBUG)
1329     debug = 1;
1330   else if (debug) /* was on but now is not */
1331     debug = 0;
1332 # endif /* DEBUG */
1333   return ret;
1334 }
1335 # ifdef _LIBC
1336 weak_alias (__re_set_syntax, re_set_syntax)
1337 # endif
1338 \f
1339 /* This table gives an error message for each of the error codes listed
1340    in regex.h.  Obviously the order here has to be same as there.
1341    POSIX doesn't require that we do anything for REG_NOERROR,
1342    but why not be nice?  */
1343
1344 static const char *re_error_msgid[] =
1345   {
1346     gettext_noop ("Success"),   /* REG_NOERROR */
1347     gettext_noop ("No match"),  /* REG_NOMATCH */
1348     gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1349     gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1350     gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1351     gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1352     gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1353     gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1354     gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1355     gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1356     gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1357     gettext_noop ("Invalid range end"), /* REG_ERANGE */
1358     gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1359     gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1360     gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1361     gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1362     gettext_noop ("Unmatched ) or \\)") /* REG_ERPAREN */
1363   };
1364 \f
1365 #endif /* INSIDE_RECURSION */
1366
1367 #ifndef DEFINED_ONCE
1368 /* Avoiding alloca during matching, to placate r_alloc.  */
1369
1370 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1371    searching and matching functions should not call alloca.  On some
1372    systems, alloca is implemented in terms of malloc, and if we're
1373    using the relocating allocator routines, then malloc could cause a
1374    relocation, which might (if the strings being searched are in the
1375    ralloc heap) shift the data out from underneath the regexp
1376    routines.
1377
1378    Here's another reason to avoid allocation: Emacs
1379    processes input from X in a signal handler; processing X input may
1380    call malloc; if input arrives while a matching routine is calling
1381    malloc, then we're scrod.  But Emacs can't just block input while
1382    calling matching routines; then we don't notice interrupts when
1383    they come in.  So, Emacs blocks input around all regexp calls
1384    except the matching calls, which it leaves unprotected, in the
1385    faith that they will not malloc.  */
1386
1387 /* Normally, this is fine.  */
1388 # define MATCH_MAY_ALLOCATE
1389
1390 /* When using GNU C, we are not REALLY using the C alloca, no matter
1391    what config.h may say.  So don't take precautions for it.  */
1392 # ifdef __GNUC__
1393 #  undef C_ALLOCA
1394 # endif
1395
1396 /* The match routines may not allocate if (1) they would do it with malloc
1397    and (2) it's not safe for them to use malloc.
1398    Note that if REL_ALLOC is defined, matching would not use malloc for the
1399    failure stack, but we would still use it for the register vectors;
1400    so REL_ALLOC should not affect this.  */
1401 # if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1402 #  undef MATCH_MAY_ALLOCATE
1403 # endif
1404 #endif /* not DEFINED_ONCE */
1405 \f
1406 #ifdef INSIDE_RECURSION
1407 /* Failure stack declarations and macros; both re_compile_fastmap and
1408    re_match_2 use a failure stack.  These have to be macros because of
1409    REGEX_ALLOCATE_STACK.  */
1410
1411
1412 /* Number of failure points for which to initially allocate space
1413    when matching.  If this number is exceeded, we allocate more
1414    space, so it is not a hard limit.  */
1415 # ifndef INIT_FAILURE_ALLOC
1416 #  define INIT_FAILURE_ALLOC 5
1417 # endif
1418
1419 /* Roughly the maximum number of failure points on the stack.  Would be
1420    exactly that if always used MAX_FAILURE_ITEMS items each time we failed.
1421    This is a variable only so users of regex can assign to it; we never
1422    change it ourselves.  */
1423
1424 # ifdef INT_IS_16BIT
1425
1426 #  ifndef DEFINED_ONCE
1427 #   if defined MATCH_MAY_ALLOCATE
1428 /* 4400 was enough to cause a crash on Alpha OSF/1,
1429    whose default stack limit is 2mb.  */
1430 long int re_max_failures = 4000;
1431 #   else
1432 long int re_max_failures = 2000;
1433 #   endif
1434 #  endif
1435
1436 union PREFIX(fail_stack_elt)
1437 {
1438   UCHAR_T *pointer;
1439   long int integer;
1440 };
1441
1442 typedef union PREFIX(fail_stack_elt) PREFIX(fail_stack_elt_t);
1443
1444 typedef struct
1445 {
1446   PREFIX(fail_stack_elt_t) *stack;
1447   unsigned long int size;
1448   unsigned long int avail;              /* Offset of next open position.  */
1449 } PREFIX(fail_stack_type);
1450
1451 # else /* not INT_IS_16BIT */
1452
1453 #  ifndef DEFINED_ONCE
1454 #   if defined MATCH_MAY_ALLOCATE
1455 /* 4400 was enough to cause a crash on Alpha OSF/1,
1456    whose default stack limit is 2mb.  */
1457 int re_max_failures = 4000;
1458 #   else
1459 int re_max_failures = 2000;
1460 #   endif
1461 #  endif
1462
1463 union PREFIX(fail_stack_elt)
1464 {
1465   UCHAR_T *pointer;
1466   int integer;
1467 };
1468
1469 typedef union PREFIX(fail_stack_elt) PREFIX(fail_stack_elt_t);
1470
1471 typedef struct
1472 {
1473   PREFIX(fail_stack_elt_t) *stack;
1474   unsigned size;
1475   unsigned avail;                       /* Offset of next open position.  */
1476 } PREFIX(fail_stack_type);
1477
1478 # endif /* INT_IS_16BIT */
1479
1480 # ifndef DEFINED_ONCE
1481 #  define FAIL_STACK_EMPTY()     (fail_stack.avail == 0)
1482 #  define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1483 #  define FAIL_STACK_FULL()      (fail_stack.avail == fail_stack.size)
1484 # endif
1485
1486
1487 /* Define macros to initialize and free the failure stack.
1488    Do `return -2' if the alloc fails.  */
1489
1490 # ifdef MATCH_MAY_ALLOCATE
1491 #  define INIT_FAIL_STACK()                                             \
1492   do {                                                                  \
1493     fail_stack.stack = (PREFIX(fail_stack_elt_t) *)             \
1494       REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (PREFIX(fail_stack_elt_t))); \
1495                                                                         \
1496     if (fail_stack.stack == NULL)                               \
1497       return -2;                                                        \
1498                                                                         \
1499     fail_stack.size = INIT_FAILURE_ALLOC;                       \
1500     fail_stack.avail = 0;                                       \
1501   } while (0)
1502
1503 #  define RESET_FAIL_STACK()  REGEX_FREE_STACK (fail_stack.stack)
1504 # else
1505 #  define INIT_FAIL_STACK()                                             \
1506   do {                                                                  \
1507     fail_stack.avail = 0;                                       \
1508   } while (0)
1509
1510 #  define RESET_FAIL_STACK()
1511 # endif
1512
1513
1514 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
1515
1516    Return 1 if succeeds, and 0 if either ran out of memory
1517    allocating space for it or it was already too large.
1518
1519    REGEX_REALLOCATE_STACK requires `destination' be declared.   */
1520
1521 # define DOUBLE_FAIL_STACK(fail_stack)                                  \
1522   ((fail_stack).size > (unsigned) (re_max_failures * MAX_FAILURE_ITEMS) \
1523    ? 0                                                                  \
1524    : ((fail_stack).stack = (PREFIX(fail_stack_elt_t) *)                 \
1525         REGEX_REALLOCATE_STACK ((fail_stack).stack,                     \
1526           (fail_stack).size * sizeof (PREFIX(fail_stack_elt_t)),        \
1527           ((fail_stack).size << 1) * sizeof (PREFIX(fail_stack_elt_t))),\
1528                                                                         \
1529       (fail_stack).stack == NULL                                        \
1530       ? 0                                                               \
1531       : ((fail_stack).size <<= 1,                                       \
1532          1)))
1533
1534
1535 /* Push pointer POINTER on FAIL_STACK.
1536    Return 1 if was able to do so and 0 if ran out of memory allocating
1537    space to do so.  */
1538 # define PUSH_PATTERN_OP(POINTER, FAIL_STACK)                           \
1539   ((FAIL_STACK_FULL ()                                                  \
1540     && !DOUBLE_FAIL_STACK (FAIL_STACK))                                 \
1541    ? 0                                                                  \
1542    : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER,       \
1543       1))
1544
1545 /* Push a pointer value onto the failure stack.
1546    Assumes the variable `fail_stack'.  Probably should only
1547    be called from within `PUSH_FAILURE_POINT'.  */
1548 # define PUSH_FAILURE_POINTER(item)                                     \
1549   fail_stack.stack[fail_stack.avail++].pointer = (UCHAR_T *) (item)
1550
1551 /* This pushes an integer-valued item onto the failure stack.
1552    Assumes the variable `fail_stack'.  Probably should only
1553    be called from within `PUSH_FAILURE_POINT'.  */
1554 # define PUSH_FAILURE_INT(item)                                 \
1555   fail_stack.stack[fail_stack.avail++].integer = (item)
1556
1557 /* Push a fail_stack_elt_t value onto the failure stack.
1558    Assumes the variable `fail_stack'.  Probably should only
1559    be called from within `PUSH_FAILURE_POINT'.  */
1560 # define PUSH_FAILURE_ELT(item)                                 \
1561   fail_stack.stack[fail_stack.avail++] =  (item)
1562
1563 /* These three POP... operations complement the three PUSH... operations.
1564    All assume that `fail_stack' is nonempty.  */
1565 # define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1566 # define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1567 # define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1568
1569 /* Used to omit pushing failure point id's when we're not debugging.  */
1570 # ifdef DEBUG
1571 #  define DEBUG_PUSH PUSH_FAILURE_INT
1572 #  define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1573 # else
1574 #  define DEBUG_PUSH(item)
1575 #  define DEBUG_POP(item_addr)
1576 # endif
1577
1578
1579 /* Push the information about the state we will need
1580    if we ever fail back to it.
1581
1582    Requires variables fail_stack, regstart, regend, reg_info, and
1583    num_regs_pushed be declared.  DOUBLE_FAIL_STACK requires `destination'
1584    be declared.
1585
1586    Does `return FAILURE_CODE' if runs out of memory.  */
1587
1588 # define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code)  \
1589   do {                                                                  \
1590     char *destination;                                                  \
1591     /* Must be int, so when we don't save any registers, the arithmetic \
1592        of 0 + -1 isn't done as unsigned.  */                            \
1593     /* Can't be int, since there is not a shred of a guarantee that int \
1594        is wide enough to hold a value of something to which pointer can \
1595        be assigned */                                                   \
1596     active_reg_t this_reg;                                              \
1597                                                                         \
1598     DEBUG_STATEMENT (failure_id++);                                     \
1599     DEBUG_STATEMENT (nfailure_points_pushed++);                         \
1600     DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id);           \
1601     DEBUG_PRINT2 ("  Before push, next avail: %d\n", (fail_stack).avail);\
1602     DEBUG_PRINT2 ("                     size: %d\n", (fail_stack).size);\
1603                                                                         \
1604     DEBUG_PRINT2 ("  slots needed: %ld\n", NUM_FAILURE_ITEMS);          \
1605     DEBUG_PRINT2 ("     available: %d\n", REMAINING_AVAIL_SLOTS);       \
1606                                                                         \
1607     /* Ensure we have enough space allocated for what we will push.  */ \
1608     while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS)                   \
1609       {                                                                 \
1610         if (!DOUBLE_FAIL_STACK (fail_stack))                            \
1611           return failure_code;                                          \
1612                                                                         \
1613         DEBUG_PRINT2 ("\n  Doubled stack; size now: %d\n",              \
1614                        (fail_stack).size);                              \
1615         DEBUG_PRINT2 ("  slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1616       }                                                                 \
1617                                                                         \
1618     /* Push the info, starting with the registers.  */                  \
1619     DEBUG_PRINT1 ("\n");                                                \
1620                                                                         \
1621     if (1)                                                              \
1622       for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1623            this_reg++)                                                  \
1624         {                                                               \
1625           DEBUG_PRINT2 ("  Pushing reg: %lu\n", this_reg);              \
1626           DEBUG_STATEMENT (num_regs_pushed++);                          \
1627                                                                         \
1628           DEBUG_PRINT2 ("    start: %p\n", regstart[this_reg]);         \
1629           PUSH_FAILURE_POINTER (regstart[this_reg]);                    \
1630                                                                         \
1631           DEBUG_PRINT2 ("    end: %p\n", regend[this_reg]);             \
1632           PUSH_FAILURE_POINTER (regend[this_reg]);                      \
1633                                                                         \
1634           DEBUG_PRINT2 ("    info: %p\n      ",                         \
1635                         reg_info[this_reg].word.pointer);               \
1636           DEBUG_PRINT2 (" match_null=%d",                               \
1637                         REG_MATCH_NULL_STRING_P (reg_info[this_reg]));  \
1638           DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg]));  \
1639           DEBUG_PRINT2 (" matched_something=%d",                        \
1640                         MATCHED_SOMETHING (reg_info[this_reg]));        \
1641           DEBUG_PRINT2 (" ever_matched=%d",                             \
1642                         EVER_MATCHED_SOMETHING (reg_info[this_reg]));   \
1643           DEBUG_PRINT1 ("\n");                                          \
1644           PUSH_FAILURE_ELT (reg_info[this_reg].word);                   \
1645         }                                                               \
1646                                                                         \
1647     DEBUG_PRINT2 ("  Pushing  low active reg: %ld\n", lowest_active_reg);\
1648     PUSH_FAILURE_INT (lowest_active_reg);                               \
1649                                                                         \
1650     DEBUG_PRINT2 ("  Pushing high active reg: %ld\n", highest_active_reg);\
1651     PUSH_FAILURE_INT (highest_active_reg);                              \
1652                                                                         \
1653     DEBUG_PRINT2 ("  Pushing pattern %p:\n", pattern_place);            \
1654     DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend);           \
1655     PUSH_FAILURE_POINTER (pattern_place);                               \
1656                                                                         \
1657     DEBUG_PRINT2 ("  Pushing string %p: `", string_place);              \
1658     DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2,   \
1659                                  size2);                                \
1660     DEBUG_PRINT1 ("'\n");                                               \
1661     PUSH_FAILURE_POINTER (string_place);                                \
1662                                                                         \
1663     DEBUG_PRINT2 ("  Pushing failure id: %u\n", failure_id);            \
1664     DEBUG_PUSH (failure_id);                                            \
1665   } while (0)
1666
1667 # ifndef DEFINED_ONCE
1668 /* This is the number of items that are pushed and popped on the stack
1669    for each register.  */
1670 #  define NUM_REG_ITEMS  3
1671
1672 /* Individual items aside from the registers.  */
1673 #  ifdef DEBUG
1674 #   define NUM_NONREG_ITEMS 5 /* Includes failure point id.  */
1675 #  else
1676 #   define NUM_NONREG_ITEMS 4
1677 #  endif
1678
1679 /* We push at most this many items on the stack.  */
1680 /* We used to use (num_regs - 1), which is the number of registers
1681    this regexp will save; but that was changed to 5
1682    to avoid stack overflow for a regexp with lots of parens.  */
1683 #  define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1684
1685 /* We actually push this many items.  */
1686 #  define NUM_FAILURE_ITEMS                             \
1687   (((0                                                  \
1688      ? 0 : highest_active_reg - lowest_active_reg + 1)  \
1689     * NUM_REG_ITEMS)                                    \
1690    + NUM_NONREG_ITEMS)
1691
1692 /* How many items can still be added to the stack without overflowing it.  */
1693 #  define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1694 # endif /* not DEFINED_ONCE */
1695
1696
1697 /* Pops what PUSH_FAIL_STACK pushes.
1698
1699    We restore into the parameters, all of which should be lvalues:
1700      STR -- the saved data position.
1701      PAT -- the saved pattern position.
1702      LOW_REG, HIGH_REG -- the highest and lowest active registers.
1703      REGSTART, REGEND -- arrays of string positions.
1704      REG_INFO -- array of information about each subexpression.
1705
1706    Also assumes the variables `fail_stack' and (if debugging), `bufp',
1707    `pend', `string1', `size1', `string2', and `size2'.  */
1708 # define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1709 {                                                                       \
1710   DEBUG_STATEMENT (unsigned failure_id;)                                \
1711   active_reg_t this_reg;                                                \
1712   const UCHAR_T *string_temp;                                           \
1713                                                                         \
1714   assert (!FAIL_STACK_EMPTY ());                                        \
1715                                                                         \
1716   /* Remove failure points and point to how many regs pushed.  */       \
1717   DEBUG_PRINT1 ("POP_FAILURE_POINT:\n");                                \
1718   DEBUG_PRINT2 ("  Before pop, next avail: %d\n", fail_stack.avail);    \
1719   DEBUG_PRINT2 ("                    size: %d\n", fail_stack.size);     \
1720                                                                         \
1721   assert (fail_stack.avail >= NUM_NONREG_ITEMS);                        \
1722                                                                         \
1723   DEBUG_POP (&failure_id);                                              \
1724   DEBUG_PRINT2 ("  Popping failure id: %u\n", failure_id);              \
1725                                                                         \
1726   /* If the saved string location is NULL, it came from an              \
1727      on_failure_keep_string_jump opcode, and we want to throw away the  \
1728      saved NULL, thus retaining our current position in the string.  */ \
1729   string_temp = POP_FAILURE_POINTER ();                                 \
1730   if (string_temp != NULL)                                              \
1731     str = (const CHAR_T *) string_temp;                                 \
1732                                                                         \
1733   DEBUG_PRINT2 ("  Popping string %p: `", str);                         \
1734   DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2);      \
1735   DEBUG_PRINT1 ("'\n");                                                 \
1736                                                                         \
1737   pat = (UCHAR_T *) POP_FAILURE_POINTER ();                             \
1738   DEBUG_PRINT2 ("  Popping pattern %p:\n", pat);                        \
1739   DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend);                       \
1740                                                                         \
1741   /* Restore register info.  */                                         \
1742   high_reg = (active_reg_t) POP_FAILURE_INT ();                         \
1743   DEBUG_PRINT2 ("  Popping high active reg: %ld\n", high_reg);          \
1744                                                                         \
1745   low_reg = (active_reg_t) POP_FAILURE_INT ();                          \
1746   DEBUG_PRINT2 ("  Popping  low active reg: %ld\n", low_reg);           \
1747                                                                         \
1748   if (1)                                                                \
1749     for (this_reg = high_reg; this_reg >= low_reg; this_reg--)          \
1750       {                                                                 \
1751         DEBUG_PRINT2 ("    Popping reg: %ld\n", this_reg);              \
1752                                                                         \
1753         reg_info[this_reg].word = POP_FAILURE_ELT ();                   \
1754         DEBUG_PRINT2 ("      info: %p\n",                               \
1755                       reg_info[this_reg].word.pointer);                 \
1756                                                                         \
1757         regend[this_reg] = (const CHAR_T *) POP_FAILURE_POINTER ();     \
1758         DEBUG_PRINT2 ("      end: %p\n", regend[this_reg]);             \
1759                                                                         \
1760         regstart[this_reg] = (const CHAR_T *) POP_FAILURE_POINTER ();   \
1761         DEBUG_PRINT2 ("      start: %p\n", regstart[this_reg]);         \
1762       }                                                                 \
1763   else                                                                  \
1764     {                                                                   \
1765       for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \
1766         {                                                               \
1767           reg_info[this_reg].word.integer = 0;                          \
1768           regend[this_reg] = 0;                                         \
1769           regstart[this_reg] = 0;                                       \
1770         }                                                               \
1771       highest_active_reg = high_reg;                                    \
1772     }                                                                   \
1773                                                                         \
1774   set_regs_matched_done = 0;                                            \
1775   DEBUG_STATEMENT (nfailure_points_popped++);                           \
1776 } /* POP_FAILURE_POINT */
1777 \f
1778 /* Structure for per-register (a.k.a. per-group) information.
1779    Other register information, such as the
1780    starting and ending positions (which are addresses), and the list of
1781    inner groups (which is a bits list) are maintained in separate
1782    variables.
1783
1784    We are making a (strictly speaking) nonportable assumption here: that
1785    the compiler will pack our bit fields into something that fits into
1786    the type of `word', i.e., is something that fits into one item on the
1787    failure stack.  */
1788
1789
1790 /* Declarations and macros for re_match_2.  */
1791
1792 typedef union
1793 {
1794   PREFIX(fail_stack_elt_t) word;
1795   struct
1796   {
1797       /* This field is one if this group can match the empty string,
1798          zero if not.  If not yet determined,  `MATCH_NULL_UNSET_VALUE'.  */
1799 # define MATCH_NULL_UNSET_VALUE 3
1800     unsigned match_null_string_p : 2;
1801     unsigned is_active : 1;
1802     unsigned matched_something : 1;
1803     unsigned ever_matched_something : 1;
1804   } bits;
1805 } PREFIX(register_info_type);
1806
1807 # ifndef DEFINED_ONCE
1808 #  define REG_MATCH_NULL_STRING_P(R)  ((R).bits.match_null_string_p)
1809 #  define IS_ACTIVE(R)  ((R).bits.is_active)
1810 #  define MATCHED_SOMETHING(R)  ((R).bits.matched_something)
1811 #  define EVER_MATCHED_SOMETHING(R)  ((R).bits.ever_matched_something)
1812
1813
1814 /* Call this when have matched a real character; it sets `matched' flags
1815    for the subexpressions which we are currently inside.  Also records
1816    that those subexprs have matched.  */
1817 #  define SET_REGS_MATCHED()                                            \
1818   do                                                                    \
1819     {                                                                   \
1820       if (!set_regs_matched_done)                                       \
1821         {                                                               \
1822           active_reg_t r;                                               \
1823           set_regs_matched_done = 1;                                    \
1824           for (r = lowest_active_reg; r <= highest_active_reg; r++)     \
1825             {                                                           \
1826               MATCHED_SOMETHING (reg_info[r])                           \
1827                 = EVER_MATCHED_SOMETHING (reg_info[r])                  \
1828                 = 1;                                                    \
1829             }                                                           \
1830         }                                                               \
1831     }                                                                   \
1832   while (0)
1833 # endif /* not DEFINED_ONCE */
1834
1835 /* Registers are set to a sentinel when they haven't yet matched.  */
1836 static CHAR_T PREFIX(reg_unset_dummy);
1837 # define REG_UNSET_VALUE (&PREFIX(reg_unset_dummy))
1838 # define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1839
1840 /* Subroutine declarations and macros for regex_compile.  */
1841 static void PREFIX(store_op1) (re_opcode_t op, UCHAR_T *loc, int arg);
1842 static void PREFIX(store_op2) (re_opcode_t op, UCHAR_T *loc,
1843                                int arg1, int arg2);
1844 static void PREFIX(insert_op1) (re_opcode_t op, UCHAR_T *loc,
1845                                 int arg, UCHAR_T *end);
1846 static void PREFIX(insert_op2) (re_opcode_t op, UCHAR_T *loc,
1847                                 int arg1, int arg2, UCHAR_T *end);
1848 static boolean PREFIX(at_begline_loc_p) (const CHAR_T *pattern,
1849                                          const CHAR_T *p,
1850                                          reg_syntax_t syntax);
1851 static boolean PREFIX(at_endline_loc_p) (const CHAR_T *p,
1852                                          const CHAR_T *pend,
1853                                          reg_syntax_t syntax);
1854 # ifdef WCHAR
1855 static reg_errcode_t wcs_compile_range (CHAR_T range_start,
1856                                         const CHAR_T **p_ptr,
1857                                         const CHAR_T *pend,
1858                                         char *translate,
1859                                         reg_syntax_t syntax,
1860                                         UCHAR_T *b,
1861                                         CHAR_T *char_set);
1862 static void insert_space (int num, CHAR_T *loc, CHAR_T *end);
1863 # else /* BYTE */
1864 static reg_errcode_t byte_compile_range (unsigned int range_start,
1865                                          const char **p_ptr,
1866                                          const char *pend,
1867                                          char *translate,
1868                                          reg_syntax_t syntax,
1869                                          unsigned char *b);
1870 # endif /* WCHAR */
1871
1872 /* Fetch the next character in the uncompiled pattern---translating it
1873    if necessary.  Also cast from a signed character in the constant
1874    string passed to us by the user to an unsigned char that we can use
1875    as an array index (in, e.g., `translate').  */
1876 /* ifdef MBS_SUPPORT, we translate only if character <= 0xff,
1877    because it is impossible to allocate 4GB array for some encodings
1878    which have 4 byte character_set like UCS4.  */
1879 # ifndef PATFETCH
1880 #  ifdef WCHAR
1881 #   define PATFETCH(c)                                                  \
1882   do {if (p == pend) return REG_EEND;                                   \
1883     c = (UCHAR_T) *p++;                                                 \
1884     if (translate && (c <= 0xff)) c = (UCHAR_T) translate[c];           \
1885   } while (0)
1886 #  else /* BYTE */
1887 #   define PATFETCH(c)                                                  \
1888   do {if (p == pend) return REG_EEND;                                   \
1889     c = (unsigned char) *p++;                                           \
1890     if (translate) c = (unsigned char) translate[c];                    \
1891   } while (0)
1892 #  endif /* WCHAR */
1893 # endif
1894
1895 /* Fetch the next character in the uncompiled pattern, with no
1896    translation.  */
1897 # define PATFETCH_RAW(c)                                                \
1898   do {if (p == pend) return REG_EEND;                                   \
1899     c = (UCHAR_T) *p++;                                                 \
1900   } while (0)
1901
1902 /* Go backwards one character in the pattern.  */
1903 # define PATUNFETCH p--
1904
1905
1906 /* If `translate' is non-null, return translate[D], else just D.  We
1907    cast the subscript to translate because some data is declared as
1908    `char *', to avoid warnings when a string constant is passed.  But
1909    when we use a character as a subscript we must make it unsigned.  */
1910 /* ifdef MBS_SUPPORT, we translate only if character <= 0xff,
1911    because it is impossible to allocate 4GB array for some encodings
1912    which have 4 byte character_set like UCS4.  */
1913
1914 # ifndef TRANSLATE
1915 #  ifdef WCHAR
1916 #   define TRANSLATE(d) \
1917   ((translate && ((UCHAR_T) (d)) <= 0xff) \
1918    ? (char) translate[(unsigned char) (d)] : (d))
1919 # else /* BYTE */
1920 #   define TRANSLATE(d) \
1921   (translate ? (char) translate[(unsigned char) (d)] : (d))
1922 #  endif /* WCHAR */
1923 # endif
1924
1925
1926 /* Macros for outputting the compiled pattern into `buffer'.  */
1927
1928 /* If the buffer isn't allocated when it comes in, use this.  */
1929 # define INIT_BUF_SIZE  (32 * sizeof(UCHAR_T))
1930
1931 /* Make sure we have at least N more bytes of space in buffer.  */
1932 # ifdef WCHAR
1933 #  define GET_BUFFER_SPACE(n)                                           \
1934     while (((unsigned long)b - (unsigned long)COMPILED_BUFFER_VAR       \
1935             + (n)*sizeof(CHAR_T)) > bufp->allocated)                    \
1936       EXTEND_BUFFER ()
1937 # else /* BYTE */
1938 #  define GET_BUFFER_SPACE(n)                                           \
1939     while ((unsigned long) (b - bufp->buffer + (n)) > bufp->allocated)  \
1940       EXTEND_BUFFER ()
1941 # endif /* WCHAR */
1942
1943 /* Make sure we have one more byte of buffer space and then add C to it.  */
1944 # define BUF_PUSH(c)                                                    \
1945   do {                                                                  \
1946     GET_BUFFER_SPACE (1);                                               \
1947     *b++ = (UCHAR_T) (c);                                               \
1948   } while (0)
1949
1950
1951 /* Ensure we have two more bytes of buffer space and then append C1 and C2.  */
1952 # define BUF_PUSH_2(c1, c2)                                             \
1953   do {                                                                  \
1954     GET_BUFFER_SPACE (2);                                               \
1955     *b++ = (UCHAR_T) (c1);                                              \
1956     *b++ = (UCHAR_T) (c2);                                              \
1957   } while (0)
1958
1959
1960 /* As with BUF_PUSH_2, except for three bytes.  */
1961 # define BUF_PUSH_3(c1, c2, c3)                                         \
1962   do {                                                                  \
1963     GET_BUFFER_SPACE (3);                                               \
1964     *b++ = (UCHAR_T) (c1);                                              \
1965     *b++ = (UCHAR_T) (c2);                                              \
1966     *b++ = (UCHAR_T) (c3);                                              \
1967   } while (0)
1968
1969 /* Store a jump with opcode OP at LOC to location TO.  We store a
1970    relative address offset by the three bytes the jump itself occupies.  */
1971 # define STORE_JUMP(op, loc, to) \
1972  PREFIX(store_op1) (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)))
1973
1974 /* Likewise, for a two-argument jump.  */
1975 # define STORE_JUMP2(op, loc, to, arg) \
1976   PREFIX(store_op2) (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)), arg)
1977
1978 /* Like `STORE_JUMP', but for inserting.  Assume `b' is the buffer end.  */
1979 # define INSERT_JUMP(op, loc, to) \
1980   PREFIX(insert_op1) (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)), b)
1981
1982 /* Like `STORE_JUMP2', but for inserting.  Assume `b' is the buffer end.  */
1983 # define INSERT_JUMP2(op, loc, to, arg) \
1984   PREFIX(insert_op2) (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)),\
1985               arg, b)
1986
1987 /* This is not an arbitrary limit: the arguments which represent offsets
1988    into the pattern are two bytes long.  So if 2^16 bytes turns out to
1989    be too small, many things would have to change.  */
1990 /* Any other compiler which, like MSC, has allocation limit below 2^16
1991    bytes will have to use approach similar to what was done below for
1992    MSC and drop MAX_BUF_SIZE a bit.  Otherwise you may end up
1993    reallocating to 0 bytes.  Such thing is not going to work too well.
1994    You have been warned!!  */
1995 # ifndef DEFINED_ONCE
1996 #  if defined _MSC_VER  && !defined WIN32
1997 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes.
1998    The REALLOC define eliminates a flurry of conversion warnings,
1999    but is not required. */
2000 #   define MAX_BUF_SIZE  65500L
2001 #   define REALLOC(p,s) realloc ((p), (size_t) (s))
2002 #  else
2003 #   define MAX_BUF_SIZE (1L << 16)
2004 #   define REALLOC(p,s) realloc ((p), (s))
2005 #  endif
2006
2007 /* Extend the buffer by twice its current size via realloc and
2008    reset the pointers that pointed into the old block to point to the
2009    correct places in the new one.  If extending the buffer results in it
2010    being larger than MAX_BUF_SIZE, then flag memory exhausted.  */
2011 #  if __BOUNDED_POINTERS__
2012 #   define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
2013 #   define MOVE_BUFFER_POINTER(P) \
2014   (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
2015 #   define ELSE_EXTEND_BUFFER_HIGH_BOUND        \
2016   else                                          \
2017     {                                           \
2018       SET_HIGH_BOUND (b);                       \
2019       SET_HIGH_BOUND (begalt);                  \
2020       if (fixup_alt_jump)                       \
2021         SET_HIGH_BOUND (fixup_alt_jump);        \
2022       if (laststart)                            \
2023         SET_HIGH_BOUND (laststart);             \
2024       if (pending_exact)                        \
2025         SET_HIGH_BOUND (pending_exact);         \
2026     }
2027 #  else
2028 #   define MOVE_BUFFER_POINTER(P) (P) += incr
2029 #   define ELSE_EXTEND_BUFFER_HIGH_BOUND
2030 #  endif
2031 # endif /* not DEFINED_ONCE */
2032
2033 # ifdef WCHAR
2034 #  define EXTEND_BUFFER()                                               \
2035   do {                                                                  \
2036     UCHAR_T *old_buffer = COMPILED_BUFFER_VAR;                          \
2037     int wchar_count;                                                    \
2038     if (bufp->allocated + sizeof(UCHAR_T) > MAX_BUF_SIZE)               \
2039       return REG_ESIZE;                                                 \
2040     bufp->allocated <<= 1;                                              \
2041     if (bufp->allocated > MAX_BUF_SIZE)                                 \
2042       bufp->allocated = MAX_BUF_SIZE;                                   \
2043     /* How many characters the new buffer can have?  */                 \
2044     wchar_count = bufp->allocated / sizeof(UCHAR_T);                    \
2045     if (wchar_count == 0) wchar_count = 1;                              \
2046     /* Truncate the buffer to CHAR_T align.  */                 \
2047     bufp->allocated = wchar_count * sizeof(UCHAR_T);                    \
2048     RETALLOC (COMPILED_BUFFER_VAR, wchar_count, UCHAR_T);               \
2049     bufp->buffer = (char*)COMPILED_BUFFER_VAR;                          \
2050     if (COMPILED_BUFFER_VAR == NULL)                                    \
2051       return REG_ESPACE;                                                \
2052     /* If the buffer moved, move all the pointers into it.  */          \
2053     if (old_buffer != COMPILED_BUFFER_VAR)                              \
2054       {                                                                 \
2055         int incr = COMPILED_BUFFER_VAR - old_buffer;                    \
2056         MOVE_BUFFER_POINTER (b);                                        \
2057         MOVE_BUFFER_POINTER (begalt);                                   \
2058         if (fixup_alt_jump)                                             \
2059           MOVE_BUFFER_POINTER (fixup_alt_jump);                         \
2060         if (laststart)                                                  \
2061           MOVE_BUFFER_POINTER (laststart);                              \
2062         if (pending_exact)                                              \
2063           MOVE_BUFFER_POINTER (pending_exact);                          \
2064       }                                                                 \
2065     ELSE_EXTEND_BUFFER_HIGH_BOUND                                       \
2066   } while (0)
2067 # else /* BYTE */
2068 #  define EXTEND_BUFFER()                                               \
2069   do {                                                                  \
2070     UCHAR_T *old_buffer = COMPILED_BUFFER_VAR;                          \
2071     if (bufp->allocated == MAX_BUF_SIZE)                                \
2072       return REG_ESIZE;                                                 \
2073     bufp->allocated <<= 1;                                              \
2074     if (bufp->allocated > MAX_BUF_SIZE)                                 \
2075       bufp->allocated = MAX_BUF_SIZE;                                   \
2076     bufp->buffer = (UCHAR_T *) REALLOC (COMPILED_BUFFER_VAR,            \
2077                                                 bufp->allocated);       \
2078     if (COMPILED_BUFFER_VAR == NULL)                                    \
2079       return REG_ESPACE;                                                \
2080     /* If the buffer moved, move all the pointers into it.  */          \
2081     if (old_buffer != COMPILED_BUFFER_VAR)                              \
2082       {                                                                 \
2083         int incr = COMPILED_BUFFER_VAR - old_buffer;                    \
2084         MOVE_BUFFER_POINTER (b);                                        \
2085         MOVE_BUFFER_POINTER (begalt);                                   \
2086         if (fixup_alt_jump)                                             \
2087           MOVE_BUFFER_POINTER (fixup_alt_jump);                         \
2088         if (laststart)                                                  \
2089           MOVE_BUFFER_POINTER (laststart);                              \
2090         if (pending_exact)                                              \
2091           MOVE_BUFFER_POINTER (pending_exact);                          \
2092       }                                                                 \
2093     ELSE_EXTEND_BUFFER_HIGH_BOUND                                       \
2094   } while (0)
2095 # endif /* WCHAR */
2096
2097 # ifndef DEFINED_ONCE
2098 /* Since we have one byte reserved for the register number argument to
2099    {start,stop}_memory, the maximum number of groups we can report
2100    things about is what fits in that byte.  */
2101 #  define MAX_REGNUM 255
2102
2103 /* But patterns can have more than `MAX_REGNUM' registers.  We just
2104    ignore the excess.  */
2105 typedef unsigned regnum_t;
2106
2107
2108 /* Macros for the compile stack.  */
2109
2110 /* Since offsets can go either forwards or backwards, this type needs to
2111    be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1.  */
2112 /* int may be not enough when sizeof(int) == 2.  */
2113 typedef long pattern_offset_t;
2114
2115 typedef struct
2116 {
2117   pattern_offset_t begalt_offset;
2118   pattern_offset_t fixup_alt_jump;
2119   pattern_offset_t inner_group_offset;
2120   pattern_offset_t laststart_offset;
2121   regnum_t regnum;
2122 } compile_stack_elt_t;
2123
2124
2125 typedef struct
2126 {
2127   compile_stack_elt_t *stack;
2128   unsigned size;
2129   unsigned avail;                       /* Offset of next open position.  */
2130 } compile_stack_type;
2131
2132
2133 #  define INIT_COMPILE_STACK_SIZE 32
2134
2135 #  define COMPILE_STACK_EMPTY  (compile_stack.avail == 0)
2136 #  define COMPILE_STACK_FULL  (compile_stack.avail == compile_stack.size)
2137
2138 /* The next available element.  */
2139 #  define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
2140
2141 # endif /* not DEFINED_ONCE */
2142
2143 /* Set the bit for character C in a list.  */
2144 # ifndef DEFINED_ONCE
2145 #  define SET_LIST_BIT(c)                               \
2146   (b[((unsigned char) (c)) / BYTEWIDTH]               \
2147    |= 1 << (((unsigned char) c) % BYTEWIDTH))
2148 # endif /* DEFINED_ONCE */
2149
2150 /* Get the next unsigned number in the uncompiled pattern.  */
2151 # define GET_UNSIGNED_NUMBER(num) \
2152   {                                                                     \
2153     while (p != pend)                                                   \
2154       {                                                                 \
2155         PATFETCH (c);                                                   \
2156         if (c < '0' || c > '9')                                         \
2157           break;                                                        \
2158         if (num <= RE_DUP_MAX)                                          \
2159           {                                                             \
2160             if (num < 0)                                                \
2161               num = 0;                                                  \
2162             num = num * 10 + c - '0';                                   \
2163           }                                                             \
2164       }                                                                 \
2165   }
2166
2167 # ifndef DEFINED_ONCE
2168 #  if defined _LIBC || WIDE_CHAR_SUPPORT
2169 /* The GNU C library provides support for user-defined character classes
2170    and the functions from ISO C amendement 1.  */
2171 #   ifdef CHARCLASS_NAME_MAX
2172 #    define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
2173 #   else
2174 /* This shouldn't happen but some implementation might still have this
2175    problem.  Use a reasonable default value.  */
2176 #    define CHAR_CLASS_MAX_LENGTH 256
2177 #   endif
2178
2179 #   ifdef _LIBC
2180 #    define IS_CHAR_CLASS(string) __wctype (string)
2181 #   else
2182 #    define IS_CHAR_CLASS(string) wctype (string)
2183 #   endif
2184 #  else
2185 #   define CHAR_CLASS_MAX_LENGTH  6 /* Namely, `xdigit'.  */
2186
2187 #   define IS_CHAR_CLASS(string)                                        \
2188    (STREQ (string, "alpha") || STREQ (string, "upper")                  \
2189     || STREQ (string, "lower") || STREQ (string, "digit")               \
2190     || STREQ (string, "alnum") || STREQ (string, "xdigit")              \
2191     || STREQ (string, "space") || STREQ (string, "print")               \
2192     || STREQ (string, "punct") || STREQ (string, "graph")               \
2193     || STREQ (string, "cntrl") || STREQ (string, "blank"))
2194 #  endif
2195 # endif /* DEFINED_ONCE */
2196 \f
2197 # ifndef MATCH_MAY_ALLOCATE
2198
2199 /* If we cannot allocate large objects within re_match_2_internal,
2200    we make the fail stack and register vectors global.
2201    The fail stack, we grow to the maximum size when a regexp
2202    is compiled.
2203    The register vectors, we adjust in size each time we
2204    compile a regexp, according to the number of registers it needs.  */
2205
2206 static PREFIX(fail_stack_type) fail_stack;
2207
2208 /* Size with which the following vectors are currently allocated.
2209    That is so we can make them bigger as needed,
2210    but never make them smaller.  */
2211 #  ifdef DEFINED_ONCE
2212 static int regs_allocated_size;
2213
2214 static const char **     regstart, **     regend;
2215 static const char ** old_regstart, ** old_regend;
2216 static const char **best_regstart, **best_regend;
2217 static const char **reg_dummy;
2218 #  endif /* DEFINED_ONCE */
2219
2220 static PREFIX(register_info_type) *PREFIX(reg_info);
2221 static PREFIX(register_info_type) *PREFIX(reg_info_dummy);
2222
2223 /* Make the register vectors big enough for NUM_REGS registers,
2224    but don't make them smaller.  */
2225
2226 static void
2227 PREFIX(regex_grow_registers) (int num_regs)
2228 {
2229   if (num_regs > regs_allocated_size)
2230     {
2231       RETALLOC_IF (regstart,     num_regs, const char *);
2232       RETALLOC_IF (regend,       num_regs, const char *);
2233       RETALLOC_IF (old_regstart, num_regs, const char *);
2234       RETALLOC_IF (old_regend,   num_regs, const char *);
2235       RETALLOC_IF (best_regstart, num_regs, const char *);
2236       RETALLOC_IF (best_regend,  num_regs, const char *);
2237       RETALLOC_IF (PREFIX(reg_info), num_regs, PREFIX(register_info_type));
2238       RETALLOC_IF (reg_dummy,    num_regs, const char *);
2239       RETALLOC_IF (PREFIX(reg_info_dummy), num_regs, PREFIX(register_info_type));
2240
2241       regs_allocated_size = num_regs;
2242     }
2243 }
2244
2245 # endif /* not MATCH_MAY_ALLOCATE */
2246 \f
2247 # ifndef DEFINED_ONCE
2248 static boolean group_in_compile_stack (compile_stack_type compile_stack,
2249                                        regnum_t regnum);
2250 # endif /* not DEFINED_ONCE */
2251
2252 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2253    Returns one of error codes defined in `regex.h', or zero for success.
2254
2255    Assumes the `allocated' (and perhaps `buffer') and `translate'
2256    fields are set in BUFP on entry.
2257
2258    If it succeeds, results are put in BUFP (if it returns an error, the
2259    contents of BUFP are undefined):
2260      `buffer' is the compiled pattern;
2261      `syntax' is set to SYNTAX;
2262      `used' is set to the length of the compiled pattern;
2263      `fastmap_accurate' is zero;
2264      `re_nsub' is the number of subexpressions in PATTERN;
2265      `not_bol' and `not_eol' are zero;
2266
2267    The `fastmap' and `newline_anchor' fields are neither
2268    examined nor set.  */
2269
2270 /* Return, freeing storage we allocated.  */
2271 # ifdef WCHAR
2272 #  define FREE_STACK_RETURN(value)              \
2273   return (free(pattern), free(mbs_offset), free(is_binary), free (compile_stack.stack), value)
2274 # else
2275 #  define FREE_STACK_RETURN(value)              \
2276   return (free (compile_stack.stack), value)
2277 # endif /* WCHAR */
2278
2279 static reg_errcode_t
2280 PREFIX(regex_compile) (const char *ARG_PREFIX(pattern),
2281                        size_t ARG_PREFIX(size), reg_syntax_t syntax,
2282                        struct re_pattern_buffer *bufp)
2283 {
2284   /* We fetch characters from PATTERN here.  Even though PATTERN is
2285      `char *' (i.e., signed), we declare these variables as unsigned, so
2286      they can be reliably used as array indices.  */
2287   register UCHAR_T c, c1;
2288
2289 #ifdef WCHAR
2290   /* A temporary space to keep wchar_t pattern and compiled pattern.  */
2291   CHAR_T *pattern, *COMPILED_BUFFER_VAR;
2292   size_t size;
2293   /* offset buffer for optimization. See convert_mbs_to_wc.  */
2294   int *mbs_offset = NULL;
2295   /* It hold whether each wchar_t is binary data or not.  */
2296   char *is_binary = NULL;
2297   /* A flag whether exactn is handling binary data or not.  */
2298   char is_exactn_bin = FALSE;
2299 #endif /* WCHAR */
2300
2301   /* A random temporary spot in PATTERN.  */
2302   const CHAR_T *p1;
2303
2304   /* Points to the end of the buffer, where we should append.  */
2305   register UCHAR_T *b;
2306
2307   /* Keeps track of unclosed groups.  */
2308   compile_stack_type compile_stack;
2309
2310   /* Points to the current (ending) position in the pattern.  */
2311 #ifdef WCHAR
2312   const CHAR_T *p;
2313   const CHAR_T *pend;
2314 #else /* BYTE */
2315   const CHAR_T *p = pattern;
2316   const CHAR_T *pend = pattern + size;
2317 #endif /* WCHAR */
2318
2319   /* How to translate the characters in the pattern.  */
2320   RE_TRANSLATE_TYPE translate = bufp->translate;
2321
2322   /* Address of the count-byte of the most recently inserted `exactn'
2323      command.  This makes it possible to tell if a new exact-match
2324      character can be added to that command or if the character requires
2325      a new `exactn' command.  */
2326   UCHAR_T *pending_exact = 0;
2327
2328   /* Address of start of the most recently finished expression.
2329      This tells, e.g., postfix * where to find the start of its
2330      operand.  Reset at the beginning of groups and alternatives.  */
2331   UCHAR_T *laststart = 0;
2332
2333   /* Address of beginning of regexp, or inside of last group.  */
2334   UCHAR_T *begalt;
2335
2336   /* Address of the place where a forward jump should go to the end of
2337      the containing expression.  Each alternative of an `or' -- except the
2338      last -- ends with a forward jump of this sort.  */
2339   UCHAR_T *fixup_alt_jump = 0;
2340
2341   /* Counts open-groups as they are encountered.  Remembered for the
2342      matching close-group on the compile stack, so the same register
2343      number is put in the stop_memory as the start_memory.  */
2344   regnum_t regnum = 0;
2345
2346 #ifdef WCHAR
2347   /* Initialize the wchar_t PATTERN and offset_buffer.  */
2348   p = pend = pattern = TALLOC(csize + 1, CHAR_T);
2349   mbs_offset = TALLOC(csize + 1, int);
2350   is_binary = TALLOC(csize + 1, char);
2351   if (pattern == NULL || mbs_offset == NULL || is_binary == NULL)
2352     {
2353       free(pattern);
2354       free(mbs_offset);
2355       free(is_binary);
2356       return REG_ESPACE;
2357     }
2358   pattern[csize] = L'\0';       /* sentinel */
2359   size = convert_mbs_to_wcs(pattern, cpattern, csize, mbs_offset, is_binary);
2360   pend = p + size;
2361   if (size < 0)
2362     {
2363       free(pattern);
2364       free(mbs_offset);
2365       free(is_binary);
2366       return REG_BADPAT;
2367     }
2368 #endif
2369
2370 #ifdef DEBUG
2371   DEBUG_PRINT1 ("\nCompiling pattern: ");
2372   if (debug)
2373     {
2374       unsigned debug_count;
2375
2376       for (debug_count = 0; debug_count < size; debug_count++)
2377         PUT_CHAR (pattern[debug_count]);
2378       putchar ('\n');
2379     }
2380 #endif /* DEBUG */
2381
2382   /* Initialize the compile stack.  */
2383   compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2384   if (compile_stack.stack == NULL)
2385     {
2386 #ifdef WCHAR
2387       free(pattern);
2388       free(mbs_offset);
2389       free(is_binary);
2390 #endif
2391       return REG_ESPACE;
2392     }
2393
2394   compile_stack.size = INIT_COMPILE_STACK_SIZE;
2395   compile_stack.avail = 0;
2396
2397   /* Initialize the pattern buffer.  */
2398   bufp->syntax = syntax;
2399   bufp->fastmap_accurate = 0;
2400   bufp->not_bol = bufp->not_eol = 0;
2401
2402   /* Set `used' to zero, so that if we return an error, the pattern
2403      printer (for debugging) will think there's no pattern.  We reset it
2404      at the end.  */
2405   bufp->used = 0;
2406
2407   /* Always count groups, whether or not bufp->no_sub is set.  */
2408   bufp->re_nsub = 0;
2409
2410 #if !defined emacs && !defined SYNTAX_TABLE
2411   /* Initialize the syntax table.  */
2412    init_syntax_once ();
2413 #endif
2414
2415   if (bufp->allocated == 0)
2416     {
2417       if (bufp->buffer)
2418         { /* If zero allocated, but buffer is non-null, try to realloc
2419              enough space.  This loses if buffer's address is bogus, but
2420              that is the user's responsibility.  */
2421 #ifdef WCHAR
2422           /* Free bufp->buffer and allocate an array for wchar_t pattern
2423              buffer.  */
2424           free(bufp->buffer);
2425           COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE/sizeof(UCHAR_T),
2426                                         UCHAR_T);
2427 #else
2428           RETALLOC (COMPILED_BUFFER_VAR, INIT_BUF_SIZE, UCHAR_T);
2429 #endif /* WCHAR */
2430         }
2431       else
2432         { /* Caller did not allocate a buffer.  Do it for them.  */
2433           COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE / sizeof(UCHAR_T),
2434                                         UCHAR_T);
2435         }
2436
2437       if (!COMPILED_BUFFER_VAR) FREE_STACK_RETURN (REG_ESPACE);
2438 #ifdef WCHAR
2439       bufp->buffer = (char*)COMPILED_BUFFER_VAR;
2440 #endif /* WCHAR */
2441       bufp->allocated = INIT_BUF_SIZE;
2442     }
2443 #ifdef WCHAR
2444   else
2445     COMPILED_BUFFER_VAR = (UCHAR_T*) bufp->buffer;
2446 #endif
2447
2448   begalt = b = COMPILED_BUFFER_VAR;
2449
2450   /* Loop through the uncompiled pattern until we're at the end.  */
2451   while (p != pend)
2452     {
2453       PATFETCH (c);
2454
2455       switch (c)
2456         {
2457         case '^':
2458           {
2459             if (   /* If at start of pattern, it's an operator.  */
2460                    p == pattern + 1
2461                    /* If context independent, it's an operator.  */
2462                 || syntax & RE_CONTEXT_INDEP_ANCHORS
2463                    /* Otherwise, depends on what's come before.  */
2464                 || PREFIX(at_begline_loc_p) (pattern, p, syntax))
2465               BUF_PUSH (begline);
2466             else
2467               goto normal_char;
2468           }
2469           break;
2470
2471
2472         case '$':
2473           {
2474             if (   /* If at end of pattern, it's an operator.  */
2475                    p == pend
2476                    /* If context independent, it's an operator.  */
2477                 || syntax & RE_CONTEXT_INDEP_ANCHORS
2478                    /* Otherwise, depends on what's next.  */
2479                 || PREFIX(at_endline_loc_p) (p, pend, syntax))
2480                BUF_PUSH (endline);
2481              else
2482                goto normal_char;
2483            }
2484            break;
2485
2486
2487         case '+':
2488         case '?':
2489           if ((syntax & RE_BK_PLUS_QM)
2490               || (syntax & RE_LIMITED_OPS))
2491             goto normal_char;
2492         handle_plus:
2493         case '*':
2494           /* If there is no previous pattern... */
2495           if (!laststart)
2496             {
2497               if (syntax & RE_CONTEXT_INVALID_OPS)
2498                 FREE_STACK_RETURN (REG_BADRPT);
2499               else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2500                 goto normal_char;
2501             }
2502
2503           {
2504             /* Are we optimizing this jump?  */
2505             boolean keep_string_p = false;
2506
2507             /* 1 means zero (many) matches is allowed.  */
2508             char zero_times_ok = 0, many_times_ok = 0;
2509
2510             /* If there is a sequence of repetition chars, collapse it
2511                down to just one (the right one).  We can't combine
2512                interval operators with these because of, e.g., `a{2}*',
2513                which should only match an even number of `a's.  */
2514
2515             for (;;)
2516               {
2517                 zero_times_ok |= c != '+';
2518                 many_times_ok |= c != '?';
2519
2520                 if (p == pend)
2521                   break;
2522
2523                 PATFETCH (c);
2524
2525                 if (c == '*'
2526                     || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
2527                   ;
2528
2529                 else if (syntax & RE_BK_PLUS_QM  &&  c == '\\')
2530                   {
2531                     if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2532
2533                     PATFETCH (c1);
2534                     if (!(c1 == '+' || c1 == '?'))
2535                       {
2536                         PATUNFETCH;
2537                         PATUNFETCH;
2538                         break;
2539                       }
2540
2541                     c = c1;
2542                   }
2543                 else
2544                   {
2545                     PATUNFETCH;
2546                     break;
2547                   }
2548
2549                 /* If we get here, we found another repeat character.  */
2550                }
2551
2552             /* Star, etc. applied to an empty pattern is equivalent
2553                to an empty pattern.  */
2554             if (!laststart)
2555               break;
2556
2557             /* Now we know whether or not zero matches is allowed
2558                and also whether or not two or more matches is allowed.  */
2559             if (many_times_ok)
2560               { /* More than one repetition is allowed, so put in at the
2561                    end a backward relative jump from `b' to before the next
2562                    jump we're going to put in below (which jumps from
2563                    laststart to after this jump).
2564
2565                    But if we are at the `*' in the exact sequence `.*\n',
2566                    insert an unconditional jump backwards to the .,
2567                    instead of the beginning of the loop.  This way we only
2568                    push a failure point once, instead of every time
2569                    through the loop.  */
2570                 assert (p - 1 > pattern);
2571
2572                 /* Allocate the space for the jump.  */
2573                 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2574
2575                 /* We know we are not at the first character of the pattern,
2576                    because laststart was nonzero.  And we've already
2577                    incremented `p', by the way, to be the character after
2578                    the `*'.  Do we have to do something analogous here
2579                    for null bytes, because of RE_DOT_NOT_NULL?  */
2580                 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
2581                     && zero_times_ok
2582                     && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
2583                     && !(syntax & RE_DOT_NEWLINE))
2584                   { /* We have .*\n.  */
2585                     STORE_JUMP (jump, b, laststart);
2586                     keep_string_p = true;
2587                   }
2588                 else
2589                   /* Anything else.  */
2590                   STORE_JUMP (maybe_pop_jump, b, laststart -
2591                               (1 + OFFSET_ADDRESS_SIZE));
2592
2593                 /* We've added more stuff to the buffer.  */
2594                 b += 1 + OFFSET_ADDRESS_SIZE;
2595               }
2596
2597             /* On failure, jump from laststart to b + 3, which will be the
2598                end of the buffer after this jump is inserted.  */
2599             /* ifdef WCHAR, 'b + 1 + OFFSET_ADDRESS_SIZE' instead of
2600                'b + 3'.  */
2601             GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2602             INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2603                                        : on_failure_jump,
2604                          laststart, b + 1 + OFFSET_ADDRESS_SIZE);
2605             pending_exact = 0;
2606             b += 1 + OFFSET_ADDRESS_SIZE;
2607
2608             if (!zero_times_ok)
2609               {
2610                 /* At least one repetition is required, so insert a
2611                    `dummy_failure_jump' before the initial
2612                    `on_failure_jump' instruction of the loop. This
2613                    effects a skip over that instruction the first time
2614                    we hit that loop.  */
2615                 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2616                 INSERT_JUMP (dummy_failure_jump, laststart, laststart +
2617                              2 + 2 * OFFSET_ADDRESS_SIZE);
2618                 b += 1 + OFFSET_ADDRESS_SIZE;
2619               }
2620             }
2621           break;
2622
2623
2624         case '.':
2625           laststart = b;
2626           BUF_PUSH (anychar);
2627           break;
2628
2629
2630         case '[':
2631           {
2632             boolean had_char_class = false;
2633 #ifdef WCHAR
2634             CHAR_T range_start = 0xffffffff;
2635 #else
2636             unsigned int range_start = 0xffffffff;
2637 #endif
2638             if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2639
2640 #ifdef WCHAR
2641             /* We assume a charset(_not) structure as a wchar_t array.
2642                charset[0] = (re_opcode_t) charset(_not)
2643                charset[1] = l (= length of char_classes)
2644                charset[2] = m (= length of collating_symbols)
2645                charset[3] = n (= length of equivalence_classes)
2646                charset[4] = o (= length of char_ranges)
2647                charset[5] = p (= length of chars)
2648
2649                charset[6] = char_class (wctype_t)
2650                charset[6+CHAR_CLASS_SIZE] = char_class (wctype_t)
2651                          ...
2652                charset[l+5]  = char_class (wctype_t)
2653
2654                charset[l+6]  = collating_symbol (wchar_t)
2655                             ...
2656                charset[l+m+5]  = collating_symbol (wchar_t)
2657                                         ifdef _LIBC we use the index if
2658                                         _NL_COLLATE_SYMB_EXTRAMB instead of
2659                                         wchar_t string.
2660
2661                charset[l+m+6]  = equivalence_classes (wchar_t)
2662                               ...
2663                charset[l+m+n+5]  = equivalence_classes (wchar_t)
2664                                         ifdef _LIBC we use the index in
2665                                         _NL_COLLATE_WEIGHT instead of
2666                                         wchar_t string.
2667
2668                charset[l+m+n+6] = range_start
2669                charset[l+m+n+7] = range_end
2670                                ...
2671                charset[l+m+n+2o+4] = range_start
2672                charset[l+m+n+2o+5] = range_end
2673                                         ifdef _LIBC we use the value looked up
2674                                         in _NL_COLLATE_COLLSEQ instead of
2675                                         wchar_t character.
2676
2677                charset[l+m+n+2o+6] = char
2678                                   ...
2679                charset[l+m+n+2o+p+5] = char
2680
2681              */
2682
2683             /* We need at least 6 spaces: the opcode, the length of
2684                char_classes, the length of collating_symbols, the length of
2685                equivalence_classes, the length of char_ranges, the length of
2686                chars.  */
2687             GET_BUFFER_SPACE (6);
2688
2689             /* Save b as laststart. And We use laststart as the pointer
2690                to the first element of the charset here.
2691                In other words, laststart[i] indicates charset[i].  */
2692             laststart = b;
2693
2694             /* We test `*p == '^' twice, instead of using an if
2695                statement, so we only need one BUF_PUSH.  */
2696             BUF_PUSH (*p == '^' ? charset_not : charset);
2697             if (*p == '^')
2698               p++;
2699
2700             /* Push the length of char_classes, the length of
2701                collating_symbols, the length of equivalence_classes, the
2702                length of char_ranges and the length of chars.  */
2703             BUF_PUSH_3 (0, 0, 0);
2704             BUF_PUSH_2 (0, 0);
2705
2706             /* Remember the first position in the bracket expression.  */
2707             p1 = p;
2708
2709             /* charset_not matches newline according to a syntax bit.  */
2710             if ((re_opcode_t) b[-6] == charset_not
2711                 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2712               {
2713                 BUF_PUSH('\n');
2714                 laststart[5]++; /* Update the length of characters  */
2715               }
2716
2717             /* Read in characters and ranges, setting map bits.  */
2718             for (;;)
2719               {
2720                 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2721
2722                 PATFETCH (c);
2723
2724                 /* \ might escape characters inside [...] and [^...].  */
2725                 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2726                   {
2727                     if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2728
2729                     PATFETCH (c1);
2730                     BUF_PUSH(c1);
2731                     laststart[5]++; /* Update the length of chars  */
2732                     range_start = c1;
2733                     continue;
2734                   }
2735
2736                 /* Could be the end of the bracket expression.  If it's
2737                    not (i.e., when the bracket expression is `[]' so
2738                    far), the ']' character bit gets set way below.  */
2739                 if (c == ']' && p != p1 + 1)
2740                   break;
2741
2742                 /* Look ahead to see if it's a range when the last thing
2743                    was a character class.  */
2744                 if (had_char_class && c == '-' && *p != ']')
2745                   FREE_STACK_RETURN (REG_ERANGE);
2746
2747                 /* Look ahead to see if it's a range when the last thing
2748                    was a character: if this is a hyphen not at the
2749                    beginning or the end of a list, then it's the range
2750                    operator.  */
2751                 if (c == '-'
2752                     && !(p - 2 >= pattern && p[-2] == '[')
2753                     && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
2754                     && *p != ']')
2755                   {
2756                     reg_errcode_t ret;
2757                     /* Allocate the space for range_start and range_end.  */
2758                     GET_BUFFER_SPACE (2);
2759                     /* Update the pointer to indicate end of buffer.  */
2760                     b += 2;
2761                     ret = wcs_compile_range (range_start, &p, pend, translate,
2762                                          syntax, b, laststart);
2763                     if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2764                     range_start = 0xffffffff;
2765                   }
2766                 else if (p[0] == '-' && p[1] != ']')
2767                   { /* This handles ranges made up of characters only.  */
2768                     reg_errcode_t ret;
2769
2770                     /* Move past the `-'.  */
2771                     PATFETCH (c1);
2772                     /* Allocate the space for range_start and range_end.  */
2773                     GET_BUFFER_SPACE (2);
2774                     /* Update the pointer to indicate end of buffer.  */
2775                     b += 2;
2776                     ret = wcs_compile_range (c, &p, pend, translate, syntax, b,
2777                                          laststart);
2778                     if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2779                     range_start = 0xffffffff;
2780                   }
2781
2782                 /* See if we're at the beginning of a possible character
2783                    class.  */
2784                 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2785                   { /* Leave room for the null.  */
2786                     char str[CHAR_CLASS_MAX_LENGTH + 1];
2787
2788                     PATFETCH (c);
2789                     c1 = 0;
2790
2791                     /* If pattern is `[[:'.  */
2792                     if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2793
2794                     for (;;)
2795                       {
2796                         PATFETCH (c);
2797                         if ((c == ':' && *p == ']') || p == pend)
2798                           break;
2799                         if (c1 < CHAR_CLASS_MAX_LENGTH)
2800                           str[c1++] = c;
2801                         else
2802                           /* This is in any case an invalid class name.  */
2803                           str[0] = '\0';
2804                       }
2805                     str[c1] = '\0';
2806
2807                     /* If isn't a word bracketed by `[:' and `:]':
2808                        undo the ending character, the letters, and leave
2809                        the leading `:' and `[' (but store them as character).  */
2810                     if (c == ':' && *p == ']')
2811                       {
2812                         wctype_t wt;
2813                         uintptr_t alignedp;
2814
2815                         /* Query the character class as wctype_t.  */
2816                         wt = IS_CHAR_CLASS (str);
2817                         if (wt == 0)
2818                           FREE_STACK_RETURN (REG_ECTYPE);
2819
2820                         /* Throw away the ] at the end of the character
2821                            class.  */
2822                         PATFETCH (c);
2823
2824                         if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2825
2826                         /* Allocate the space for character class.  */
2827                         GET_BUFFER_SPACE(CHAR_CLASS_SIZE);
2828                         /* Update the pointer to indicate end of buffer.  */
2829                         b += CHAR_CLASS_SIZE;
2830                         /* Move data which follow character classes
2831                             not to violate the data.  */
2832                         insert_space(CHAR_CLASS_SIZE,
2833                                      laststart + 6 + laststart[1],
2834                                      b - 1);
2835                         alignedp = ((uintptr_t)(laststart + 6 + laststart[1])
2836                                     + __alignof__(wctype_t) - 1)
2837                                     & ~(uintptr_t)(__alignof__(wctype_t) - 1);
2838                         /* Store the character class.  */
2839                         *((wctype_t*)alignedp) = wt;
2840                         /* Update length of char_classes */
2841                         laststart[1] += CHAR_CLASS_SIZE;
2842
2843                         had_char_class = true;
2844                       }
2845                     else
2846                       {
2847                         c1++;
2848                         while (c1--)
2849                           PATUNFETCH;
2850                         BUF_PUSH ('[');
2851                         BUF_PUSH (':');
2852                         laststart[5] += 2; /* Update the length of characters  */
2853                         range_start = ':';
2854                         had_char_class = false;
2855                       }
2856                   }
2857                 else if (syntax & RE_CHAR_CLASSES && c == '[' && (*p == '='
2858                                                           || *p == '.'))
2859                   {
2860                     CHAR_T str[128];    /* Should be large enough.  */
2861                     CHAR_T delim = *p; /* '=' or '.'  */
2862 # ifdef _LIBC
2863                     uint32_t nrules =
2864                       _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
2865 # endif
2866                     PATFETCH (c);
2867                     c1 = 0;
2868
2869                     /* If pattern is `[[=' or '[[.'.  */
2870                     if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2871
2872                     for (;;)
2873                       {
2874                         PATFETCH (c);
2875                         if ((c == delim && *p == ']') || p == pend)
2876                           break;
2877                         if (c1 < sizeof (str) - 1)
2878                           str[c1++] = c;
2879                         else
2880                           /* This is in any case an invalid class name.  */
2881                           str[0] = '\0';
2882                       }
2883                     str[c1] = '\0';
2884
2885                     if (c == delim && *p == ']' && str[0] != '\0')
2886                       {
2887                         unsigned int i, offset;
2888                         /* If we have no collation data we use the default
2889                            collation in which each character is in a class
2890                            by itself.  It also means that ASCII is the
2891                            character set and therefore we cannot have character
2892                            with more than one byte in the multibyte
2893                            representation.  */
2894
2895                         /* If not defined _LIBC, we push the name and
2896                            `\0' for the sake of matching performance.  */
2897                         int datasize = c1 + 1;
2898
2899 # ifdef _LIBC
2900                         int32_t idx = 0;
2901                         if (nrules == 0)
2902 # endif
2903                           {
2904                             if (c1 != 1)
2905                               FREE_STACK_RETURN (REG_ECOLLATE);
2906                           }
2907 # ifdef _LIBC
2908                         else
2909                           {
2910                             const int32_t *table;
2911                             const int32_t *weights;
2912                             const int32_t *extra;
2913                             const int32_t *indirect;
2914                             wint_t *cp;
2915
2916                             /* This #include defines a local function!  */
2917 #  include <locale/weightwc.h>
2918
2919                             if(delim == '=')
2920                               {
2921                                 /* We push the index for equivalence class.  */
2922                                 cp = (wint_t*)str;
2923
2924                                 table = (const int32_t *)
2925                                   _NL_CURRENT (LC_COLLATE,
2926                                                _NL_COLLATE_TABLEWC);
2927                                 weights = (const int32_t *)
2928                                   _NL_CURRENT (LC_COLLATE,
2929                                                _NL_COLLATE_WEIGHTWC);
2930                                 extra = (const int32_t *)
2931                                   _NL_CURRENT (LC_COLLATE,
2932                                                _NL_COLLATE_EXTRAWC);
2933                                 indirect = (const int32_t *)
2934                                   _NL_CURRENT (LC_COLLATE,
2935                                                _NL_COLLATE_INDIRECTWC);
2936
2937                                 idx = findidx ((const wint_t**)&cp);
2938                                 if (idx == 0 || cp < (wint_t*) str + c1)
2939                                   /* This is no valid character.  */
2940                                   FREE_STACK_RETURN (REG_ECOLLATE);
2941
2942                                 str[0] = (wchar_t)idx;
2943                               }
2944                             else /* delim == '.' */
2945                               {
2946                                 /* We push collation sequence value
2947                                    for collating symbol.  */
2948                                 int32_t table_size;
2949                                 const int32_t *symb_table;
2950                                 const unsigned char *extra;
2951                                 int32_t idx;
2952                                 int32_t elem;
2953                                 int32_t second;
2954                                 int32_t hash;
2955                                 char char_str[c1];
2956
2957                                 /* We have to convert the name to a single-byte
2958                                    string.  This is possible since the names
2959                                    consist of ASCII characters and the internal
2960                                    representation is UCS4.  */
2961                                 for (i = 0; i < c1; ++i)
2962                                   char_str[i] = str[i];
2963
2964                                 table_size =
2965                                   _NL_CURRENT_WORD (LC_COLLATE,
2966                                                     _NL_COLLATE_SYMB_HASH_SIZEMB);
2967                                 symb_table = (const int32_t *)
2968                                   _NL_CURRENT (LC_COLLATE,
2969                                                _NL_COLLATE_SYMB_TABLEMB);
2970                                 extra = (const unsigned char *)
2971                                   _NL_CURRENT (LC_COLLATE,
2972                                                _NL_COLLATE_SYMB_EXTRAMB);
2973
2974                                 /* Locate the character in the hashing table.  */
2975                                 hash = elem_hash (char_str, c1);
2976
2977                                 idx = 0;
2978                                 elem = hash % table_size;
2979                                 second = hash % (table_size - 2);
2980                                 while (symb_table[2 * elem] != 0)
2981                                   {
2982                                     /* First compare the hashing value.  */
2983                                     if (symb_table[2 * elem] == hash
2984                                         && c1 == extra[symb_table[2 * elem + 1]]
2985                                         && memcmp (char_str,
2986                                                    &extra[symb_table[2 * elem + 1]
2987                                                          + 1], c1) == 0)
2988                                       {
2989                                         /* Yep, this is the entry.  */
2990                                         idx = symb_table[2 * elem + 1];
2991                                         idx += 1 + extra[idx];
2992                                         break;
2993                                       }
2994
2995                                     /* Next entry.  */
2996                                     elem += second;
2997                                   }
2998
2999                                 if (symb_table[2 * elem] != 0)
3000                                   {
3001                                     /* Compute the index of the byte sequence
3002                                        in the table.  */
3003                                     idx += 1 + extra[idx];
3004                                     /* Adjust for the alignment.  */
3005                                     idx = (idx + 3) & ~3;
3006
3007                                     str[0] = (wchar_t) idx + 4;
3008                                   }
3009                                 else if (symb_table[2 * elem] == 0 && c1 == 1)
3010                                   {
3011                                     /* No valid character.  Match it as a
3012                                        single byte character.  */
3013                                     had_char_class = false;
3014                                     BUF_PUSH(str[0]);
3015                                     /* Update the length of characters  */
3016                                     laststart[5]++;
3017                                     range_start = str[0];
3018
3019                                     /* Throw away the ] at the end of the
3020                                        collating symbol.  */
3021                                     PATFETCH (c);
3022                                     /* exit from the switch block.  */
3023                                     continue;
3024                                   }
3025                                 else
3026                                   FREE_STACK_RETURN (REG_ECOLLATE);
3027                               }
3028                             datasize = 1;
3029                           }
3030 # endif
3031                         /* Throw away the ] at the end of the equivalence
3032                            class (or collating symbol).  */
3033                         PATFETCH (c);
3034
3035                         /* Allocate the space for the equivalence class
3036                            (or collating symbol) (and '\0' if needed).  */
3037                         GET_BUFFER_SPACE(datasize);
3038                         /* Update the pointer to indicate end of buffer.  */
3039                         b += datasize;
3040
3041                         if (delim == '=')
3042                           { /* equivalence class  */
3043                             /* Calculate the offset of char_ranges,
3044                                which is next to equivalence_classes.  */
3045                             offset = laststart[1] + laststart[2]
3046                               + laststart[3] +6;
3047                             /* Insert space.  */
3048                             insert_space(datasize, laststart + offset, b - 1);
3049
3050                             /* Write the equivalence_class and \0.  */
3051                             for (i = 0 ; i < datasize ; i++)
3052                               laststart[offset + i] = str[i];
3053
3054                             /* Update the length of equivalence_classes.  */
3055                             laststart[3] += datasize;
3056                             had_char_class = true;
3057                           }
3058                         else /* delim == '.' */
3059                           { /* collating symbol  */
3060                             /* Calculate the offset of the equivalence_classes,
3061                                which is next to collating_symbols.  */
3062                             offset = laststart[1] + laststart[2] + 6;
3063                             /* Insert space and write the collationg_symbol
3064                                and \0.  */
3065                             insert_space(datasize, laststart + offset, b-1);
3066                             for (i = 0 ; i < datasize ; i++)
3067                               laststart[offset + i] = str[i];
3068
3069                             /* In re_match_2_internal if range_start < -1, we
3070                                assume -range_start is the offset of the
3071                                collating symbol which is specified as
3072                                the character of the range start.  So we assign
3073                                -(laststart[1] + laststart[2] + 6) to
3074                                range_start.  */
3075                             range_start = -(laststart[1] + laststart[2] + 6);
3076                             /* Update the length of collating_symbol.  */
3077                             laststart[2] += datasize;
3078                             had_char_class = false;
3079                           }
3080                       }
3081                     else
3082                       {
3083                         c1++;
3084                         while (c1--)
3085                           PATUNFETCH;
3086                         BUF_PUSH ('[');
3087                         BUF_PUSH (delim);
3088                         laststart[5] += 2; /* Update the length of characters  */
3089                         range_start = delim;
3090                         had_char_class = false;
3091                       }
3092                   }
3093                 else
3094                   {
3095                     had_char_class = false;
3096                     BUF_PUSH(c);
3097                     laststart[5]++;  /* Update the length of characters  */
3098                     range_start = c;
3099                   }
3100               }
3101
3102 #else /* BYTE */
3103             /* Ensure that we have enough space to push a charset: the
3104                opcode, the length count, and the bitset; 34 bytes in all.  */
3105             GET_BUFFER_SPACE (34);
3106
3107             laststart = b;
3108
3109             /* We test `*p == '^' twice, instead of using an if
3110                statement, so we only need one BUF_PUSH.  */
3111             BUF_PUSH (*p == '^' ? charset_not : charset);
3112             if (*p == '^')
3113               p++;
3114
3115             /* Remember the first position in the bracket expression.  */
3116             p1 = p;
3117
3118             /* Push the number of bytes in the bitmap.  */
3119             BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
3120
3121             /* Clear the whole map.  */
3122             bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
3123
3124             /* charset_not matches newline according to a syntax bit.  */
3125             if ((re_opcode_t) b[-2] == charset_not
3126                 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
3127               SET_LIST_BIT ('\n');
3128
3129             /* Read in characters and ranges, setting map bits.  */
3130             for (;;)
3131               {
3132                 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3133
3134                 PATFETCH (c);
3135
3136                 /* \ might escape characters inside [...] and [^...].  */
3137                 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
3138                   {
3139                     if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3140
3141                     PATFETCH (c1);
3142                     SET_LIST_BIT (c1);
3143                     range_start = c1;
3144                     continue;
3145                   }
3146
3147                 /* Could be the end of the bracket expression.  If it's
3148                    not (i.e., when the bracket expression is `[]' so
3149                    far), the ']' character bit gets set way below.  */
3150                 if (c == ']' && p != p1 + 1)
3151                   break;
3152
3153                 /* Look ahead to see if it's a range when the last thing
3154                    was a character class.  */
3155                 if (had_char_class && c == '-' && *p != ']')
3156                   FREE_STACK_RETURN (REG_ERANGE);
3157
3158                 /* Look ahead to see if it's a range when the last thing
3159                    was a character: if this is a hyphen not at the
3160                    beginning or the end of a list, then it's the range
3161                    operator.  */
3162                 if (c == '-'
3163                     && !(p - 2 >= pattern && p[-2] == '[')
3164                     && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
3165                     && *p != ']')
3166                   {
3167                     reg_errcode_t ret
3168                       = byte_compile_range (range_start, &p, pend, translate,
3169                                             syntax, b);
3170                     if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3171                     range_start = 0xffffffff;
3172                   }
3173
3174                 else if (p[0] == '-' && p[1] != ']')
3175                   { /* This handles ranges made up of characters only.  */
3176                     reg_errcode_t ret;
3177
3178                     /* Move past the `-'.  */
3179                     PATFETCH (c1);
3180
3181                     ret = byte_compile_range (c, &p, pend, translate, syntax, b);
3182                     if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3183                     range_start = 0xffffffff;
3184                   }
3185
3186                 /* See if we're at the beginning of a possible character
3187                    class.  */
3188
3189                 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
3190                   { /* Leave room for the null.  */
3191                     char str[CHAR_CLASS_MAX_LENGTH + 1];
3192
3193                     PATFETCH (c);
3194                     c1 = 0;
3195
3196                     /* If pattern is `[[:'.  */
3197                     if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3198
3199                     for (;;)
3200                       {
3201                         PATFETCH (c);
3202                         if ((c == ':' && *p == ']') || p == pend)
3203                           break;
3204                         if (c1 < CHAR_CLASS_MAX_LENGTH)
3205                           str[c1++] = c;
3206                         else
3207                           /* This is in any case an invalid class name.  */
3208                           str[0] = '\0';
3209                       }
3210                     str[c1] = '\0';
3211
3212                     /* If isn't a word bracketed by `[:' and `:]':
3213                        undo the ending character, the letters, and leave
3214                        the leading `:' and `[' (but set bits for them).  */
3215                     if (c == ':' && *p == ']')
3216                       {
3217 # if defined _LIBC || WIDE_CHAR_SUPPORT
3218                         boolean is_lower = STREQ (str, "lower");
3219                         boolean is_upper = STREQ (str, "upper");
3220                         wctype_t wt;
3221                         int ch;
3222
3223                         wt = IS_CHAR_CLASS (str);
3224                         if (wt == 0)
3225                           FREE_STACK_RETURN (REG_ECTYPE);
3226
3227                         /* Throw away the ] at the end of the character
3228                            class.  */
3229                         PATFETCH (c);
3230
3231                         if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3232
3233                         for (ch = 0; ch < 1 << BYTEWIDTH; ++ch)
3234                           {
3235 #  ifdef _LIBC
3236                             if (__iswctype (__btowc (ch), wt))
3237                               SET_LIST_BIT (ch);
3238 #  else
3239                             if (iswctype (btowc (ch), wt))
3240                               SET_LIST_BIT (ch);
3241 #  endif
3242
3243                             if (translate && (is_upper || is_lower)
3244                                 && (ISUPPER (ch) || ISLOWER (ch)))
3245                               SET_LIST_BIT (ch);
3246                           }
3247
3248                         had_char_class = true;
3249 # else
3250                         int ch;
3251                         boolean is_alnum = STREQ (str, "alnum");
3252                         boolean is_alpha = STREQ (str, "alpha");
3253                         boolean is_blank = STREQ (str, "blank");
3254                         boolean is_cntrl = STREQ (str, "cntrl");
3255                         boolean is_digit = STREQ (str, "digit");
3256                         boolean is_graph = STREQ (str, "graph");
3257                         boolean is_lower = STREQ (str, "lower");
3258                         boolean is_print = STREQ (str, "print");
3259                         boolean is_punct = STREQ (str, "punct");
3260                         boolean is_space = STREQ (str, "space");
3261                         boolean is_upper = STREQ (str, "upper");
3262                         boolean is_xdigit = STREQ (str, "xdigit");
3263
3264                         if (!IS_CHAR_CLASS (str))
3265                           FREE_STACK_RETURN (REG_ECTYPE);
3266
3267                         /* Throw away the ] at the end of the character
3268                            class.  */
3269                         PATFETCH (c);
3270
3271                         if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3272
3273                         for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
3274                           {
3275                             /* This was split into 3 if's to
3276                                avoid an arbitrary limit in some compiler.  */
3277                             if (   (is_alnum  && ISALNUM (ch))
3278                                 || (is_alpha  && ISALPHA (ch))
3279                                 || (is_blank  && ISBLANK (ch))
3280                                 || (is_cntrl  && ISCNTRL (ch)))
3281                               SET_LIST_BIT (ch);
3282                             if (   (is_digit  && ISDIGIT (ch))
3283                                 || (is_graph  && ISGRAPH (ch))
3284                                 || (is_lower  && ISLOWER (ch))
3285                                 || (is_print  && ISPRINT (ch)))
3286                               SET_LIST_BIT (ch);
3287                             if (   (is_punct  && ISPUNCT (ch))
3288                                 || (is_space  && ISSPACE (ch))
3289                                 || (is_upper  && ISUPPER (ch))
3290                                 || (is_xdigit && ISXDIGIT (ch)))
3291                               SET_LIST_BIT (ch);
3292                             if (   translate && (is_upper || is_lower)
3293                                 && (ISUPPER (ch) || ISLOWER (ch)))
3294                               SET_LIST_BIT (ch);
3295                           }
3296                         had_char_class = true;
3297 # endif /* libc || wctype.h */
3298                       }
3299                     else
3300                       {
3301                         c1++;
3302                         while (c1--)
3303                           PATUNFETCH;
3304                         SET_LIST_BIT ('[');
3305                         SET_LIST_BIT (':');
3306                         range_start = ':';
3307                         had_char_class = false;
3308                       }
3309                   }
3310                 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '=')
3311                   {
3312                     unsigned char str[MB_LEN_MAX + 1];
3313 # ifdef _LIBC
3314                     uint32_t nrules =
3315                       _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3316 # endif
3317
3318                     PATFETCH (c);
3319                     c1 = 0;
3320
3321                     /* If pattern is `[[='.  */
3322                     if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3323
3324                     for (;;)
3325                       {
3326                         PATFETCH (c);
3327                         if ((c == '=' && *p == ']') || p == pend)
3328                           break;
3329                         if (c1 < MB_LEN_MAX)
3330                           str[c1++] = c;
3331                         else
3332                           /* This is in any case an invalid class name.  */
3333                           str[0] = '\0';
3334                       }
3335                     str[c1] = '\0';
3336
3337                     if (c == '=' && *p == ']' && str[0] != '\0')
3338                       {
3339                         /* If we have no collation data we use the default
3340                            collation in which each character is in a class
3341                            by itself.  It also means that ASCII is the
3342                            character set and therefore we cannot have character
3343                            with more than one byte in the multibyte
3344                            representation.  */
3345 # ifdef _LIBC
3346                         if (nrules == 0)
3347 # endif
3348                           {
3349                             if (c1 != 1)
3350                               FREE_STACK_RETURN (REG_ECOLLATE);
3351
3352                             /* Throw away the ] at the end of the equivalence
3353                                class.  */
3354                             PATFETCH (c);
3355
3356                             /* Set the bit for the character.  */
3357                             SET_LIST_BIT (str[0]);
3358                           }
3359 # ifdef _LIBC
3360                         else
3361                           {
3362                             /* Try to match the byte sequence in `str' against
3363                                those known to the collate implementation.
3364                                First find out whether the bytes in `str' are
3365                                actually from exactly one character.  */
3366                             const int32_t *table;
3367                             const unsigned char *weights;
3368                             const unsigned char *extra;
3369                             const int32_t *indirect;
3370                             int32_t idx;
3371                             const unsigned char *cp = str;
3372                             int ch;
3373
3374                             /* This #include defines a local function!  */
3375 #  include <locale/weight.h>
3376
3377                             table = (const int32_t *)
3378                               _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
3379                             weights = (const unsigned char *)
3380                               _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB);
3381                             extra = (const unsigned char *)
3382                               _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
3383                             indirect = (const int32_t *)
3384                               _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
3385
3386                             idx = findidx (&cp);
3387                             if (idx == 0 || cp < str + c1)
3388                               /* This is no valid character.  */
3389                               FREE_STACK_RETURN (REG_ECOLLATE);
3390
3391                             /* Throw away the ] at the end of the equivalence
3392                                class.  */
3393                             PATFETCH (c);
3394
3395                             /* Now we have to go throught the whole table
3396                                and find all characters which have the same
3397                                first level weight.
3398
3399                                XXX Note that this is not entirely correct.
3400                                we would have to match multibyte sequences
3401                                but this is not possible with the current
3402                                implementation.  */
3403                             for (ch = 1; ch < 256; ++ch)
3404                               /* XXX This test would have to be changed if we
3405                                  would allow matching multibyte sequences.  */
3406                               if (table[ch] > 0)
3407                                 {
3408                                   int32_t idx2 = table[ch];
3409                                   size_t len = weights[idx2];
3410
3411                                   /* Test whether the lenghts match.  */
3412                                   if (weights[idx] == len)
3413                                     {
3414                                       /* They do.  New compare the bytes of
3415                                          the weight.  */
3416                                       size_t cnt = 0;
3417
3418                                       while (cnt < len
3419                                              && (weights[idx + 1 + cnt]
3420                                                  == weights[idx2 + 1 + cnt]))
3421                                         ++cnt;
3422
3423                                       if (cnt == len)
3424                                         /* They match.  Mark the character as
3425                                            acceptable.  */
3426                                         SET_LIST_BIT (ch);
3427                                     }
3428                                 }
3429                           }
3430 # endif
3431                         had_char_class = true;
3432                       }
3433                     else
3434                       {
3435                         c1++;
3436                         while (c1--)
3437                           PATUNFETCH;
3438                         SET_LIST_BIT ('[');
3439                         SET_LIST_BIT ('=');
3440                         range_start = '=';
3441                         had_char_class = false;
3442                       }
3443                   }
3444                 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '.')
3445                   {
3446                     unsigned char str[128];     /* Should be large enough.  */
3447 # ifdef _LIBC
3448                     uint32_t nrules =
3449                       _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3450 # endif
3451
3452                     PATFETCH (c);
3453                     c1 = 0;
3454
3455                     /* If pattern is `[[.'.  */
3456                     if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3457
3458                     for (;;)
3459                       {
3460                         PATFETCH (c);
3461                         if ((c == '.' && *p == ']') || p == pend)
3462                           break;
3463                         if (c1 < sizeof (str))
3464                           str[c1++] = c;
3465                         else
3466                           /* This is in any case an invalid class name.  */
3467                           str[0] = '\0';
3468                       }
3469                     str[c1] = '\0';
3470
3471                     if (c == '.' && *p == ']' && str[0] != '\0')
3472                       {
3473                         /* If we have no collation data we use the default
3474                            collation in which each character is the name
3475                            for its own class which contains only the one
3476                            character.  It also means that ASCII is the
3477                            character set and therefore we cannot have character
3478                            with more than one byte in the multibyte
3479                            representation.  */
3480 # ifdef _LIBC
3481                         if (nrules == 0)
3482 # endif
3483                           {
3484                             if (c1 != 1)
3485                               FREE_STACK_RETURN (REG_ECOLLATE);
3486
3487                             /* Throw away the ] at the end of the equivalence
3488                                class.  */
3489                             PATFETCH (c);
3490
3491                             /* Set the bit for the character.  */
3492                             SET_LIST_BIT (str[0]);
3493                             range_start = ((const unsigned char *) str)[0];
3494                           }
3495 # ifdef _LIBC
3496                         else
3497                           {
3498                             /* Try to match the byte sequence in `str' against
3499                                those known to the collate implementation.
3500                                First find out whether the bytes in `str' are
3501                                actually from exactly one character.  */
3502                             int32_t table_size;
3503                             const int32_t *symb_table;
3504                             const unsigned char *extra;
3505                             int32_t idx;
3506                             int32_t elem;
3507                             int32_t second;
3508                             int32_t hash;
3509
3510                             table_size =
3511                               _NL_CURRENT_WORD (LC_COLLATE,
3512                                                 _NL_COLLATE_SYMB_HASH_SIZEMB);
3513                             symb_table = (const int32_t *)
3514                               _NL_CURRENT (LC_COLLATE,
3515                                            _NL_COLLATE_SYMB_TABLEMB);
3516                             extra = (const unsigned char *)
3517                               _NL_CURRENT (LC_COLLATE,
3518                                            _NL_COLLATE_SYMB_EXTRAMB);
3519
3520                             /* Locate the character in the hashing table.  */
3521                             hash = elem_hash (str, c1);
3522
3523                             idx = 0;
3524                             elem = hash % table_size;
3525                             second = hash % (table_size - 2);
3526                             while (symb_table[2 * elem] != 0)
3527                               {
3528                                 /* First compare the hashing value.  */
3529                                 if (symb_table[2 * elem] == hash
3530                                     && c1 == extra[symb_table[2 * elem + 1]]
3531                                     && memcmp (str,
3532                                                &extra[symb_table[2 * elem + 1]
3533                                                      + 1],
3534                                                c1) == 0)
3535                                   {
3536                                     /* Yep, this is the entry.  */
3537                                     idx = symb_table[2 * elem + 1];
3538                                     idx += 1 + extra[idx];
3539                                     break;
3540                                   }
3541
3542                                 /* Next entry.  */
3543                                 elem += second;
3544                               }
3545
3546                             if (symb_table[2 * elem] == 0)
3547                               /* This is no valid character.  */
3548                               FREE_STACK_RETURN (REG_ECOLLATE);
3549
3550                             /* Throw away the ] at the end of the equivalence
3551                                class.  */
3552                             PATFETCH (c);
3553
3554                             /* Now add the multibyte character(s) we found
3555                                to the accept list.
3556
3557                                XXX Note that this is not entirely correct.
3558                                we would have to match multibyte sequences
3559                                but this is not possible with the current
3560                                implementation.  Also, we have to match
3561                                collating symbols, which expand to more than
3562                                one file, as a whole and not allow the
3563                                individual bytes.  */
3564                             c1 = extra[idx++];
3565                             if (c1 == 1)
3566                               range_start = extra[idx];
3567                             while (c1-- > 0)
3568                               {
3569                                 SET_LIST_BIT (extra[idx]);
3570                                 ++idx;
3571                               }
3572                           }
3573 # endif
3574                         had_char_class = false;
3575                       }
3576                     else
3577                       {
3578                         c1++;
3579                         while (c1--)
3580                           PATUNFETCH;
3581                         SET_LIST_BIT ('[');
3582                         SET_LIST_BIT ('.');
3583                         range_start = '.';
3584                         had_char_class = false;
3585                       }
3586                   }
3587                 else
3588                   {
3589                     had_char_class = false;
3590                     SET_LIST_BIT (c);
3591                     range_start = c;
3592                   }
3593               }
3594
3595             /* Discard any (non)matching list bytes that are all 0 at the
3596                end of the map.  Decrease the map-length byte too.  */
3597             while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
3598               b[-1]--;
3599             b += b[-1];
3600 #endif /* WCHAR */
3601           }
3602           break;
3603
3604
3605         case '(':
3606           if (syntax & RE_NO_BK_PARENS)
3607             goto handle_open;
3608           else
3609             goto normal_char;
3610
3611
3612         case ')':
3613           if (syntax & RE_NO_BK_PARENS)
3614             goto handle_close;
3615           else
3616             goto normal_char;
3617
3618
3619         case '\n':
3620           if (syntax & RE_NEWLINE_ALT)
3621             goto handle_alt;
3622           else
3623             goto normal_char;
3624
3625
3626         case '|':
3627           if (syntax & RE_NO_BK_VBAR)
3628             goto handle_alt;
3629           else
3630             goto normal_char;
3631
3632
3633         case '{':
3634            if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3635              goto handle_interval;
3636            else
3637              goto normal_char;
3638
3639
3640         case '\\':
3641           if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3642
3643           /* Do not translate the character after the \, so that we can
3644              distinguish, e.g., \B from \b, even if we normally would
3645              translate, e.g., B to b.  */
3646           PATFETCH_RAW (c);
3647
3648           switch (c)
3649             {
3650             case '(':
3651               if (syntax & RE_NO_BK_PARENS)
3652                 goto normal_backslash;
3653
3654             handle_open:
3655               bufp->re_nsub++;
3656               regnum++;
3657
3658               if (COMPILE_STACK_FULL)
3659                 {
3660                   RETALLOC (compile_stack.stack, compile_stack.size << 1,
3661                             compile_stack_elt_t);
3662                   if (compile_stack.stack == NULL) return REG_ESPACE;
3663
3664                   compile_stack.size <<= 1;
3665                 }
3666
3667               /* These are the values to restore when we hit end of this
3668                  group.  They are all relative offsets, so that if the
3669                  whole pattern moves because of realloc, they will still
3670                  be valid.  */
3671               COMPILE_STACK_TOP.begalt_offset = begalt - COMPILED_BUFFER_VAR;
3672               COMPILE_STACK_TOP.fixup_alt_jump
3673                 = fixup_alt_jump ? fixup_alt_jump - COMPILED_BUFFER_VAR + 1 : 0;
3674               COMPILE_STACK_TOP.laststart_offset = b - COMPILED_BUFFER_VAR;
3675               COMPILE_STACK_TOP.regnum = regnum;
3676
3677               /* We will eventually replace the 0 with the number of
3678                  groups inner to this one.  But do not push a
3679                  start_memory for groups beyond the last one we can
3680                  represent in the compiled pattern.  */
3681               if (regnum <= MAX_REGNUM)
3682                 {
3683                   COMPILE_STACK_TOP.inner_group_offset = b
3684                     - COMPILED_BUFFER_VAR + 2;
3685                   BUF_PUSH_3 (start_memory, regnum, 0);
3686                 }
3687
3688               compile_stack.avail++;
3689
3690               fixup_alt_jump = 0;
3691               laststart = 0;
3692               begalt = b;
3693               /* If we've reached MAX_REGNUM groups, then this open
3694                  won't actually generate any code, so we'll have to
3695                  clear pending_exact explicitly.  */
3696               pending_exact = 0;
3697               break;
3698
3699
3700             case ')':
3701               if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3702
3703               if (COMPILE_STACK_EMPTY)
3704                 {
3705                   if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3706                     goto normal_backslash;
3707                   else
3708                     FREE_STACK_RETURN (REG_ERPAREN);
3709                 }
3710
3711             handle_close:
3712               if (fixup_alt_jump)
3713                 { /* Push a dummy failure point at the end of the
3714                      alternative for a possible future
3715                      `pop_failure_jump' to pop.  See comments at
3716                      `push_dummy_failure' in `re_match_2'.  */
3717                   BUF_PUSH (push_dummy_failure);
3718
3719                   /* We allocated space for this jump when we assigned
3720                      to `fixup_alt_jump', in the `handle_alt' case below.  */
3721                   STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
3722                 }
3723
3724               /* See similar code for backslashed left paren above.  */
3725               if (COMPILE_STACK_EMPTY)
3726                 {
3727                   if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3728                     goto normal_char;
3729                   else
3730                     FREE_STACK_RETURN (REG_ERPAREN);
3731                 }
3732
3733               /* Since we just checked for an empty stack above, this
3734                  ``can't happen''.  */
3735               assert (compile_stack.avail != 0);
3736               {
3737                 /* We don't just want to restore into `regnum', because
3738                    later groups should continue to be numbered higher,
3739                    as in `(ab)c(de)' -- the second group is #2.  */
3740                 regnum_t this_group_regnum;
3741
3742                 compile_stack.avail--;
3743                 begalt = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.begalt_offset;
3744                 fixup_alt_jump
3745                   = COMPILE_STACK_TOP.fixup_alt_jump
3746                     ? COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.fixup_alt_jump - 1
3747                     : 0;
3748                 laststart = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.laststart_offset;
3749                 this_group_regnum = COMPILE_STACK_TOP.regnum;
3750                 /* If we've reached MAX_REGNUM groups, then this open
3751                    won't actually generate any code, so we'll have to
3752                    clear pending_exact explicitly.  */
3753                 pending_exact = 0;
3754
3755                 /* We're at the end of the group, so now we know how many
3756                    groups were inside this one.  */
3757                 if (this_group_regnum <= MAX_REGNUM)
3758                   {
3759                     UCHAR_T *inner_group_loc
3760                       = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.inner_group_offset;
3761
3762                     *inner_group_loc = regnum - this_group_regnum;
3763                     BUF_PUSH_3 (stop_memory, this_group_regnum,
3764                                 regnum - this_group_regnum);
3765                   }
3766               }
3767               break;
3768
3769
3770             case '|':                                   /* `\|'.  */
3771               if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3772                 goto normal_backslash;
3773             handle_alt:
3774               if (syntax & RE_LIMITED_OPS)
3775                 goto normal_char;
3776
3777               /* Insert before the previous alternative a jump which
3778                  jumps to this alternative if the former fails.  */
3779               GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3780               INSERT_JUMP (on_failure_jump, begalt,
3781                            b + 2 + 2 * OFFSET_ADDRESS_SIZE);
3782               pending_exact = 0;
3783               b += 1 + OFFSET_ADDRESS_SIZE;
3784
3785               /* The alternative before this one has a jump after it
3786                  which gets executed if it gets matched.  Adjust that
3787                  jump so it will jump to this alternative's analogous
3788                  jump (put in below, which in turn will jump to the next
3789                  (if any) alternative's such jump, etc.).  The last such
3790                  jump jumps to the correct final destination.  A picture:
3791                           _____ _____
3792                           |   | |   |
3793                           |   v |   v
3794                          a | b   | c
3795
3796                  If we are at `b', then fixup_alt_jump right now points to a
3797                  three-byte space after `a'.  We'll put in the jump, set
3798                  fixup_alt_jump to right after `b', and leave behind three
3799                  bytes which we'll fill in when we get to after `c'.  */
3800
3801               if (fixup_alt_jump)
3802                 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
3803
3804               /* Mark and leave space for a jump after this alternative,
3805                  to be filled in later either by next alternative or
3806                  when know we're at the end of a series of alternatives.  */
3807               fixup_alt_jump = b;
3808               GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3809               b += 1 + OFFSET_ADDRESS_SIZE;
3810
3811               laststart = 0;
3812               begalt = b;
3813               break;
3814
3815
3816             case '{':
3817               /* If \{ is a literal.  */
3818               if (!(syntax & RE_INTERVALS)
3819                      /* If we're at `\{' and it's not the open-interval
3820                         operator.  */
3821                   || (syntax & RE_NO_BK_BRACES))
3822                 goto normal_backslash;
3823
3824             handle_interval:
3825               {
3826                 /* If got here, then the syntax allows intervals.  */
3827
3828                 /* At least (most) this many matches must be made.  */
3829                 int lower_bound = -1, upper_bound = -1;
3830
3831                 /* Place in the uncompiled pattern (i.e., just after
3832                    the '{') to go back to if the interval is invalid.  */
3833                 const CHAR_T *beg_interval = p;
3834
3835                 if (p == pend)
3836                   goto invalid_interval;
3837
3838                 GET_UNSIGNED_NUMBER (lower_bound);
3839
3840                 if (c == ',')
3841                   {
3842                     GET_UNSIGNED_NUMBER (upper_bound);
3843                     if (upper_bound < 0)
3844                       upper_bound = RE_DUP_MAX;
3845                   }
3846                 else
3847                   /* Interval such as `{1}' => match exactly once. */
3848                   upper_bound = lower_bound;
3849
3850                 if (! (0 <= lower_bound && lower_bound <= upper_bound))
3851                   goto invalid_interval;
3852
3853                 if (!(syntax & RE_NO_BK_BRACES))
3854                   {
3855                     if (c != '\\' || p == pend)
3856                       goto invalid_interval;
3857                     PATFETCH (c);
3858                   }
3859
3860                 if (c != '}')
3861                   goto invalid_interval;
3862
3863                 /* If it's invalid to have no preceding re.  */
3864                 if (!laststart)
3865                   {
3866                     if (syntax & RE_CONTEXT_INVALID_OPS
3867                         && !(syntax & RE_INVALID_INTERVAL_ORD))
3868                       FREE_STACK_RETURN (REG_BADRPT);
3869                     else if (syntax & RE_CONTEXT_INDEP_OPS)
3870                       laststart = b;
3871                     else
3872                       goto unfetch_interval;
3873                   }
3874
3875                 /* We just parsed a valid interval.  */
3876
3877                 if (RE_DUP_MAX < upper_bound)
3878                   FREE_STACK_RETURN (REG_BADBR);
3879
3880                 /* If the upper bound is zero, don't want to succeed at
3881                    all; jump from `laststart' to `b + 3', which will be
3882                    the end of the buffer after we insert the jump.  */
3883                 /* ifdef WCHAR, 'b + 1 + OFFSET_ADDRESS_SIZE'
3884                    instead of 'b + 3'.  */
3885                  if (upper_bound == 0)
3886                    {
3887                      GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3888                      INSERT_JUMP (jump, laststart, b + 1
3889                                   + OFFSET_ADDRESS_SIZE);
3890                      b += 1 + OFFSET_ADDRESS_SIZE;
3891                    }
3892
3893                  /* Otherwise, we have a nontrivial interval.  When
3894                     we're all done, the pattern will look like:
3895                       set_number_at <jump count> <upper bound>
3896                       set_number_at <succeed_n count> <lower bound>
3897                       succeed_n <after jump addr> <succeed_n count>
3898                       <body of loop>
3899                       jump_n <succeed_n addr> <jump count>
3900                     (The upper bound and `jump_n' are omitted if
3901                     `upper_bound' is 1, though.)  */
3902                  else
3903                    { /* If the upper bound is > 1, we need to insert
3904                         more at the end of the loop.  */
3905                      unsigned nbytes = 2 + 4 * OFFSET_ADDRESS_SIZE +
3906                        (upper_bound > 1) * (2 + 4 * OFFSET_ADDRESS_SIZE);
3907
3908                      GET_BUFFER_SPACE (nbytes);
3909
3910                      /* Initialize lower bound of the `succeed_n', even
3911                         though it will be set during matching by its
3912                         attendant `set_number_at' (inserted next),
3913                         because `re_compile_fastmap' needs to know.
3914                         Jump to the `jump_n' we might insert below.  */
3915                      INSERT_JUMP2 (succeed_n, laststart,
3916                                    b + 1 + 2 * OFFSET_ADDRESS_SIZE
3917                                    + (upper_bound > 1) * (1 + 2 * OFFSET_ADDRESS_SIZE)
3918                                    , lower_bound);
3919                      b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3920
3921                      /* Code to initialize the lower bound.  Insert
3922                         before the `succeed_n'.  The `5' is the last two
3923                         bytes of this `set_number_at', plus 3 bytes of
3924                         the following `succeed_n'.  */
3925                      /* ifdef WCHAR, The '1+2*OFFSET_ADDRESS_SIZE'
3926                         is the 'set_number_at', plus '1+OFFSET_ADDRESS_SIZE'
3927                         of the following `succeed_n'.  */
3928                      PREFIX(insert_op2) (set_number_at, laststart, 1
3929                                  + 2 * OFFSET_ADDRESS_SIZE, lower_bound, b);
3930                      b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3931
3932                      if (upper_bound > 1)
3933                        { /* More than one repetition is allowed, so
3934                             append a backward jump to the `succeed_n'
3935                             that starts this interval.
3936
3937                             When we've reached this during matching,
3938                             we'll have matched the interval once, so
3939                             jump back only `upper_bound - 1' times.  */
3940                          STORE_JUMP2 (jump_n, b, laststart
3941                                       + 2 * OFFSET_ADDRESS_SIZE + 1,
3942                                       upper_bound - 1);
3943                          b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3944
3945                          /* The location we want to set is the second
3946                             parameter of the `jump_n'; that is `b-2' as
3947                             an absolute address.  `laststart' will be
3948                             the `set_number_at' we're about to insert;
3949                             `laststart+3' the number to set, the source
3950                             for the relative address.  But we are
3951                             inserting into the middle of the pattern --
3952                             so everything is getting moved up by 5.
3953                             Conclusion: (b - 2) - (laststart + 3) + 5,
3954                             i.e., b - laststart.
3955
3956                             We insert this at the beginning of the loop
3957                             so that if we fail during matching, we'll
3958                             reinitialize the bounds.  */
3959                          PREFIX(insert_op2) (set_number_at, laststart,
3960                                              b - laststart,
3961                                              upper_bound - 1, b);
3962                          b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3963                        }
3964                    }
3965                 pending_exact = 0;
3966                 break;
3967
3968               invalid_interval:
3969                 if (!(syntax & RE_INVALID_INTERVAL_ORD))
3970                   FREE_STACK_RETURN (p == pend ? REG_EBRACE : REG_BADBR);
3971               unfetch_interval:
3972                 /* Match the characters as literals.  */
3973                 p = beg_interval;
3974                 c = '{';
3975                 if (syntax & RE_NO_BK_BRACES)
3976                   goto normal_char;
3977                 else
3978                   goto normal_backslash;
3979               }
3980
3981 #ifdef emacs
3982             /* There is no way to specify the before_dot and after_dot
3983                operators.  rms says this is ok.  --karl  */
3984             case '=':
3985               BUF_PUSH (at_dot);
3986               break;
3987
3988             case 's':
3989               laststart = b;
3990               PATFETCH (c);
3991               BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
3992               break;
3993
3994             case 'S':
3995               laststart = b;
3996               PATFETCH (c);
3997               BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
3998               break;
3999 #endif /* emacs */
4000
4001
4002             case 'w':
4003               if (syntax & RE_NO_GNU_OPS)
4004                 goto normal_char;
4005               laststart = b;
4006               BUF_PUSH (wordchar);
4007               break;
4008
4009
4010             case 'W':
4011               if (syntax & RE_NO_GNU_OPS)
4012                 goto normal_char;
4013               laststart = b;
4014               BUF_PUSH (notwordchar);
4015               break;
4016
4017
4018             case '<':
4019               if (syntax & RE_NO_GNU_OPS)
4020                 goto normal_char;
4021               BUF_PUSH (wordbeg);
4022               break;
4023
4024             case '>':
4025               if (syntax & RE_NO_GNU_OPS)
4026                 goto normal_char;
4027               BUF_PUSH (wordend);
4028               break;
4029
4030             case 'b':
4031               if (syntax & RE_NO_GNU_OPS)
4032                 goto normal_char;
4033               BUF_PUSH (wordbound);
4034               break;
4035
4036             case 'B':
4037               if (syntax & RE_NO_GNU_OPS)
4038                 goto normal_char;
4039               BUF_PUSH (notwordbound);
4040               break;
4041
4042             case '`':
4043               if (syntax & RE_NO_GNU_OPS)
4044                 goto normal_char;
4045               BUF_PUSH (begbuf);
4046               break;
4047
4048             case '\'':
4049               if (syntax & RE_NO_GNU_OPS)
4050                 goto normal_char;
4051               BUF_PUSH (endbuf);
4052               break;
4053
4054             case '1': case '2': case '3': case '4': case '5':
4055             case '6': case '7': case '8': case '9':
4056               if (syntax & RE_NO_BK_REFS)
4057                 goto normal_char;
4058
4059               c1 = c - '0';
4060
4061               if (c1 > regnum)
4062                 FREE_STACK_RETURN (REG_ESUBREG);
4063
4064               /* Can't back reference to a subexpression if inside of it.  */
4065               if (group_in_compile_stack (compile_stack, (regnum_t) c1))
4066                 goto normal_char;
4067
4068               laststart = b;
4069               BUF_PUSH_2 (duplicate, c1);
4070               break;
4071
4072
4073             case '+':
4074             case '?':
4075               if (syntax & RE_BK_PLUS_QM)
4076                 goto handle_plus;
4077               else
4078                 goto normal_backslash;
4079
4080             default:
4081             normal_backslash:
4082               /* You might think it would be useful for \ to mean
4083                  not to translate; but if we don't translate it
4084                  it will never match anything.  */
4085               c = TRANSLATE (c);
4086               goto normal_char;
4087             }
4088           break;
4089
4090
4091         default:
4092         /* Expects the character in `c'.  */
4093         normal_char:
4094               /* If no exactn currently being built.  */
4095           if (!pending_exact
4096 #ifdef WCHAR
4097               /* If last exactn handle binary(or character) and
4098                  new exactn handle character(or binary).  */
4099               || is_exactn_bin != is_binary[p - 1 - pattern]
4100 #endif /* WCHAR */
4101
4102               /* If last exactn not at current position.  */
4103               || pending_exact + *pending_exact + 1 != b
4104
4105               /* We have only one byte following the exactn for the count.  */
4106               || *pending_exact == (1 << BYTEWIDTH) - 1
4107
4108               /* If followed by a repetition operator.  */
4109               || *p == '*' || *p == '^'
4110               || ((syntax & RE_BK_PLUS_QM)
4111                   ? *p == '\\' && (p[1] == '+' || p[1] == '?')
4112                   : (*p == '+' || *p == '?'))
4113               || ((syntax & RE_INTERVALS)
4114                   && ((syntax & RE_NO_BK_BRACES)
4115                       ? *p == '{'
4116                       : (p[0] == '\\' && p[1] == '{'))))
4117             {
4118               /* Start building a new exactn.  */
4119
4120               laststart = b;
4121
4122 #ifdef WCHAR
4123               /* Is this exactn binary data or character? */
4124               is_exactn_bin = is_binary[p - 1 - pattern];
4125               if (is_exactn_bin)
4126                   BUF_PUSH_2 (exactn_bin, 0);
4127               else
4128                   BUF_PUSH_2 (exactn, 0);
4129 #else
4130               BUF_PUSH_2 (exactn, 0);
4131 #endif /* WCHAR */
4132               pending_exact = b - 1;
4133             }
4134
4135           BUF_PUSH (c);
4136           (*pending_exact)++;
4137           break;
4138         } /* switch (c) */
4139     } /* while p != pend */
4140
4141
4142   /* Through the pattern now.  */
4143
4144   if (fixup_alt_jump)
4145     STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
4146
4147   if (!COMPILE_STACK_EMPTY)
4148     FREE_STACK_RETURN (REG_EPAREN);
4149
4150   /* If we don't want backtracking, force success
4151      the first time we reach the end of the compiled pattern.  */
4152   if (syntax & RE_NO_POSIX_BACKTRACKING)
4153     BUF_PUSH (succeed);
4154
4155 #ifdef WCHAR
4156   free (pattern);
4157   free (mbs_offset);
4158   free (is_binary);
4159 #endif
4160   free (compile_stack.stack);
4161
4162   /* We have succeeded; set the length of the buffer.  */
4163 #ifdef WCHAR
4164   bufp->used = (uintptr_t) b - (uintptr_t) COMPILED_BUFFER_VAR;
4165 #else
4166   bufp->used = b - bufp->buffer;
4167 #endif
4168
4169 #ifdef DEBUG
4170   if (debug)
4171     {
4172       DEBUG_PRINT1 ("\nCompiled pattern: \n");
4173       PREFIX(print_compiled_pattern) (bufp);
4174     }
4175 #endif /* DEBUG */
4176
4177 #ifndef MATCH_MAY_ALLOCATE
4178   /* Initialize the failure stack to the largest possible stack.  This
4179      isn't necessary unless we're trying to avoid calling alloca in
4180      the search and match routines.  */
4181   {
4182     int num_regs = bufp->re_nsub + 1;
4183
4184     /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
4185        is strictly greater than re_max_failures, the largest possible stack
4186        is 2 * re_max_failures failure points.  */
4187     if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
4188       {
4189         fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
4190
4191 # ifdef emacs
4192         if (! fail_stack.stack)
4193           fail_stack.stack
4194             = (PREFIX(fail_stack_elt_t) *) xmalloc (fail_stack.size
4195                                     * sizeof (PREFIX(fail_stack_elt_t)));
4196         else
4197           fail_stack.stack
4198             = (PREFIX(fail_stack_elt_t) *) xrealloc (fail_stack.stack,
4199                                      (fail_stack.size
4200                                       * sizeof (PREFIX(fail_stack_elt_t))));
4201 # else /* not emacs */
4202         if (! fail_stack.stack)
4203           fail_stack.stack
4204             = (PREFIX(fail_stack_elt_t) *) malloc (fail_stack.size
4205                                    * sizeof (PREFIX(fail_stack_elt_t)));
4206         else
4207           fail_stack.stack
4208             = (PREFIX(fail_stack_elt_t) *) realloc (fail_stack.stack,
4209                                             (fail_stack.size
4210                                      * sizeof (PREFIX(fail_stack_elt_t))));
4211 # endif /* not emacs */
4212       }
4213
4214    PREFIX(regex_grow_registers) (num_regs);
4215   }
4216 #endif /* not MATCH_MAY_ALLOCATE */
4217
4218   return REG_NOERROR;
4219 } /* regex_compile */
4220
4221 /* Subroutines for `regex_compile'.  */
4222
4223 /* Store OP at LOC followed by two-byte integer parameter ARG.  */
4224 /* ifdef WCHAR, integer parameter is 1 wchar_t.  */
4225
4226 static void
4227 PREFIX(store_op1) (re_opcode_t op, UCHAR_T *loc, int arg)
4228 {
4229   *loc = (UCHAR_T) op;
4230   STORE_NUMBER (loc + 1, arg);
4231 }
4232
4233
4234 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2.  */
4235 /* ifdef WCHAR, integer parameter is 1 wchar_t.  */
4236
4237 static void
4238 PREFIX(store_op2) (re_opcode_t op, UCHAR_T *loc, int arg1, int arg2)
4239 {
4240   *loc = (UCHAR_T) op;
4241   STORE_NUMBER (loc + 1, arg1);
4242   STORE_NUMBER (loc + 1 + OFFSET_ADDRESS_SIZE, arg2);
4243 }
4244
4245
4246 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
4247    for OP followed by two-byte integer parameter ARG.  */
4248 /* ifdef WCHAR, integer parameter is 1 wchar_t.  */
4249
4250 static void
4251 PREFIX(insert_op1) (re_opcode_t op, UCHAR_T *loc, int arg, UCHAR_T *end)
4252 {
4253   register UCHAR_T *pfrom = end;
4254   register UCHAR_T *pto = end + 1 + OFFSET_ADDRESS_SIZE;
4255
4256   while (pfrom != loc)
4257     *--pto = *--pfrom;
4258
4259   PREFIX(store_op1) (op, loc, arg);
4260 }
4261
4262
4263 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2.  */
4264 /* ifdef WCHAR, integer parameter is 1 wchar_t.  */
4265
4266 static void
4267 PREFIX(insert_op2) (re_opcode_t op, UCHAR_T *loc, int arg1,
4268                     int arg2, UCHAR_T *end)
4269 {
4270   register UCHAR_T *pfrom = end;
4271   register UCHAR_T *pto = end + 1 + 2 * OFFSET_ADDRESS_SIZE;
4272
4273   while (pfrom != loc)
4274     *--pto = *--pfrom;
4275
4276   PREFIX(store_op2) (op, loc, arg1, arg2);
4277 }
4278
4279
4280 /* P points to just after a ^ in PATTERN.  Return true if that ^ comes
4281    after an alternative or a begin-subexpression.  We assume there is at
4282    least one character before the ^.  */
4283
4284 static boolean
4285 PREFIX(at_begline_loc_p) (const CHAR_T *pattern, const CHAR_T *p,
4286                           reg_syntax_t syntax)
4287 {
4288   const CHAR_T *prev = p - 2;
4289   boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
4290
4291   return
4292        /* After a subexpression?  */
4293        (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
4294        /* After an alternative?  */
4295     || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
4296 }
4297
4298
4299 /* The dual of at_begline_loc_p.  This one is for $.  We assume there is
4300    at least one character after the $, i.e., `P < PEND'.  */
4301
4302 static boolean
4303 PREFIX(at_endline_loc_p) (const CHAR_T *p, const CHAR_T *pend,
4304                           reg_syntax_t syntax)
4305 {
4306   const CHAR_T *next = p;
4307   boolean next_backslash = *next == '\\';
4308   const CHAR_T *next_next = p + 1 < pend ? p + 1 : 0;
4309
4310   return
4311        /* Before a subexpression?  */
4312        (syntax & RE_NO_BK_PARENS ? *next == ')'
4313         : next_backslash && next_next && *next_next == ')')
4314        /* Before an alternative?  */
4315     || (syntax & RE_NO_BK_VBAR ? *next == '|'
4316         : next_backslash && next_next && *next_next == '|');
4317 }
4318
4319 #else /* not INSIDE_RECURSION */
4320
4321 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
4322    false if it's not.  */
4323
4324 static boolean
4325 group_in_compile_stack (compile_stack_type compile_stack, regnum_t regnum)
4326 {
4327   int this_element;
4328
4329   for (this_element = compile_stack.avail - 1;
4330        this_element >= 0;
4331        this_element--)
4332     if (compile_stack.stack[this_element].regnum == regnum)
4333       return true;
4334
4335   return false;
4336 }
4337 #endif /* not INSIDE_RECURSION */
4338
4339 #ifdef INSIDE_RECURSION
4340
4341 #ifdef WCHAR
4342 /* This insert space, which size is "num", into the pattern at "loc".
4343    "end" must point the end of the allocated buffer.  */
4344 static void
4345 insert_space (int num, CHAR_T *loc, CHAR_T *end)
4346 {
4347   register CHAR_T *pto = end;
4348   register CHAR_T *pfrom = end - num;
4349
4350   while (pfrom >= loc)
4351     *pto-- = *pfrom--;
4352 }
4353 #endif /* WCHAR */
4354
4355 #ifdef WCHAR
4356 static reg_errcode_t
4357 wcs_compile_range (CHAR_T range_start_char, const CHAR_T **p_ptr,
4358                    const CHAR_T *pend, RE_TRANSLATE_TYPE translate,
4359                    reg_syntax_t syntax, CHAR_T *b, CHAR_T *char_set)
4360 {
4361   const CHAR_T *p = *p_ptr;
4362   CHAR_T range_start, range_end;
4363   reg_errcode_t ret;
4364 # ifdef _LIBC
4365   uint32_t nrules;
4366   uint32_t start_val, end_val;
4367 # endif
4368   if (p == pend)
4369     return REG_ERANGE;
4370
4371 # ifdef _LIBC
4372   nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
4373   if (nrules != 0)
4374     {
4375       const char *collseq = (const char *) _NL_CURRENT(LC_COLLATE,
4376                                                        _NL_COLLATE_COLLSEQWC);
4377       const unsigned char *extra = (const unsigned char *)
4378         _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
4379
4380       if (range_start_char < -1)
4381         {
4382           /* range_start is a collating symbol.  */
4383           int32_t *wextra;
4384           /* Retreive the index and get collation sequence value.  */
4385           wextra = (int32_t*)(extra + char_set[-range_start_char]);
4386           start_val = wextra[1 + *wextra];
4387         }
4388       else
4389         start_val = collseq_table_lookup(collseq, TRANSLATE(range_start_char));
4390
4391       end_val = collseq_table_lookup (collseq, TRANSLATE (p[0]));
4392
4393       /* Report an error if the range is empty and the syntax prohibits
4394          this.  */
4395       ret = ((syntax & RE_NO_EMPTY_RANGES)
4396              && (start_val > end_val))? REG_ERANGE : REG_NOERROR;
4397
4398       /* Insert space to the end of the char_ranges.  */
4399       insert_space(2, b - char_set[5] - 2, b - 1);
4400       *(b - char_set[5] - 2) = (wchar_t)start_val;
4401       *(b - char_set[5] - 1) = (wchar_t)end_val;
4402       char_set[4]++; /* ranges_index */
4403     }
4404   else
4405 # endif
4406     {
4407       range_start = (range_start_char >= 0)? TRANSLATE (range_start_char):
4408         range_start_char;
4409       range_end = TRANSLATE (p[0]);
4410       /* Report an error if the range is empty and the syntax prohibits
4411          this.  */
4412       ret = ((syntax & RE_NO_EMPTY_RANGES)
4413              && (range_start > range_end))? REG_ERANGE : REG_NOERROR;
4414
4415       /* Insert space to the end of the char_ranges.  */
4416       insert_space(2, b - char_set[5] - 2, b - 1);
4417       *(b - char_set[5] - 2) = range_start;
4418       *(b - char_set[5] - 1) = range_end;
4419       char_set[4]++; /* ranges_index */
4420     }
4421   /* Have to increment the pointer into the pattern string, so the
4422      caller isn't still at the ending character.  */
4423   (*p_ptr)++;
4424
4425   return ret;
4426 }
4427 #else /* BYTE */
4428 /* Read the ending character of a range (in a bracket expression) from the
4429    uncompiled pattern *P_PTR (which ends at PEND).  We assume the
4430    starting character is in `P[-2]'.  (`P[-1]' is the character `-'.)
4431    Then we set the translation of all bits between the starting and
4432    ending characters (inclusive) in the compiled pattern B.
4433
4434    Return an error code.
4435
4436    We use these short variable names so we can use the same macros as
4437    `regex_compile' itself.  */
4438
4439 static reg_errcode_t
4440 byte_compile_range (unsigned int range_start_char, const char **p_ptr,
4441                     const char *pend, RE_TRANSLATE_TYPE translate,
4442                     reg_syntax_t syntax, unsigned char *b)
4443 {
4444   unsigned this_char;
4445   const char *p = *p_ptr;
4446   reg_errcode_t ret;
4447 # if _LIBC
4448   const unsigned char *collseq;
4449   unsigned int start_colseq;
4450   unsigned int end_colseq;
4451 # else
4452   unsigned end_char;
4453 # endif
4454
4455   if (p == pend)
4456     return REG_ERANGE;
4457
4458   /* Have to increment the pointer into the pattern string, so the
4459      caller isn't still at the ending character.  */
4460   (*p_ptr)++;
4461
4462   /* Report an error if the range is empty and the syntax prohibits this.  */
4463   ret = syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
4464
4465 # if _LIBC
4466   collseq = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
4467                                                  _NL_COLLATE_COLLSEQMB);
4468
4469   start_colseq = collseq[(unsigned char) TRANSLATE (range_start_char)];
4470   end_colseq = collseq[(unsigned char) TRANSLATE (p[0])];
4471   for (this_char = 0; this_char <= (unsigned char) -1; ++this_char)
4472     {
4473       unsigned int this_colseq = collseq[(unsigned char) TRANSLATE (this_char)];
4474
4475       if (start_colseq <= this_colseq && this_colseq <= end_colseq)
4476         {
4477           SET_LIST_BIT (TRANSLATE (this_char));
4478           ret = REG_NOERROR;
4479         }
4480     }
4481 # else
4482   /* Here we see why `this_char' has to be larger than an `unsigned
4483      char' -- we would otherwise go into an infinite loop, since all
4484      characters <= 0xff.  */
4485   range_start_char = TRANSLATE (range_start_char);
4486   /* TRANSLATE(p[0]) is casted to char (not unsigned char) in TRANSLATE,
4487      and some compilers cast it to int implicitly, so following for_loop
4488      may fall to (almost) infinite loop.
4489      e.g. If translate[p[0]] = 0xff, end_char may equals to 0xffffffff.
4490      To avoid this, we cast p[0] to unsigned int and truncate it.  */
4491   end_char = ((unsigned)TRANSLATE(p[0]) & ((1 << BYTEWIDTH) - 1));
4492
4493   for (this_char = range_start_char; this_char <= end_char; ++this_char)
4494     {
4495       SET_LIST_BIT (TRANSLATE (this_char));
4496       ret = REG_NOERROR;
4497     }
4498 # endif
4499
4500   return ret;
4501 }
4502 #endif /* WCHAR */
4503 \f
4504 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4505    BUFP.  A fastmap records which of the (1 << BYTEWIDTH) possible
4506    characters can start a string that matches the pattern.  This fastmap
4507    is used by re_search to skip quickly over impossible starting points.
4508
4509    The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4510    area as BUFP->fastmap.
4511
4512    We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4513    the pattern buffer.
4514
4515    Returns 0 if we succeed, -2 if an internal error.   */
4516
4517 #ifdef WCHAR
4518 /* local function for re_compile_fastmap.
4519    truncate wchar_t character to char.  */
4520 static unsigned char truncate_wchar (CHAR_T c);
4521
4522 static unsigned char
4523 truncate_wchar (CHAR_T c)
4524 {
4525   unsigned char buf[MB_CUR_MAX];
4526   mbstate_t state;
4527   int retval;
4528   memset (&state, '\0', sizeof (state));
4529 # ifdef _LIBC
4530   retval = __wcrtomb (buf, c, &state);
4531 # else
4532   retval = wcrtomb (buf, c, &state);
4533 # endif
4534   return retval > 0 ? buf[0] : (unsigned char) c;
4535 }
4536 #endif /* WCHAR */
4537
4538 static int
4539 PREFIX(re_compile_fastmap) (struct re_pattern_buffer *bufp)
4540 {
4541   int j, k;
4542 #ifdef MATCH_MAY_ALLOCATE
4543   PREFIX(fail_stack_type) fail_stack;
4544 #endif
4545 #ifndef REGEX_MALLOC
4546   char *destination;
4547 #endif
4548
4549   register char *fastmap = bufp->fastmap;
4550
4551 #ifdef WCHAR
4552   /* We need to cast pattern to (wchar_t*), because we casted this compiled
4553      pattern to (char*) in regex_compile.  */
4554   UCHAR_T *pattern = (UCHAR_T*)bufp->buffer;
4555   register UCHAR_T *pend = (UCHAR_T*) (bufp->buffer + bufp->used);
4556 #else /* BYTE */
4557   UCHAR_T *pattern = bufp->buffer;
4558   register UCHAR_T *pend = pattern + bufp->used;
4559 #endif /* WCHAR */
4560   UCHAR_T *p = pattern;
4561
4562 #ifdef REL_ALLOC
4563   /* This holds the pointer to the failure stack, when
4564      it is allocated relocatably.  */
4565   fail_stack_elt_t *failure_stack_ptr;
4566 #endif
4567
4568   /* Assume that each path through the pattern can be null until
4569      proven otherwise.  We set this false at the bottom of switch
4570      statement, to which we get only if a particular path doesn't
4571      match the empty string.  */
4572   boolean path_can_be_null = true;
4573
4574   /* We aren't doing a `succeed_n' to begin with.  */
4575   boolean succeed_n_p = false;
4576
4577   assert (fastmap != NULL && p != NULL);
4578
4579   INIT_FAIL_STACK ();
4580   bzero (fastmap, 1 << BYTEWIDTH);  /* Assume nothing's valid.  */
4581   bufp->fastmap_accurate = 1;       /* It will be when we're done.  */
4582   bufp->can_be_null = 0;
4583
4584   while (1)
4585     {
4586       if (p == pend || *p == (UCHAR_T) succeed)
4587         {
4588           /* We have reached the (effective) end of pattern.  */
4589           if (!FAIL_STACK_EMPTY ())
4590             {
4591               bufp->can_be_null |= path_can_be_null;
4592
4593               /* Reset for next path.  */
4594               path_can_be_null = true;
4595
4596               p = fail_stack.stack[--fail_stack.avail].pointer;
4597
4598               continue;
4599             }
4600           else
4601             break;
4602         }
4603
4604       /* We should never be about to go beyond the end of the pattern.  */
4605       assert (p < pend);
4606
4607       switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4608         {
4609
4610         /* I guess the idea here is to simply not bother with a fastmap
4611            if a backreference is used, since it's too hard to figure out
4612            the fastmap for the corresponding group.  Setting
4613            `can_be_null' stops `re_search_2' from using the fastmap, so
4614            that is all we do.  */
4615         case duplicate:
4616           bufp->can_be_null = 1;
4617           goto done;
4618
4619
4620       /* Following are the cases which match a character.  These end
4621          with `break'.  */
4622
4623 #ifdef WCHAR
4624         case exactn:
4625           fastmap[truncate_wchar(p[1])] = 1;
4626           break;
4627 #else /* BYTE */
4628         case exactn:
4629           fastmap[p[1]] = 1;
4630           break;
4631 #endif /* WCHAR */
4632 #ifdef MBS_SUPPORT
4633         case exactn_bin:
4634           fastmap[p[1]] = 1;
4635           break;
4636 #endif
4637
4638 #ifdef WCHAR
4639         /* It is hard to distinguish fastmap from (multi byte) characters
4640            which depends on current locale.  */
4641         case charset:
4642         case charset_not:
4643         case wordchar:
4644         case notwordchar:
4645           bufp->can_be_null = 1;
4646           goto done;
4647 #else /* BYTE */
4648         case charset:
4649           for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4650             if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
4651               fastmap[j] = 1;
4652           break;
4653
4654
4655         case charset_not:
4656           /* Chars beyond end of map must be allowed.  */
4657           for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
4658             fastmap[j] = 1;
4659
4660           for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4661             if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
4662               fastmap[j] = 1;
4663           break;
4664
4665
4666         case wordchar:
4667           for (j = 0; j < (1 << BYTEWIDTH); j++)
4668             if (SYNTAX (j) == Sword)
4669               fastmap[j] = 1;
4670           break;
4671
4672
4673         case notwordchar:
4674           for (j = 0; j < (1 << BYTEWIDTH); j++)
4675             if (SYNTAX (j) != Sword)
4676               fastmap[j] = 1;
4677           break;
4678 #endif /* WCHAR */
4679
4680         case anychar:
4681           {
4682             int fastmap_newline = fastmap['\n'];
4683
4684             /* `.' matches anything ...  */
4685             for (j = 0; j < (1 << BYTEWIDTH); j++)
4686               fastmap[j] = 1;
4687
4688             /* ... except perhaps newline.  */
4689             if (!(bufp->syntax & RE_DOT_NEWLINE))
4690               fastmap['\n'] = fastmap_newline;
4691
4692             /* Return if we have already set `can_be_null'; if we have,
4693                then the fastmap is irrelevant.  Something's wrong here.  */
4694             else if (bufp->can_be_null)
4695               goto done;
4696
4697             /* Otherwise, have to check alternative paths.  */
4698             break;
4699           }
4700
4701 #ifdef emacs
4702         case syntaxspec:
4703           k = *p++;
4704           for (j = 0; j < (1 << BYTEWIDTH); j++)
4705             if (SYNTAX (j) == (enum syntaxcode) k)
4706               fastmap[j] = 1;
4707           break;
4708
4709
4710         case notsyntaxspec:
4711           k = *p++;
4712           for (j = 0; j < (1 << BYTEWIDTH); j++)
4713             if (SYNTAX (j) != (enum syntaxcode) k)
4714               fastmap[j] = 1;
4715           break;
4716
4717
4718       /* All cases after this match the empty string.  These end with
4719          `continue'.  */
4720
4721
4722         case before_dot:
4723         case at_dot:
4724         case after_dot:
4725           continue;
4726 #endif /* emacs */
4727
4728
4729         case no_op:
4730         case begline:
4731         case endline:
4732         case begbuf:
4733         case endbuf:
4734         case wordbound:
4735         case notwordbound:
4736         case wordbeg:
4737         case wordend:
4738         case push_dummy_failure:
4739           continue;
4740
4741
4742         case jump_n:
4743         case pop_failure_jump:
4744         case maybe_pop_jump:
4745         case jump:
4746         case jump_past_alt:
4747         case dummy_failure_jump:
4748           EXTRACT_NUMBER_AND_INCR (j, p);
4749           p += j;
4750           if (j > 0)
4751             continue;
4752
4753           /* Jump backward implies we just went through the body of a
4754              loop and matched nothing.  Opcode jumped to should be
4755              `on_failure_jump' or `succeed_n'.  Just treat it like an
4756              ordinary jump.  For a * loop, it has pushed its failure
4757              point already; if so, discard that as redundant.  */
4758           if ((re_opcode_t) *p != on_failure_jump
4759               && (re_opcode_t) *p != succeed_n)
4760             continue;
4761
4762           p++;
4763           EXTRACT_NUMBER_AND_INCR (j, p);
4764           p += j;
4765
4766           /* If what's on the stack is where we are now, pop it.  */
4767           if (!FAIL_STACK_EMPTY ()
4768               && fail_stack.stack[fail_stack.avail - 1].pointer == p)
4769             fail_stack.avail--;
4770
4771           continue;
4772
4773
4774         case on_failure_jump:
4775         case on_failure_keep_string_jump:
4776         handle_on_failure_jump:
4777           EXTRACT_NUMBER_AND_INCR (j, p);
4778
4779           /* For some patterns, e.g., `(a?)?', `p+j' here points to the
4780              end of the pattern.  We don't want to push such a point,
4781              since when we restore it above, entering the switch will
4782              increment `p' past the end of the pattern.  We don't need
4783              to push such a point since we obviously won't find any more
4784              fastmap entries beyond `pend'.  Such a pattern can match
4785              the null string, though.  */
4786           if (p + j < pend)
4787             {
4788               if (!PUSH_PATTERN_OP (p + j, fail_stack))
4789                 {
4790                   RESET_FAIL_STACK ();
4791                   return -2;
4792                 }
4793             }
4794           else
4795             bufp->can_be_null = 1;
4796
4797           if (succeed_n_p)
4798             {
4799               EXTRACT_NUMBER_AND_INCR (k, p);   /* Skip the n.  */
4800               succeed_n_p = false;
4801             }
4802
4803           continue;
4804
4805
4806         case succeed_n:
4807           /* Get to the number of times to succeed.  */
4808           p += OFFSET_ADDRESS_SIZE;
4809
4810           /* Increment p past the n for when k != 0.  */
4811           EXTRACT_NUMBER_AND_INCR (k, p);
4812           if (k == 0)
4813             {
4814               p -= 2 * OFFSET_ADDRESS_SIZE;
4815               succeed_n_p = true;  /* Spaghetti code alert.  */
4816               goto handle_on_failure_jump;
4817             }
4818           continue;
4819
4820
4821         case set_number_at:
4822           p += 2 * OFFSET_ADDRESS_SIZE;
4823           continue;
4824
4825
4826         case start_memory:
4827         case stop_memory:
4828           p += 2;
4829           continue;
4830
4831
4832         default:
4833           abort (); /* We have listed all the cases.  */
4834         } /* switch *p++ */
4835
4836       /* Getting here means we have found the possible starting
4837          characters for one path of the pattern -- and that the empty
4838          string does not match.  We need not follow this path further.
4839          Instead, look at the next alternative (remembered on the
4840          stack), or quit if no more.  The test at the top of the loop
4841          does these things.  */
4842       path_can_be_null = false;
4843       p = pend;
4844     } /* while p */
4845
4846   /* Set `can_be_null' for the last path (also the first path, if the
4847      pattern is empty).  */
4848   bufp->can_be_null |= path_can_be_null;
4849
4850  done:
4851   RESET_FAIL_STACK ();
4852   return 0;
4853 }
4854
4855 #else /* not INSIDE_RECURSION */
4856
4857 int
4858 re_compile_fastmap (struct re_pattern_buffer *bufp)
4859 {
4860 # ifdef MBS_SUPPORT
4861   if (MB_CUR_MAX != 1)
4862     return wcs_re_compile_fastmap(bufp);
4863   else
4864 # endif
4865     return byte_re_compile_fastmap(bufp);
4866 } /* re_compile_fastmap */
4867 #ifdef _LIBC
4868 weak_alias (__re_compile_fastmap, re_compile_fastmap)
4869 #endif
4870 \f
4871
4872 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4873    ENDS.  Subsequent matches using PATTERN_BUFFER and REGS will use
4874    this memory for recording register information.  STARTS and ENDS
4875    must be allocated using the malloc library routine, and must each
4876    be at least NUM_REGS * sizeof (regoff_t) bytes long.
4877
4878    If NUM_REGS == 0, then subsequent matches should allocate their own
4879    register data.
4880
4881    Unless this function is called, the first search or match using
4882    PATTERN_BUFFER will allocate its own register data, without
4883    freeing the old data.  */
4884
4885 void
4886 re_set_registers (struct re_pattern_buffer *bufp,
4887                   struct re_registers *regs, unsigned num_regs,
4888                   regoff_t *starts, regoff_t *ends)
4889 {
4890   if (num_regs)
4891     {
4892       bufp->regs_allocated = REGS_REALLOCATE;
4893       regs->num_regs = num_regs;
4894       regs->start = starts;
4895       regs->end = ends;
4896     }
4897   else
4898     {
4899       bufp->regs_allocated = REGS_UNALLOCATED;
4900       regs->num_regs = 0;
4901       regs->start = regs->end = (regoff_t *) 0;
4902     }
4903 }
4904 #ifdef _LIBC
4905 weak_alias (__re_set_registers, re_set_registers)
4906 #endif
4907 \f
4908 /* Searching routines.  */
4909
4910 /* Like re_search_2, below, but only one string is specified, and
4911    doesn't let you say where to stop matching.  */
4912
4913 int
4914 re_search (struct re_pattern_buffer *bufp, const char *string, int size,
4915            int startpos, int range, struct re_registers *regs)
4916 {
4917   return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4918                       regs, size);
4919 }
4920 #ifdef _LIBC
4921 weak_alias (__re_search, re_search)
4922 #endif
4923
4924
4925 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4926    virtual concatenation of STRING1 and STRING2, starting first at index
4927    STARTPOS, then at STARTPOS + 1, and so on.
4928
4929    STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4930
4931    RANGE is how far to scan while trying to match.  RANGE = 0 means try
4932    only at STARTPOS; in general, the last start tried is STARTPOS +
4933    RANGE.
4934
4935    In REGS, return the indices of the virtual concatenation of STRING1
4936    and STRING2 that matched the entire BUFP->buffer and its contained
4937    subexpressions.
4938
4939    Do not consider matching one past the index STOP in the virtual
4940    concatenation of STRING1 and STRING2.
4941
4942    We return either the position in the strings at which the match was
4943    found, -1 if no match, or -2 if error (such as failure
4944    stack overflow).  */
4945
4946 int
4947 re_search_2 (struct re_pattern_buffer *bufp, const char *string1, int size1,
4948              const char *string2, int size2, int startpos, int range,
4949              struct re_registers *regs, int stop)
4950 {
4951 # ifdef MBS_SUPPORT
4952   if (MB_CUR_MAX != 1)
4953     return wcs_re_search_2 (bufp, string1, size1, string2, size2, startpos,
4954                             range, regs, stop);
4955   else
4956 # endif
4957     return byte_re_search_2 (bufp, string1, size1, string2, size2, startpos,
4958                              range, regs, stop);
4959 } /* re_search_2 */
4960 #ifdef _LIBC
4961 weak_alias (__re_search_2, re_search_2)
4962 #endif
4963
4964 #endif /* not INSIDE_RECURSION */
4965
4966 #ifdef INSIDE_RECURSION
4967
4968 #ifdef MATCH_MAY_ALLOCATE
4969 # define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
4970 #else
4971 # define FREE_VAR(var) if (var) free (var); var = NULL
4972 #endif
4973
4974 #ifdef WCHAR
4975 # define MAX_ALLOCA_SIZE        2000
4976
4977 # define FREE_WCS_BUFFERS() \
4978   do {                                                                        \
4979     if (size1 > MAX_ALLOCA_SIZE)                                              \
4980       {                                                                       \
4981         free (wcs_string1);                                                   \
4982         free (mbs_offset1);                                                   \
4983       }                                                                       \
4984     else                                                                      \
4985       {                                                                       \
4986         FREE_VAR (wcs_string1);                                               \
4987         FREE_VAR (mbs_offset1);                                               \
4988       }                                                                       \
4989     if (size2 > MAX_ALLOCA_SIZE)                                              \
4990       {                                                                       \
4991         free (wcs_string2);                                                   \
4992         free (mbs_offset2);                                                   \
4993       }                                                                       \
4994     else                                                                      \
4995       {                                                                       \
4996         FREE_VAR (wcs_string2);                                               \
4997         FREE_VAR (mbs_offset2);                                               \
4998       }                                                                       \
4999   } while (0)
5000
5001 #endif
5002
5003
5004 static int
5005 PREFIX(re_search_2) (struct re_pattern_buffer *bufp, const char *string1,
5006                      int size1, const char *string2, int size2,
5007                      int startpos, int range,
5008                      struct re_registers *regs, int stop)
5009 {
5010   int val;
5011   register char *fastmap = bufp->fastmap;
5012   register RE_TRANSLATE_TYPE translate = bufp->translate;
5013   int total_size = size1 + size2;
5014   int endpos = startpos + range;
5015 #ifdef WCHAR
5016   /* We need wchar_t* buffers correspond to cstring1, cstring2.  */
5017   wchar_t *wcs_string1 = NULL, *wcs_string2 = NULL;
5018   /* We need the size of wchar_t buffers correspond to csize1, csize2.  */
5019   int wcs_size1 = 0, wcs_size2 = 0;
5020   /* offset buffer for optimizatoin. See convert_mbs_to_wc.  */
5021   int *mbs_offset1 = NULL, *mbs_offset2 = NULL;
5022   /* They hold whether each wchar_t is binary data or not.  */
5023   char *is_binary = NULL;
5024 #endif /* WCHAR */
5025
5026   /* Check for out-of-range STARTPOS.  */
5027   if (startpos < 0 || startpos > total_size)
5028     return -1;
5029
5030   /* Fix up RANGE if it might eventually take us outside
5031      the virtual concatenation of STRING1 and STRING2.
5032      Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE.  */
5033   if (endpos < 0)
5034     range = 0 - startpos;
5035   else if (endpos > total_size)
5036     range = total_size - startpos;
5037
5038   /* If the search isn't to be a backwards one, don't waste time in a
5039      search for a pattern that must be anchored.  */
5040   if (bufp->used > 0 && range > 0
5041       && ((re_opcode_t) bufp->buffer[0] == begbuf
5042           /* `begline' is like `begbuf' if it cannot match at newlines.  */
5043           || ((re_opcode_t) bufp->buffer[0] == begline
5044               && !bufp->newline_anchor)))
5045     {
5046       if (startpos > 0)
5047         return -1;
5048       else
5049         range = 1;
5050     }
5051
5052 #ifdef emacs
5053   /* In a forward search for something that starts with \=.
5054      don't keep searching past point.  */
5055   if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
5056     {
5057       range = PT - startpos;
5058       if (range <= 0)
5059         return -1;
5060     }
5061 #endif /* emacs */
5062
5063   /* Update the fastmap now if not correct already.  */
5064   if (fastmap && !bufp->fastmap_accurate)
5065     if (re_compile_fastmap (bufp) == -2)
5066       return -2;
5067
5068 #ifdef WCHAR
5069   /* Allocate wchar_t array for wcs_string1 and wcs_string2 and
5070      fill them with converted string.  */
5071   if (size1 != 0)
5072     {
5073       if (size1 > MAX_ALLOCA_SIZE)
5074         {
5075           wcs_string1 = TALLOC (size1 + 1, CHAR_T);
5076           mbs_offset1 = TALLOC (size1 + 1, int);
5077           is_binary = TALLOC (size1 + 1, char);
5078         }
5079       else
5080         {
5081           wcs_string1 = REGEX_TALLOC (size1 + 1, CHAR_T);
5082           mbs_offset1 = REGEX_TALLOC (size1 + 1, int);
5083           is_binary = REGEX_TALLOC (size1 + 1, char);
5084         }
5085       if (!wcs_string1 || !mbs_offset1 || !is_binary)
5086         {
5087           if (size1 > MAX_ALLOCA_SIZE)
5088             {
5089               free (wcs_string1);
5090               free (mbs_offset1);
5091               free (is_binary);
5092             }
5093           else
5094             {
5095               FREE_VAR (wcs_string1);
5096               FREE_VAR (mbs_offset1);
5097               FREE_VAR (is_binary);
5098             }
5099           return -2;
5100         }
5101       wcs_size1 = convert_mbs_to_wcs(wcs_string1, string1, size1,
5102                                      mbs_offset1, is_binary);
5103       wcs_string1[wcs_size1] = L'\0'; /* for a sentinel  */
5104       if (size1 > MAX_ALLOCA_SIZE)
5105         free (is_binary);
5106       else
5107         FREE_VAR (is_binary);
5108     }
5109   if (size2 != 0)
5110     {
5111       if (size2 > MAX_ALLOCA_SIZE)
5112         {
5113           wcs_string2 = TALLOC (size2 + 1, CHAR_T);
5114           mbs_offset2 = TALLOC (size2 + 1, int);
5115           is_binary = TALLOC (size2 + 1, char);
5116         }
5117       else
5118         {
5119           wcs_string2 = REGEX_TALLOC (size2 + 1, CHAR_T);
5120           mbs_offset2 = REGEX_TALLOC (size2 + 1, int);
5121           is_binary = REGEX_TALLOC (size2 + 1, char);
5122         }
5123       if (!wcs_string2 || !mbs_offset2 || !is_binary)
5124         {
5125           FREE_WCS_BUFFERS ();
5126           if (size2 > MAX_ALLOCA_SIZE)
5127             free (is_binary);
5128           else
5129             FREE_VAR (is_binary);
5130           return -2;
5131         }
5132       wcs_size2 = convert_mbs_to_wcs(wcs_string2, string2, size2,
5133                                      mbs_offset2, is_binary);
5134       wcs_string2[wcs_size2] = L'\0'; /* for a sentinel  */
5135       if (size2 > MAX_ALLOCA_SIZE)
5136         free (is_binary);
5137       else
5138         FREE_VAR (is_binary);
5139     }
5140 #endif /* WCHAR */
5141
5142
5143   /* Loop through the string, looking for a place to start matching.  */
5144   for (;;)
5145     {
5146       /* If a fastmap is supplied, skip quickly over characters that
5147          cannot be the start of a match.  If the pattern can match the
5148          null string, however, we don't need to skip characters; we want
5149          the first null string.  */
5150       if (fastmap && startpos < total_size && !bufp->can_be_null)
5151         {
5152           if (range > 0)        /* Searching forwards.  */
5153             {
5154               register const char *d;
5155               register int lim = 0;
5156               int irange = range;
5157
5158               if (startpos < size1 && startpos + range >= size1)
5159                 lim = range - (size1 - startpos);
5160
5161               d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
5162
5163               /* Written out as an if-else to avoid testing `translate'
5164                  inside the loop.  */
5165               if (translate)
5166                 while (range > lim
5167                        && !fastmap[(unsigned char)
5168                                    translate[(unsigned char) *d++]])
5169                   range--;
5170               else
5171                 while (range > lim && !fastmap[(unsigned char) *d++])
5172                   range--;
5173
5174               startpos += irange - range;
5175             }
5176           else                          /* Searching backwards.  */
5177             {
5178               register CHAR_T c = (size1 == 0 || startpos >= size1
5179                                       ? string2[startpos - size1]
5180                                       : string1[startpos]);
5181
5182               if (!fastmap[(unsigned char) TRANSLATE (c)])
5183                 goto advance;
5184             }
5185         }
5186
5187       /* If can't match the null string, and that's all we have left, fail.  */
5188       if (range >= 0 && startpos == total_size && fastmap
5189           && !bufp->can_be_null)
5190        {
5191 #ifdef WCHAR
5192          FREE_WCS_BUFFERS ();
5193 #endif
5194          return -1;
5195        }
5196
5197 #ifdef WCHAR
5198       val = wcs_re_match_2_internal (bufp, string1, size1, string2,
5199                                      size2, startpos, regs, stop,
5200                                      wcs_string1, wcs_size1,
5201                                      wcs_string2, wcs_size2,
5202                                      mbs_offset1, mbs_offset2);
5203 #else /* BYTE */
5204       val = byte_re_match_2_internal (bufp, string1, size1, string2,
5205                                       size2, startpos, regs, stop);
5206 #endif /* BYTE */
5207
5208 #ifndef REGEX_MALLOC
5209 # ifdef C_ALLOCA
5210       alloca (0);
5211 # endif
5212 #endif
5213
5214       if (val >= 0)
5215         {
5216 #ifdef WCHAR
5217           FREE_WCS_BUFFERS ();
5218 #endif
5219           return startpos;
5220         }
5221
5222       if (val == -2)
5223         {
5224 #ifdef WCHAR
5225           FREE_WCS_BUFFERS ();
5226 #endif
5227           return -2;
5228         }
5229
5230     advance:
5231       if (!range)
5232         break;
5233       else if (range > 0)
5234         {
5235           range--;
5236           startpos++;
5237         }
5238       else
5239         {
5240           range++;
5241           startpos--;
5242         }
5243     }
5244 #ifdef WCHAR
5245   FREE_WCS_BUFFERS ();
5246 #endif
5247   return -1;
5248 }
5249
5250 #ifdef WCHAR
5251 /* This converts PTR, a pointer into one of the search wchar_t strings
5252    `string1' and `string2' into an multibyte string offset from the
5253    beginning of that string. We use mbs_offset to optimize.
5254    See convert_mbs_to_wcs.  */
5255 # define POINTER_TO_OFFSET(ptr)                                         \
5256   (FIRST_STRING_P (ptr)                                                 \
5257    ? ((regoff_t)(mbs_offset1 != NULL? mbs_offset1[(ptr)-string1] : 0))  \
5258    : ((regoff_t)((mbs_offset2 != NULL? mbs_offset2[(ptr)-string2] : 0)  \
5259                  + csize1)))
5260 #else /* BYTE */
5261 /* This converts PTR, a pointer into one of the search strings `string1'
5262    and `string2' into an offset from the beginning of that string.  */
5263 # define POINTER_TO_OFFSET(ptr)                 \
5264   (FIRST_STRING_P (ptr)                         \
5265    ? ((regoff_t) ((ptr) - string1))             \
5266    : ((regoff_t) ((ptr) - string2 + size1)))
5267 #endif /* WCHAR */
5268
5269 /* Macros for dealing with the split strings in re_match_2.  */
5270
5271 #define MATCHING_IN_FIRST_STRING  (dend == end_match_1)
5272
5273 /* Call before fetching a character with *d.  This switches over to
5274    string2 if necessary.  */
5275 #define PREFETCH()                                                      \
5276   while (d == dend)                                                     \
5277     {                                                                   \
5278       /* End of string2 => fail.  */                                    \
5279       if (dend == end_match_2)                                          \
5280         goto fail;                                                      \
5281       /* End of string1 => advance to string2.  */                      \
5282       d = string2;                                                      \
5283       dend = end_match_2;                                               \
5284     }
5285
5286 /* Test if at very beginning or at very end of the virtual concatenation
5287    of `string1' and `string2'.  If only one string, it's `string2'.  */
5288 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
5289 #define AT_STRINGS_END(d) ((d) == end2)
5290
5291
5292 /* Test if D points to a character which is word-constituent.  We have
5293    two special cases to check for: if past the end of string1, look at
5294    the first character in string2; and if before the beginning of
5295    string2, look at the last character in string1.  */
5296 #ifdef WCHAR
5297 /* Use internationalized API instead of SYNTAX.  */
5298 # define WORDCHAR_P(d)                                                  \
5299   (iswalnum ((wint_t)((d) == end1 ? *string2                            \
5300            : (d) == string2 - 1 ? *(end1 - 1) : *(d))) != 0             \
5301    || ((d) == end1 ? *string2                                           \
5302        : (d) == string2 - 1 ? *(end1 - 1) : *(d)) == L'_')
5303 #else /* BYTE */
5304 # define WORDCHAR_P(d)                                                  \
5305   (SYNTAX ((d) == end1 ? *string2                                       \
5306            : (d) == string2 - 1 ? *(end1 - 1) : *(d))                   \
5307    == Sword)
5308 #endif /* WCHAR */
5309
5310 /* Disabled due to a compiler bug -- see comment at case wordbound */
5311 #if 0
5312 /* Test if the character before D and the one at D differ with respect
5313    to being word-constituent.  */
5314 #define AT_WORD_BOUNDARY(d)                                             \
5315   (AT_STRINGS_BEG (d) || AT_STRINGS_END (d)                             \
5316    || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
5317 #endif
5318
5319 /* Free everything we malloc.  */
5320 #ifdef MATCH_MAY_ALLOCATE
5321 # ifdef WCHAR
5322 #  define FREE_VARIABLES()                                              \
5323   do {                                                                  \
5324     REGEX_FREE_STACK (fail_stack.stack);                                \
5325     FREE_VAR (regstart);                                                \
5326     FREE_VAR (regend);                                                  \
5327     FREE_VAR (old_regstart);                                            \
5328     FREE_VAR (old_regend);                                              \
5329     FREE_VAR (best_regstart);                                           \
5330     FREE_VAR (best_regend);                                             \
5331     FREE_VAR (reg_info);                                                \
5332     FREE_VAR (reg_dummy);                                               \
5333     FREE_VAR (reg_info_dummy);                                          \
5334     if (!cant_free_wcs_buf)                                             \
5335       {                                                                 \
5336         FREE_VAR (string1);                                             \
5337         FREE_VAR (string2);                                             \
5338         FREE_VAR (mbs_offset1);                                         \
5339         FREE_VAR (mbs_offset2);                                         \
5340       }                                                                 \
5341   } while (0)
5342 # else /* BYTE */
5343 #  define FREE_VARIABLES()                                              \
5344   do {                                                                  \
5345     REGEX_FREE_STACK (fail_stack.stack);                                \
5346     FREE_VAR (regstart);                                                \
5347     FREE_VAR (regend);                                                  \
5348     FREE_VAR (old_regstart);                                            \
5349     FREE_VAR (old_regend);                                              \
5350     FREE_VAR (best_regstart);                                           \
5351     FREE_VAR (best_regend);                                             \
5352     FREE_VAR (reg_info);                                                \
5353     FREE_VAR (reg_dummy);                                               \
5354     FREE_VAR (reg_info_dummy);                                          \
5355   } while (0)
5356 # endif /* WCHAR */
5357 #else
5358 # ifdef WCHAR
5359 #  define FREE_VARIABLES()                                              \
5360   do {                                                                  \
5361     if (!cant_free_wcs_buf)                                             \
5362       {                                                                 \
5363         FREE_VAR (string1);                                             \
5364         FREE_VAR (string2);                                             \
5365         FREE_VAR (mbs_offset1);                                         \
5366         FREE_VAR (mbs_offset2);                                         \
5367       }                                                                 \
5368   } while (0)
5369 # else /* BYTE */
5370 #  define FREE_VARIABLES() ((void)0) /* Do nothing!  But inhibit gcc warning. */
5371 # endif /* WCHAR */
5372 #endif /* not MATCH_MAY_ALLOCATE */
5373
5374 /* These values must meet several constraints.  They must not be valid
5375    register values; since we have a limit of 255 registers (because
5376    we use only one byte in the pattern for the register number), we can
5377    use numbers larger than 255.  They must differ by 1, because of
5378    NUM_FAILURE_ITEMS above.  And the value for the lowest register must
5379    be larger than the value for the highest register, so we do not try
5380    to actually save any registers when none are active.  */
5381 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
5382 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
5383 \f
5384 #else /* not INSIDE_RECURSION */
5385 /* Matching routines.  */
5386
5387 #ifndef emacs   /* Emacs never uses this.  */
5388 /* re_match is like re_match_2 except it takes only a single string.  */
5389
5390 int
5391 re_match (struct re_pattern_buffer *bufp, const char *string,
5392           int size, int pos, struct re_registers *regs)
5393 {
5394   int result;
5395 # ifdef MBS_SUPPORT
5396   if (MB_CUR_MAX != 1)
5397     result = wcs_re_match_2_internal (bufp, NULL, 0, string, size,
5398                                       pos, regs, size,
5399                                       NULL, 0, NULL, 0, NULL, NULL);
5400   else
5401 # endif
5402     result = byte_re_match_2_internal (bufp, NULL, 0, string, size,
5403                                   pos, regs, size);
5404 # ifndef REGEX_MALLOC
5405 #  ifdef C_ALLOCA
5406   alloca (0);
5407 #  endif
5408 # endif
5409   return result;
5410 }
5411 # ifdef _LIBC
5412 weak_alias (__re_match, re_match)
5413 # endif
5414 #endif /* not emacs */
5415
5416 #endif /* not INSIDE_RECURSION */
5417
5418 #ifdef INSIDE_RECURSION
5419 static boolean PREFIX(group_match_null_string_p) (UCHAR_T **p,
5420                                                   UCHAR_T *end,
5421                                         PREFIX(register_info_type) *reg_info);
5422 static boolean PREFIX(alt_match_null_string_p) (UCHAR_T *p,
5423                                                 UCHAR_T *end,
5424                                         PREFIX(register_info_type) *reg_info);
5425 static boolean PREFIX(common_op_match_null_string_p) (UCHAR_T **p,
5426                                                       UCHAR_T *end,
5427                                         PREFIX(register_info_type) *reg_info);
5428 static int PREFIX(bcmp_translate) (const CHAR_T *s1, const CHAR_T *s2,
5429                                    int len, char *translate);
5430 #else /* not INSIDE_RECURSION */
5431
5432 /* re_match_2 matches the compiled pattern in BUFP against the
5433    the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
5434    and SIZE2, respectively).  We start matching at POS, and stop
5435    matching at STOP.
5436
5437    If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
5438    store offsets for the substring each group matched in REGS.  See the
5439    documentation for exactly how many groups we fill.
5440
5441    We return -1 if no match, -2 if an internal error (such as the
5442    failure stack overflowing).  Otherwise, we return the length of the
5443    matched substring.  */
5444
5445 int
5446 re_match_2 (struct re_pattern_buffer *bufp, const char *string1, int size1,
5447             const char *string2, int size2, int pos,
5448             struct re_registers *regs, int stop)
5449 {
5450   int result;
5451 # ifdef MBS_SUPPORT
5452   if (MB_CUR_MAX != 1)
5453     result = wcs_re_match_2_internal (bufp, string1, size1, string2, size2,
5454                                       pos, regs, stop,
5455                                       NULL, 0, NULL, 0, NULL, NULL);
5456   else
5457 # endif
5458     result = byte_re_match_2_internal (bufp, string1, size1, string2, size2,
5459                                   pos, regs, stop);
5460
5461 #ifndef REGEX_MALLOC
5462 # ifdef C_ALLOCA
5463   alloca (0);
5464 # endif
5465 #endif
5466   return result;
5467 }
5468 #ifdef _LIBC
5469 weak_alias (__re_match_2, re_match_2)
5470 #endif
5471
5472 #endif /* not INSIDE_RECURSION */
5473
5474 #ifdef INSIDE_RECURSION
5475
5476 #ifdef WCHAR
5477 static int count_mbs_length (int *, int);
5478
5479 /* This check the substring (from 0, to length) of the multibyte string,
5480    to which offset_buffer correspond. And count how many wchar_t_characters
5481    the substring occupy. We use offset_buffer to optimization.
5482    See convert_mbs_to_wcs.  */
5483
5484 static int
5485 count_mbs_length(int *offset_buffer, int length)
5486 {
5487   int upper, lower;
5488
5489   /* Check whether the size is valid.  */
5490   if (length < 0)
5491     return -1;
5492
5493   if (offset_buffer == NULL)
5494     return 0;
5495
5496   /* If there are no multibyte character, offset_buffer[i] == i.
5497    Optmize for this case.  */
5498   if (offset_buffer[length] == length)
5499     return length;
5500
5501   /* Set up upper with length. (because for all i, offset_buffer[i] >= i)  */
5502   upper = length;
5503   lower = 0;
5504
5505   while (true)
5506     {
5507       int middle = (lower + upper) / 2;
5508       if (middle == lower || middle == upper)
5509         break;
5510       if (offset_buffer[middle] > length)
5511         upper = middle;
5512       else if (offset_buffer[middle] < length)
5513         lower = middle;
5514       else
5515         return middle;
5516     }
5517
5518   return -1;
5519 }
5520 #endif /* WCHAR */
5521
5522 /* This is a separate function so that we can force an alloca cleanup
5523    afterwards.  */
5524 #ifdef WCHAR
5525 static int
5526 wcs_re_match_2_internal (struct re_pattern_buffer *bufp,
5527                          const char *cstring1, int csize1,
5528                          const char *cstring2, int csize2,
5529                          int pos,
5530                          struct re_registers *regs,
5531                          int stop,
5532      /* string1 == string2 == NULL means string1/2, size1/2 and
5533         mbs_offset1/2 need seting up in this function.  */
5534      /* We need wchar_t* buffers correspond to cstring1, cstring2.  */
5535                          wchar_t *string1, int size1,
5536                          wchar_t *string2, int size2,
5537      /* offset buffer for optimizatoin. See convert_mbs_to_wc.  */
5538                          int *mbs_offset1, int *mbs_offset2)
5539 #else /* BYTE */
5540 static int
5541 byte_re_match_2_internal (struct re_pattern_buffer *bufp,
5542                           const char *string1, int size1,
5543                           const char *string2, int size2,
5544                           int pos,
5545                           struct re_registers *regs, int stop)
5546 #endif /* BYTE */
5547 {
5548   /* General temporaries.  */
5549   int mcnt;
5550   UCHAR_T *p1;
5551 #ifdef WCHAR
5552   /* They hold whether each wchar_t is binary data or not.  */
5553   char *is_binary = NULL;
5554   /* If true, we can't free string1/2, mbs_offset1/2.  */
5555   int cant_free_wcs_buf = 1;
5556 #endif /* WCHAR */
5557
5558   /* Just past the end of the corresponding string.  */
5559   const CHAR_T *end1, *end2;
5560
5561   /* Pointers into string1 and string2, just past the last characters in
5562      each to consider matching.  */
5563   const CHAR_T *end_match_1, *end_match_2;
5564
5565   /* Where we are in the data, and the end of the current string.  */
5566   const CHAR_T *d, *dend;
5567
5568   /* Where we are in the pattern, and the end of the pattern.  */
5569 #ifdef WCHAR
5570   UCHAR_T *pattern, *p;
5571   register UCHAR_T *pend;
5572 #else /* BYTE */
5573   UCHAR_T *p = bufp->buffer;
5574   register UCHAR_T *pend = p + bufp->used;
5575 #endif /* WCHAR */
5576
5577   /* Mark the opcode just after a start_memory, so we can test for an
5578      empty subpattern when we get to the stop_memory.  */
5579   UCHAR_T *just_past_start_mem = 0;
5580
5581   /* We use this to map every character in the string.  */
5582   RE_TRANSLATE_TYPE translate = bufp->translate;
5583
5584   /* Failure point stack.  Each place that can handle a failure further
5585      down the line pushes a failure point on this stack.  It consists of
5586      restart, regend, and reg_info for all registers corresponding to
5587      the subexpressions we're currently inside, plus the number of such
5588      registers, and, finally, two char *'s.  The first char * is where
5589      to resume scanning the pattern; the second one is where to resume
5590      scanning the strings.  If the latter is zero, the failure point is
5591      a ``dummy''; if a failure happens and the failure point is a dummy,
5592      it gets discarded and the next next one is tried.  */
5593 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global.  */
5594   PREFIX(fail_stack_type) fail_stack;
5595 #endif
5596 #ifdef DEBUG
5597   static unsigned failure_id;
5598   unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
5599 #endif
5600
5601 #ifdef REL_ALLOC
5602   /* This holds the pointer to the failure stack, when
5603      it is allocated relocatably.  */
5604   fail_stack_elt_t *failure_stack_ptr;
5605 #endif
5606
5607   /* We fill all the registers internally, independent of what we
5608      return, for use in backreferences.  The number here includes
5609      an element for register zero.  */
5610   size_t num_regs = bufp->re_nsub + 1;
5611
5612   /* The currently active registers.  */
5613   active_reg_t lowest_active_reg = NO_LOWEST_ACTIVE_REG;
5614   active_reg_t highest_active_reg = NO_HIGHEST_ACTIVE_REG;
5615
5616   /* Information on the contents of registers. These are pointers into
5617      the input strings; they record just what was matched (on this
5618      attempt) by a subexpression part of the pattern, that is, the
5619      regnum-th regstart pointer points to where in the pattern we began
5620      matching and the regnum-th regend points to right after where we
5621      stopped matching the regnum-th subexpression.  (The zeroth register
5622      keeps track of what the whole pattern matches.)  */
5623 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global.  */
5624   const CHAR_T **regstart, **regend;
5625 #endif
5626
5627   /* If a group that's operated upon by a repetition operator fails to
5628      match anything, then the register for its start will need to be
5629      restored because it will have been set to wherever in the string we
5630      are when we last see its open-group operator.  Similarly for a
5631      register's end.  */
5632 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global.  */
5633   const CHAR_T **old_regstart, **old_regend;
5634 #endif
5635
5636   /* The is_active field of reg_info helps us keep track of which (possibly
5637      nested) subexpressions we are currently in. The matched_something
5638      field of reg_info[reg_num] helps us tell whether or not we have
5639      matched any of the pattern so far this time through the reg_num-th
5640      subexpression.  These two fields get reset each time through any
5641      loop their register is in.  */
5642 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global.  */
5643   PREFIX(register_info_type) *reg_info;
5644 #endif
5645
5646   /* The following record the register info as found in the above
5647      variables when we find a match better than any we've seen before.
5648      This happens as we backtrack through the failure points, which in
5649      turn happens only if we have not yet matched the entire string. */
5650   unsigned best_regs_set = false;
5651 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global.  */
5652   const CHAR_T **best_regstart, **best_regend;
5653 #endif
5654
5655   /* Logically, this is `best_regend[0]'.  But we don't want to have to
5656      allocate space for that if we're not allocating space for anything
5657      else (see below).  Also, we never need info about register 0 for
5658      any of the other register vectors, and it seems rather a kludge to
5659      treat `best_regend' differently than the rest.  So we keep track of
5660      the end of the best match so far in a separate variable.  We
5661      initialize this to NULL so that when we backtrack the first time
5662      and need to test it, it's not garbage.  */
5663   const CHAR_T *match_end = NULL;
5664
5665   /* This helps SET_REGS_MATCHED avoid doing redundant work.  */
5666   int set_regs_matched_done = 0;
5667
5668   /* Used when we pop values we don't care about.  */
5669 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global.  */
5670   const CHAR_T **reg_dummy;
5671   PREFIX(register_info_type) *reg_info_dummy;
5672 #endif
5673
5674 #ifdef DEBUG
5675   /* Counts the total number of registers pushed.  */
5676   unsigned num_regs_pushed = 0;
5677 #endif
5678
5679   DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5680
5681   INIT_FAIL_STACK ();
5682
5683 #ifdef MATCH_MAY_ALLOCATE
5684   /* Do not bother to initialize all the register variables if there are
5685      no groups in the pattern, as it takes a fair amount of time.  If
5686      there are groups, we include space for register 0 (the whole
5687      pattern), even though we never use it, since it simplifies the
5688      array indexing.  We should fix this.  */
5689   if (bufp->re_nsub)
5690     {
5691       regstart = REGEX_TALLOC (num_regs, const CHAR_T *);
5692       regend = REGEX_TALLOC (num_regs, const CHAR_T *);
5693       old_regstart = REGEX_TALLOC (num_regs, const CHAR_T *);
5694       old_regend = REGEX_TALLOC (num_regs, const CHAR_T *);
5695       best_regstart = REGEX_TALLOC (num_regs, const CHAR_T *);
5696       best_regend = REGEX_TALLOC (num_regs, const CHAR_T *);
5697       reg_info = REGEX_TALLOC (num_regs, PREFIX(register_info_type));
5698       reg_dummy = REGEX_TALLOC (num_regs, const CHAR_T *);
5699       reg_info_dummy = REGEX_TALLOC (num_regs, PREFIX(register_info_type));
5700
5701       if (!(regstart && regend && old_regstart && old_regend && reg_info
5702             && best_regstart && best_regend && reg_dummy && reg_info_dummy))
5703         {
5704           FREE_VARIABLES ();
5705           return -2;
5706         }
5707     }
5708   else
5709     {
5710       /* We must initialize all our variables to NULL, so that
5711          `FREE_VARIABLES' doesn't try to free them.  */
5712       regstart = regend = old_regstart = old_regend = best_regstart
5713         = best_regend = reg_dummy = NULL;
5714       reg_info = reg_info_dummy = (PREFIX(register_info_type) *) NULL;
5715     }
5716 #endif /* MATCH_MAY_ALLOCATE */
5717
5718   /* The starting position is bogus.  */
5719 #ifdef WCHAR
5720   if (pos < 0 || pos > csize1 + csize2)
5721 #else /* BYTE */
5722   if (pos < 0 || pos > size1 + size2)
5723 #endif
5724     {
5725       FREE_VARIABLES ();
5726       return -1;
5727     }
5728
5729 #ifdef WCHAR
5730   /* Allocate wchar_t array for string1 and string2 and
5731      fill them with converted string.  */
5732   if (string1 == NULL && string2 == NULL)
5733     {
5734       /* We need seting up buffers here.  */
5735
5736       /* We must free wcs buffers in this function.  */
5737       cant_free_wcs_buf = 0;
5738
5739       if (csize1 != 0)
5740         {
5741           string1 = REGEX_TALLOC (csize1 + 1, CHAR_T);
5742           mbs_offset1 = REGEX_TALLOC (csize1 + 1, int);
5743           is_binary = REGEX_TALLOC (csize1 + 1, char);
5744           if (!string1 || !mbs_offset1 || !is_binary)
5745             {
5746               FREE_VAR (string1);
5747               FREE_VAR (mbs_offset1);
5748               FREE_VAR (is_binary);
5749               return -2;
5750             }
5751         }
5752       if (csize2 != 0)
5753         {
5754           string2 = REGEX_TALLOC (csize2 + 1, CHAR_T);
5755           mbs_offset2 = REGEX_TALLOC (csize2 + 1, int);
5756           is_binary = REGEX_TALLOC (csize2 + 1, char);
5757           if (!string2 || !mbs_offset2 || !is_binary)
5758             {
5759               FREE_VAR (string1);
5760               FREE_VAR (mbs_offset1);
5761               FREE_VAR (string2);
5762               FREE_VAR (mbs_offset2);
5763               FREE_VAR (is_binary);
5764               return -2;
5765             }
5766           size2 = convert_mbs_to_wcs(string2, cstring2, csize2,
5767                                      mbs_offset2, is_binary);
5768           string2[size2] = L'\0'; /* for a sentinel  */
5769           FREE_VAR (is_binary);
5770         }
5771     }
5772
5773   /* We need to cast pattern to (wchar_t*), because we casted this compiled
5774      pattern to (char*) in regex_compile.  */
5775   p = pattern = (CHAR_T*)bufp->buffer;
5776   pend = (CHAR_T*)(bufp->buffer + bufp->used);
5777
5778 #endif /* WCHAR */
5779
5780   /* Initialize subexpression text positions to -1 to mark ones that no
5781      start_memory/stop_memory has been seen for. Also initialize the
5782      register information struct.  */
5783   for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5784     {
5785       regstart[mcnt] = regend[mcnt]
5786         = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
5787
5788       REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
5789       IS_ACTIVE (reg_info[mcnt]) = 0;
5790       MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5791       EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5792     }
5793
5794   /* We move `string1' into `string2' if the latter's empty -- but not if
5795      `string1' is null.  */
5796   if (size2 == 0 && string1 != NULL)
5797     {
5798       string2 = string1;
5799       size2 = size1;
5800       string1 = 0;
5801       size1 = 0;
5802 #ifdef WCHAR
5803       mbs_offset2 = mbs_offset1;
5804       csize2 = csize1;
5805       mbs_offset1 = NULL;
5806       csize1 = 0;
5807 #endif
5808     }
5809   end1 = string1 + size1;
5810   end2 = string2 + size2;
5811
5812   /* Compute where to stop matching, within the two strings.  */
5813 #ifdef WCHAR
5814   if (stop <= csize1)
5815     {
5816       mcnt = count_mbs_length(mbs_offset1, stop);
5817       end_match_1 = string1 + mcnt;
5818       end_match_2 = string2;
5819     }
5820   else
5821     {
5822       if (stop > csize1 + csize2)
5823         stop = csize1 + csize2;
5824       end_match_1 = end1;
5825       mcnt = count_mbs_length(mbs_offset2, stop-csize1);
5826       end_match_2 = string2 + mcnt;
5827     }
5828   if (mcnt < 0)
5829     { /* count_mbs_length return error.  */
5830       FREE_VARIABLES ();
5831       return -1;
5832     }
5833 #else
5834   if (stop <= size1)
5835     {
5836       end_match_1 = string1 + stop;
5837       end_match_2 = string2;
5838     }
5839   else
5840     {
5841       end_match_1 = end1;
5842       end_match_2 = string2 + stop - size1;
5843     }
5844 #endif /* WCHAR */
5845
5846   /* `p' scans through the pattern as `d' scans through the data.
5847      `dend' is the end of the input string that `d' points within.  `d'
5848      is advanced into the following input string whenever necessary, but
5849      this happens before fetching; therefore, at the beginning of the
5850      loop, `d' can be pointing at the end of a string, but it cannot
5851      equal `string2'.  */
5852 #ifdef WCHAR
5853   if (size1 > 0 && pos <= csize1)
5854     {
5855       mcnt = count_mbs_length(mbs_offset1, pos);
5856       d = string1 + mcnt;
5857       dend = end_match_1;
5858     }
5859   else
5860     {
5861       mcnt = count_mbs_length(mbs_offset2, pos-csize1);
5862       d = string2 + mcnt;
5863       dend = end_match_2;
5864     }
5865
5866   if (mcnt < 0)
5867     { /* count_mbs_length return error.  */
5868       FREE_VARIABLES ();
5869       return -1;
5870     }
5871 #else
5872   if (size1 > 0 && pos <= size1)
5873     {
5874       d = string1 + pos;
5875       dend = end_match_1;
5876     }
5877   else
5878     {
5879       d = string2 + pos - size1;
5880       dend = end_match_2;
5881     }
5882 #endif /* WCHAR */
5883
5884   DEBUG_PRINT1 ("The compiled pattern is:\n");
5885   DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5886   DEBUG_PRINT1 ("The string to match is: `");
5887   DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5888   DEBUG_PRINT1 ("'\n");
5889
5890   /* This loops over pattern commands.  It exits by returning from the
5891      function if the match is complete, or it drops through if the match
5892      fails at this starting point in the input data.  */
5893   for (;;)
5894     {
5895 #ifdef _LIBC
5896       DEBUG_PRINT2 ("\n%p: ", p);
5897 #else
5898       DEBUG_PRINT2 ("\n0x%x: ", p);
5899 #endif
5900
5901       if (p == pend)
5902         { /* End of pattern means we might have succeeded.  */
5903           DEBUG_PRINT1 ("end of pattern ... ");
5904
5905           /* If we haven't matched the entire string, and we want the
5906              longest match, try backtracking.  */
5907           if (d != end_match_2)
5908             {
5909               /* 1 if this match ends in the same string (string1 or string2)
5910                  as the best previous match.  */
5911               boolean same_str_p = (FIRST_STRING_P (match_end)
5912                                     == MATCHING_IN_FIRST_STRING);
5913               /* 1 if this match is the best seen so far.  */
5914               boolean best_match_p;
5915
5916               /* AIX compiler got confused when this was combined
5917                  with the previous declaration.  */
5918               if (same_str_p)
5919                 best_match_p = d > match_end;
5920               else
5921                 best_match_p = !MATCHING_IN_FIRST_STRING;
5922
5923               DEBUG_PRINT1 ("backtracking.\n");
5924
5925               if (!FAIL_STACK_EMPTY ())
5926                 { /* More failure points to try.  */
5927
5928                   /* If exceeds best match so far, save it.  */
5929                   if (!best_regs_set || best_match_p)
5930                     {
5931                       best_regs_set = true;
5932                       match_end = d;
5933
5934                       DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5935
5936                       for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5937                         {
5938                           best_regstart[mcnt] = regstart[mcnt];
5939                           best_regend[mcnt] = regend[mcnt];
5940                         }
5941                     }
5942                   goto fail;
5943                 }
5944
5945               /* If no failure points, don't restore garbage.  And if
5946                  last match is real best match, don't restore second
5947                  best one. */
5948               else if (best_regs_set && !best_match_p)
5949                 {
5950                 restore_best_regs:
5951                   /* Restore best match.  It may happen that `dend ==
5952                      end_match_1' while the restored d is in string2.
5953                      For example, the pattern `x.*y.*z' against the
5954                      strings `x-' and `y-z-', if the two strings are
5955                      not consecutive in memory.  */
5956                   DEBUG_PRINT1 ("Restoring best registers.\n");
5957
5958                   d = match_end;
5959                   dend = ((d >= string1 && d <= end1)
5960                            ? end_match_1 : end_match_2);
5961
5962                   for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5963                     {
5964                       regstart[mcnt] = best_regstart[mcnt];
5965                       regend[mcnt] = best_regend[mcnt];
5966                     }
5967                 }
5968             } /* d != end_match_2 */
5969
5970         succeed_label:
5971           DEBUG_PRINT1 ("Accepting match.\n");
5972           /* If caller wants register contents data back, do it.  */
5973           if (regs && !bufp->no_sub)
5974             {
5975               /* Have the register data arrays been allocated?  */
5976               if (bufp->regs_allocated == REGS_UNALLOCATED)
5977                 { /* No.  So allocate them with malloc.  We need one
5978                      extra element beyond `num_regs' for the `-1' marker
5979                      GNU code uses.  */
5980                   regs->num_regs = MAX (RE_NREGS, num_regs + 1);
5981                   regs->start = TALLOC (regs->num_regs, regoff_t);
5982                   regs->end = TALLOC (regs->num_regs, regoff_t);
5983                   if (regs->start == NULL || regs->end == NULL)
5984                     {
5985                       FREE_VARIABLES ();
5986                       return -2;
5987                     }
5988                   bufp->regs_allocated = REGS_REALLOCATE;
5989                 }
5990               else if (bufp->regs_allocated == REGS_REALLOCATE)
5991                 { /* Yes.  If we need more elements than were already
5992                      allocated, reallocate them.  If we need fewer, just
5993                      leave it alone.  */
5994                   if (regs->num_regs < num_regs + 1)
5995                     {
5996                       regs->num_regs = num_regs + 1;
5997                       RETALLOC (regs->start, regs->num_regs, regoff_t);
5998                       RETALLOC (regs->end, regs->num_regs, regoff_t);
5999                       if (regs->start == NULL || regs->end == NULL)
6000                         {
6001                           FREE_VARIABLES ();
6002                           return -2;
6003                         }
6004                     }
6005                 }
6006               else
6007                 {
6008                   /* These braces fend off a "empty body in an else-statement"
6009                      warning under GCC when assert expands to nothing.  */
6010                   assert (bufp->regs_allocated == REGS_FIXED);
6011                 }
6012
6013               /* Convert the pointer data in `regstart' and `regend' to
6014                  indices.  Register zero has to be set differently,
6015                  since we haven't kept track of any info for it.  */
6016               if (regs->num_regs > 0)
6017                 {
6018                   regs->start[0] = pos;
6019 #ifdef WCHAR
6020                   if (MATCHING_IN_FIRST_STRING)
6021                     regs->end[0] = mbs_offset1 != NULL ?
6022                                         mbs_offset1[d-string1] : 0;
6023                   else
6024                     regs->end[0] = csize1 + (mbs_offset2 != NULL ?
6025                                              mbs_offset2[d-string2] : 0);
6026 #else
6027                   regs->end[0] = (MATCHING_IN_FIRST_STRING
6028                                   ? ((regoff_t) (d - string1))
6029                                   : ((regoff_t) (d - string2 + size1)));
6030 #endif /* WCHAR */
6031                 }
6032
6033               /* Go through the first `min (num_regs, regs->num_regs)'
6034                  registers, since that is all we initialized.  */
6035               for (mcnt = 1; (unsigned) mcnt < MIN (num_regs, regs->num_regs);
6036                    mcnt++)
6037                 {
6038                   if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
6039                     regs->start[mcnt] = regs->end[mcnt] = -1;
6040                   else
6041                     {
6042                       regs->start[mcnt]
6043                         = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
6044                       regs->end[mcnt]
6045                         = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
6046                     }
6047                 }
6048
6049               /* If the regs structure we return has more elements than
6050                  were in the pattern, set the extra elements to -1.  If
6051                  we (re)allocated the registers, this is the case,
6052                  because we always allocate enough to have at least one
6053                  -1 at the end.  */
6054               for (mcnt = num_regs; (unsigned) mcnt < regs->num_regs; mcnt++)
6055                 regs->start[mcnt] = regs->end[mcnt] = -1;
6056             } /* regs && !bufp->no_sub */
6057
6058           DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
6059                         nfailure_points_pushed, nfailure_points_popped,
6060                         nfailure_points_pushed - nfailure_points_popped);
6061           DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
6062
6063 #ifdef WCHAR
6064           if (MATCHING_IN_FIRST_STRING)
6065             mcnt = mbs_offset1 != NULL ? mbs_offset1[d-string1] : 0;
6066           else
6067             mcnt = (mbs_offset2 != NULL ? mbs_offset2[d-string2] : 0) +
6068                         csize1;
6069           mcnt -= pos;
6070 #else
6071           mcnt = d - pos - (MATCHING_IN_FIRST_STRING
6072                             ? string1
6073                             : string2 - size1);
6074 #endif /* WCHAR */
6075
6076           DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
6077
6078           FREE_VARIABLES ();
6079           return mcnt;
6080         }
6081
6082       /* Otherwise match next pattern command.  */
6083       switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
6084         {
6085         /* Ignore these.  Used to ignore the n of succeed_n's which
6086            currently have n == 0.  */
6087         case no_op:
6088           DEBUG_PRINT1 ("EXECUTING no_op.\n");
6089           break;
6090
6091         case succeed:
6092           DEBUG_PRINT1 ("EXECUTING succeed.\n");
6093           goto succeed_label;
6094
6095         /* Match the next n pattern characters exactly.  The following
6096            byte in the pattern defines n, and the n bytes after that
6097            are the characters to match.  */
6098         case exactn:
6099 #ifdef MBS_SUPPORT
6100         case exactn_bin:
6101 #endif
6102           mcnt = *p++;
6103           DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
6104
6105           /* This is written out as an if-else so we don't waste time
6106              testing `translate' inside the loop.  */
6107           if (translate)
6108             {
6109               do
6110                 {
6111                   PREFETCH ();
6112 #ifdef WCHAR
6113                   if (*d <= 0xff)
6114                     {
6115                       if ((UCHAR_T) translate[(unsigned char) *d++]
6116                           != (UCHAR_T) *p++)
6117                         goto fail;
6118                     }
6119                   else
6120                     {
6121                       if (*d++ != (CHAR_T) *p++)
6122                         goto fail;
6123                     }
6124 #else
6125                   if ((UCHAR_T) translate[(unsigned char) *d++]
6126                       != (UCHAR_T) *p++)
6127                     goto fail;
6128 #endif /* WCHAR */
6129                 }
6130               while (--mcnt);
6131             }
6132           else
6133             {
6134               do
6135                 {
6136                   PREFETCH ();
6137                   if (*d++ != (CHAR_T) *p++) goto fail;
6138                 }
6139               while (--mcnt);
6140             }
6141           SET_REGS_MATCHED ();
6142           break;
6143
6144
6145         /* Match any character except possibly a newline or a null.  */
6146         case anychar:
6147           DEBUG_PRINT1 ("EXECUTING anychar.\n");
6148
6149           PREFETCH ();
6150
6151           if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
6152               || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
6153             goto fail;
6154
6155           SET_REGS_MATCHED ();
6156           DEBUG_PRINT2 ("  Matched `%ld'.\n", (long int) *d);
6157           d++;
6158           break;
6159
6160
6161         case charset:
6162         case charset_not:
6163           {
6164             register UCHAR_T c;
6165 #ifdef WCHAR
6166             unsigned int i, char_class_length, coll_symbol_length,
6167               equiv_class_length, ranges_length, chars_length, length;
6168             CHAR_T *workp, *workp2, *charset_top;
6169 #define WORK_BUFFER_SIZE 128
6170             CHAR_T str_buf[WORK_BUFFER_SIZE];
6171 # ifdef _LIBC
6172             uint32_t nrules;
6173 # endif /* _LIBC */
6174 #endif /* WCHAR */
6175             boolean negate = (re_opcode_t) *(p - 1) == charset_not;
6176
6177             DEBUG_PRINT2 ("EXECUTING charset%s.\n", negate ? "_not" : "");
6178             PREFETCH ();
6179             c = TRANSLATE (*d); /* The character to match.  */
6180 #ifdef WCHAR
6181 # ifdef _LIBC
6182             nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
6183 # endif /* _LIBC */
6184             charset_top = p - 1;
6185             char_class_length = *p++;
6186             coll_symbol_length = *p++;
6187             equiv_class_length = *p++;
6188             ranges_length = *p++;
6189             chars_length = *p++;
6190             /* p points charset[6], so the address of the next instruction
6191                (charset[l+m+n+2o+k+p']) equals p[l+m+n+2*o+p'],
6192                where l=length of char_classes, m=length of collating_symbol,
6193                n=equivalence_class, o=length of char_range,
6194                p'=length of character.  */
6195             workp = p;
6196             /* Update p to indicate the next instruction.  */
6197             p += char_class_length + coll_symbol_length+ equiv_class_length +
6198               2*ranges_length + chars_length;
6199
6200             /* match with char_class?  */
6201             for (i = 0; i < char_class_length ; i += CHAR_CLASS_SIZE)
6202               {
6203                 wctype_t wctype;
6204                 uintptr_t alignedp = ((uintptr_t)workp
6205                                       + __alignof__(wctype_t) - 1)
6206                                       & ~(uintptr_t)(__alignof__(wctype_t) - 1);
6207                 wctype = *((wctype_t*)alignedp);
6208                 workp += CHAR_CLASS_SIZE;
6209 # ifdef _LIBC
6210                 if (__iswctype((wint_t)c, wctype))
6211                   goto char_set_matched;
6212 # else
6213                 if (iswctype((wint_t)c, wctype))
6214                   goto char_set_matched;
6215 # endif
6216               }
6217
6218             /* match with collating_symbol?  */
6219 # ifdef _LIBC
6220             if (nrules != 0)
6221               {
6222                 const unsigned char *extra = (const unsigned char *)
6223                   _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
6224
6225                 for (workp2 = workp + coll_symbol_length ; workp < workp2 ;
6226                      workp++)
6227                   {
6228                     int32_t *wextra;
6229                     wextra = (int32_t*)(extra + *workp++);
6230                     for (i = 0; i < *wextra; ++i)
6231                       if (TRANSLATE(d[i]) != wextra[1 + i])
6232                         break;
6233
6234                     if (i == *wextra)
6235                       {
6236                         /* Update d, however d will be incremented at
6237                            char_set_matched:, we decrement d here.  */
6238                         d += i - 1;
6239                         goto char_set_matched;
6240                       }
6241                   }
6242               }
6243             else /* (nrules == 0) */
6244 # endif
6245               /* If we can't look up collation data, we use wcscoll
6246                  instead.  */
6247               {
6248                 for (workp2 = workp + coll_symbol_length ; workp < workp2 ;)
6249                   {
6250                     const CHAR_T *backup_d = d, *backup_dend = dend;
6251 # ifdef _LIBC
6252                     length = __wcslen (workp);
6253 # else
6254                     length = wcslen (workp);
6255 # endif
6256
6257                     /* If wcscoll(the collating symbol, whole string) > 0,
6258                        any substring of the string never match with the
6259                        collating symbol.  */
6260 # ifdef _LIBC
6261                     if (__wcscoll (workp, d) > 0)
6262 # else
6263                     if (wcscoll (workp, d) > 0)
6264 # endif
6265                       {
6266                         workp += length + 1;
6267                         continue;
6268                       }
6269
6270                     /* First, we compare the collating symbol with
6271                        the first character of the string.
6272                        If it don't match, we add the next character to
6273                        the compare buffer in turn.  */
6274                     for (i = 0 ; i < WORK_BUFFER_SIZE-1 ; i++, d++)
6275                       {
6276                         int match;
6277                         if (d == dend)
6278                           {
6279                             if (dend == end_match_2)
6280                               break;
6281                             d = string2;
6282                             dend = end_match_2;
6283                           }
6284
6285                         /* add next character to the compare buffer.  */
6286                         str_buf[i] = TRANSLATE(*d);
6287                         str_buf[i+1] = '\0';
6288
6289 # ifdef _LIBC
6290                         match = __wcscoll (workp, str_buf);
6291 # else
6292                         match = wcscoll (workp, str_buf);
6293 # endif
6294                         if (match == 0)
6295                           goto char_set_matched;
6296
6297                         if (match < 0)
6298                           /* (str_buf > workp) indicate (str_buf + X > workp),
6299                              because for all X (str_buf + X > str_buf).
6300                              So we don't need continue this loop.  */
6301                           break;
6302
6303                         /* Otherwise(str_buf < workp),
6304                            (str_buf+next_character) may equals (workp).
6305                            So we continue this loop.  */
6306                       }
6307                     /* not matched */
6308                     d = backup_d;
6309                     dend = backup_dend;
6310                     workp += length + 1;
6311                   }
6312               }
6313             /* match with equivalence_class?  */
6314 # ifdef _LIBC
6315             if (nrules != 0)
6316               {
6317                 const CHAR_T *backup_d = d, *backup_dend = dend;
6318                 /* Try to match the equivalence class against
6319                    those known to the collate implementation.  */
6320                 const int32_t *table;
6321                 const int32_t *weights;
6322                 const int32_t *extra;
6323                 const int32_t *indirect;
6324                 int32_t idx, idx2;
6325                 wint_t *cp;
6326                 size_t len;
6327
6328                 /* This #include defines a local function!  */
6329 #  include <locale/weightwc.h>
6330
6331                 table = (const int32_t *)
6332                   _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEWC);
6333                 weights = (const wint_t *)
6334                   _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTWC);
6335                 extra = (const wint_t *)
6336                   _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAWC);
6337                 indirect = (const int32_t *)
6338                   _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTWC);
6339
6340                 /* Write 1 collating element to str_buf, and
6341                    get its index.  */
6342                 idx2 = 0;
6343
6344                 for (i = 0 ; idx2 == 0 && i < WORK_BUFFER_SIZE - 1; i++)
6345                   {
6346                     cp = (wint_t*)str_buf;
6347                     if (d == dend)
6348                       {
6349                         if (dend == end_match_2)
6350                           break;
6351                         d = string2;
6352                         dend = end_match_2;
6353                       }
6354                     str_buf[i] = TRANSLATE(*(d+i));
6355                     str_buf[i+1] = '\0'; /* sentinel */
6356                     idx2 = findidx ((const wint_t**)&cp);
6357                   }
6358
6359                 /* Update d, however d will be incremented at
6360                    char_set_matched:, we decrement d here.  */
6361                 d = backup_d + ((wchar_t*)cp - (wchar_t*)str_buf - 1);
6362                 if (d >= dend)
6363                   {
6364                     if (dend == end_match_2)
6365                         d = dend;
6366                     else
6367                       {
6368                         d = string2;
6369                         dend = end_match_2;
6370                       }
6371                   }
6372
6373                 len = weights[idx2];
6374
6375                 for (workp2 = workp + equiv_class_length ; workp < workp2 ;
6376                      workp++)
6377                   {
6378                     idx = (int32_t)*workp;
6379                     /* We already checked idx != 0 in regex_compile. */
6380
6381                     if (idx2 != 0 && len == weights[idx])
6382                       {
6383                         int cnt = 0;
6384                         while (cnt < len && (weights[idx + 1 + cnt]
6385                                              == weights[idx2 + 1 + cnt]))
6386                           ++cnt;
6387
6388                         if (cnt == len)
6389                           goto char_set_matched;
6390                       }
6391                   }
6392                 /* not matched */
6393                 d = backup_d;
6394                 dend = backup_dend;
6395               }
6396             else /* (nrules == 0) */
6397 # endif
6398               /* If we can't look up collation data, we use wcscoll
6399                  instead.  */
6400               {
6401                 for (workp2 = workp + equiv_class_length ; workp < workp2 ;)
6402                   {
6403                     const CHAR_T *backup_d = d, *backup_dend = dend;
6404 # ifdef _LIBC
6405                     length = __wcslen (workp);
6406 # else
6407                     length = wcslen (workp);
6408 # endif
6409
6410                     /* If wcscoll(the collating symbol, whole string) > 0,
6411                        any substring of the string never match with the
6412                        collating symbol.  */
6413 # ifdef _LIBC
6414                     if (__wcscoll (workp, d) > 0)
6415 # else
6416                     if (wcscoll (workp, d) > 0)
6417 # endif
6418                       {
6419                         workp += length + 1;
6420                         break;
6421                       }
6422
6423                     /* First, we compare the equivalence class with
6424                        the first character of the string.
6425                        If it don't match, we add the next character to
6426                        the compare buffer in turn.  */
6427                     for (i = 0 ; i < WORK_BUFFER_SIZE - 1 ; i++, d++)
6428                       {
6429                         int match;
6430                         if (d == dend)
6431                           {
6432                             if (dend == end_match_2)
6433                               break;
6434                             d = string2;
6435                             dend = end_match_2;
6436                           }
6437
6438                         /* add next character to the compare buffer.  */
6439                         str_buf[i] = TRANSLATE(*d);
6440                         str_buf[i+1] = '\0';
6441
6442 # ifdef _LIBC
6443                         match = __wcscoll (workp, str_buf);
6444 # else
6445                         match = wcscoll (workp, str_buf);
6446 # endif
6447
6448                         if (match == 0)
6449                           goto char_set_matched;
6450
6451                         if (match < 0)
6452                         /* (str_buf > workp) indicate (str_buf + X > workp),
6453                            because for all X (str_buf + X > str_buf).
6454                            So we don't need continue this loop.  */
6455                           break;
6456
6457                         /* Otherwise(str_buf < workp),
6458                            (str_buf+next_character) may equals (workp).
6459                            So we continue this loop.  */
6460                       }
6461                     /* not matched */
6462                     d = backup_d;
6463                     dend = backup_dend;
6464                     workp += length + 1;
6465                   }
6466               }
6467
6468             /* match with char_range?  */
6469 # ifdef _LIBC
6470             if (nrules != 0)
6471               {
6472                 uint32_t collseqval;
6473                 const char *collseq = (const char *)
6474                   _NL_CURRENT(LC_COLLATE, _NL_COLLATE_COLLSEQWC);
6475
6476                 collseqval = collseq_table_lookup (collseq, c);
6477
6478                 for (; workp < p - chars_length ;)
6479                   {
6480                     uint32_t start_val, end_val;
6481
6482                     /* We already compute the collation sequence value
6483                        of the characters (or collating symbols).  */
6484                     start_val = (uint32_t) *workp++; /* range_start */
6485                     end_val = (uint32_t) *workp++; /* range_end */
6486
6487                     if (start_val <= collseqval && collseqval <= end_val)
6488                       goto char_set_matched;
6489                   }
6490               }
6491             else
6492 # endif
6493               {
6494                 /* We set range_start_char at str_buf[0], range_end_char
6495                    at str_buf[4], and compared char at str_buf[2].  */
6496                 str_buf[1] = 0;
6497                 str_buf[2] = c;
6498                 str_buf[3] = 0;
6499                 str_buf[5] = 0;
6500                 for (; workp < p - chars_length ;)
6501                   {
6502                     wchar_t *range_start_char, *range_end_char;
6503
6504                     /* match if (range_start_char <= c <= range_end_char).  */
6505
6506                     /* If range_start(or end) < 0, we assume -range_start(end)
6507                        is the offset of the collating symbol which is specified
6508                        as the character of the range start(end).  */
6509
6510                     /* range_start */
6511                     if (*workp < 0)
6512                       range_start_char = charset_top - (*workp++);
6513                     else
6514                       {
6515                         str_buf[0] = *workp++;
6516                         range_start_char = str_buf;
6517                       }
6518
6519                     /* range_end */
6520                     if (*workp < 0)
6521                       range_end_char = charset_top - (*workp++);
6522                     else
6523                       {
6524                         str_buf[4] = *workp++;
6525                         range_end_char = str_buf + 4;
6526                       }
6527
6528 # ifdef _LIBC
6529                     if (__wcscoll (range_start_char, str_buf+2) <= 0
6530                         && __wcscoll (str_buf+2, range_end_char) <= 0)
6531 # else
6532                     if (wcscoll (range_start_char, str_buf+2) <= 0
6533                         && wcscoll (str_buf+2, range_end_char) <= 0)
6534 # endif
6535                       goto char_set_matched;
6536                   }
6537               }
6538
6539             /* match with char?  */
6540             for (; workp < p ; workp++)
6541               if (c == *workp)
6542                 goto char_set_matched;
6543
6544             negate = !negate;
6545
6546           char_set_matched:
6547             if (negate) goto fail;
6548 #else
6549             /* Cast to `unsigned' instead of `unsigned char' in case the
6550                bit list is a full 32 bytes long.  */
6551             if (c < (unsigned) (*p * BYTEWIDTH)
6552                 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
6553               negate = !negate;
6554
6555             p += 1 + *p;
6556
6557             if (!negate) goto fail;
6558 #undef WORK_BUFFER_SIZE
6559 #endif /* WCHAR */
6560             SET_REGS_MATCHED ();
6561             d++;
6562             break;
6563           }
6564
6565
6566         /* The beginning of a group is represented by start_memory.
6567            The arguments are the register number in the next byte, and the
6568            number of groups inner to this one in the next.  The text
6569            matched within the group is recorded (in the internal
6570            registers data structure) under the register number.  */
6571         case start_memory:
6572           DEBUG_PRINT3 ("EXECUTING start_memory %ld (%ld):\n",
6573                         (long int) *p, (long int) p[1]);
6574
6575           /* Find out if this group can match the empty string.  */
6576           p1 = p;               /* To send to group_match_null_string_p.  */
6577
6578           if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
6579             REG_MATCH_NULL_STRING_P (reg_info[*p])
6580               = PREFIX(group_match_null_string_p) (&p1, pend, reg_info);
6581
6582           /* Save the position in the string where we were the last time
6583              we were at this open-group operator in case the group is
6584              operated upon by a repetition operator, e.g., with `(a*)*b'
6585              against `ab'; then we want to ignore where we are now in
6586              the string in case this attempt to match fails.  */
6587           old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6588                              ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
6589                              : regstart[*p];
6590           DEBUG_PRINT2 ("  old_regstart: %d\n",
6591                          POINTER_TO_OFFSET (old_regstart[*p]));
6592
6593           regstart[*p] = d;
6594           DEBUG_PRINT2 ("  regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
6595
6596           IS_ACTIVE (reg_info[*p]) = 1;
6597           MATCHED_SOMETHING (reg_info[*p]) = 0;
6598
6599           /* Clear this whenever we change the register activity status.  */
6600           set_regs_matched_done = 0;
6601
6602           /* This is the new highest active register.  */
6603           highest_active_reg = *p;
6604
6605           /* If nothing was active before, this is the new lowest active
6606              register.  */
6607           if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6608             lowest_active_reg = *p;
6609
6610           /* Move past the register number and inner group count.  */
6611           p += 2;
6612           just_past_start_mem = p;
6613
6614           break;
6615
6616
6617         /* The stop_memory opcode represents the end of a group.  Its
6618            arguments are the same as start_memory's: the register
6619            number, and the number of inner groups.  */
6620         case stop_memory:
6621           DEBUG_PRINT3 ("EXECUTING stop_memory %ld (%ld):\n",
6622                         (long int) *p, (long int) p[1]);
6623
6624           /* We need to save the string position the last time we were at
6625              this close-group operator in case the group is operated
6626              upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
6627              against `aba'; then we want to ignore where we are now in
6628              the string in case this attempt to match fails.  */
6629           old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6630                            ? REG_UNSET (regend[*p]) ? d : regend[*p]
6631                            : regend[*p];
6632           DEBUG_PRINT2 ("      old_regend: %d\n",
6633                          POINTER_TO_OFFSET (old_regend[*p]));
6634
6635           regend[*p] = d;
6636           DEBUG_PRINT2 ("      regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
6637
6638           /* This register isn't active anymore.  */
6639           IS_ACTIVE (reg_info[*p]) = 0;
6640
6641           /* Clear this whenever we change the register activity status.  */
6642           set_regs_matched_done = 0;
6643
6644           /* If this was the only register active, nothing is active
6645              anymore.  */
6646           if (lowest_active_reg == highest_active_reg)
6647             {
6648               lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6649               highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6650             }
6651           else
6652             { /* We must scan for the new highest active register, since
6653                  it isn't necessarily one less than now: consider
6654                  (a(b)c(d(e)f)g).  When group 3 ends, after the f), the
6655                  new highest active register is 1.  */
6656               UCHAR_T r = *p - 1;
6657               while (r > 0 && !IS_ACTIVE (reg_info[r]))
6658                 r--;
6659
6660               /* If we end up at register zero, that means that we saved
6661                  the registers as the result of an `on_failure_jump', not
6662                  a `start_memory', and we jumped to past the innermost
6663                  `stop_memory'.  For example, in ((.)*) we save
6664                  registers 1 and 2 as a result of the *, but when we pop
6665                  back to the second ), we are at the stop_memory 1.
6666                  Thus, nothing is active.  */
6667               if (r == 0)
6668                 {
6669                   lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6670                   highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6671                 }
6672               else
6673                 highest_active_reg = r;
6674             }
6675
6676           /* If just failed to match something this time around with a
6677              group that's operated on by a repetition operator, try to
6678              force exit from the ``loop'', and restore the register
6679              information for this group that we had before trying this
6680              last match.  */
6681           if ((!MATCHED_SOMETHING (reg_info[*p])
6682                || just_past_start_mem == p - 1)
6683               && (p + 2) < pend)
6684             {
6685               boolean is_a_jump_n = false;
6686
6687               p1 = p + 2;
6688               mcnt = 0;
6689               switch ((re_opcode_t) *p1++)
6690                 {
6691                   case jump_n:
6692                     is_a_jump_n = true;
6693                   case pop_failure_jump:
6694                   case maybe_pop_jump:
6695                   case jump:
6696                   case dummy_failure_jump:
6697                     EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6698                     if (is_a_jump_n)
6699                       p1 += OFFSET_ADDRESS_SIZE;
6700                     break;
6701
6702                   default:
6703                     /* do nothing */ ;
6704                 }
6705               p1 += mcnt;
6706
6707               /* If the next operation is a jump backwards in the pattern
6708                  to an on_failure_jump right before the start_memory
6709                  corresponding to this stop_memory, exit from the loop
6710                  by forcing a failure after pushing on the stack the
6711                  on_failure_jump's jump in the pattern, and d.  */
6712               if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
6713                   && (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == start_memory
6714                   && p1[2+OFFSET_ADDRESS_SIZE] == *p)
6715                 {
6716                   /* If this group ever matched anything, then restore
6717                      what its registers were before trying this last
6718                      failed match, e.g., with `(a*)*b' against `ab' for
6719                      regstart[1], and, e.g., with `((a*)*(b*)*)*'
6720                      against `aba' for regend[3].
6721
6722                      Also restore the registers for inner groups for,
6723                      e.g., `((a*)(b*))*' against `aba' (register 3 would
6724                      otherwise get trashed).  */
6725
6726                   if (EVER_MATCHED_SOMETHING (reg_info[*p]))
6727                     {
6728                       unsigned r;
6729
6730                       EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
6731
6732                       /* Restore this and inner groups' (if any) registers.  */
6733                       for (r = *p; r < (unsigned) *p + (unsigned) *(p + 1);
6734                            r++)
6735                         {
6736                           regstart[r] = old_regstart[r];
6737
6738                           /* xx why this test?  */
6739                           if (old_regend[r] >= regstart[r])
6740                             regend[r] = old_regend[r];
6741                         }
6742                     }
6743                   p1++;
6744                   EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6745                   PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
6746
6747                   goto fail;
6748                 }
6749             }
6750
6751           /* Move past the register number and the inner group count.  */
6752           p += 2;
6753           break;
6754
6755
6756         /* \<digit> has been turned into a `duplicate' command which is
6757            followed by the numeric value of <digit> as the register number.  */
6758         case duplicate:
6759           {
6760             register const CHAR_T *d2, *dend2;
6761             int regno = *p++;   /* Get which register to match against.  */
6762             DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
6763
6764             /* Can't back reference a group which we've never matched.  */
6765             if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
6766               goto fail;
6767
6768             /* Where in input to try to start matching.  */
6769             d2 = regstart[regno];
6770
6771             /* Where to stop matching; if both the place to start and
6772                the place to stop matching are in the same string, then
6773                set to the place to stop, otherwise, for now have to use
6774                the end of the first string.  */
6775
6776             dend2 = ((FIRST_STRING_P (regstart[regno])
6777                       == FIRST_STRING_P (regend[regno]))
6778                      ? regend[regno] : end_match_1);
6779             for (;;)
6780               {
6781                 /* If necessary, advance to next segment in register
6782                    contents.  */
6783                 while (d2 == dend2)
6784                   {
6785                     if (dend2 == end_match_2) break;
6786                     if (dend2 == regend[regno]) break;
6787
6788                     /* End of string1 => advance to string2. */
6789                     d2 = string2;
6790                     dend2 = regend[regno];
6791                   }
6792                 /* At end of register contents => success */
6793                 if (d2 == dend2) break;
6794
6795                 /* If necessary, advance to next segment in data.  */
6796                 PREFETCH ();
6797
6798                 /* How many characters left in this segment to match.  */
6799                 mcnt = dend - d;
6800
6801                 /* Want how many consecutive characters we can match in
6802                    one shot, so, if necessary, adjust the count.  */
6803                 if (mcnt > dend2 - d2)
6804                   mcnt = dend2 - d2;
6805
6806                 /* Compare that many; failure if mismatch, else move
6807                    past them.  */
6808                 if (translate
6809                     ? PREFIX(bcmp_translate) (d, d2, mcnt, translate)
6810                     : memcmp (d, d2, mcnt*sizeof(UCHAR_T)))
6811                   goto fail;
6812                 d += mcnt, d2 += mcnt;
6813
6814                 /* Do this because we've match some characters.  */
6815                 SET_REGS_MATCHED ();
6816               }
6817           }
6818           break;
6819
6820
6821         /* begline matches the empty string at the beginning of the string
6822            (unless `not_bol' is set in `bufp'), and, if
6823            `newline_anchor' is set, after newlines.  */
6824         case begline:
6825           DEBUG_PRINT1 ("EXECUTING begline.\n");
6826
6827           if (AT_STRINGS_BEG (d))
6828             {
6829               if (!bufp->not_bol) break;
6830             }
6831           else if (d[-1] == '\n' && bufp->newline_anchor)
6832             {
6833               break;
6834             }
6835           /* In all other cases, we fail.  */
6836           goto fail;
6837
6838
6839         /* endline is the dual of begline.  */
6840         case endline:
6841           DEBUG_PRINT1 ("EXECUTING endline.\n");
6842
6843           if (AT_STRINGS_END (d))
6844             {
6845               if (!bufp->not_eol) break;
6846             }
6847
6848           /* We have to ``prefetch'' the next character.  */
6849           else if ((d == end1 ? *string2 : *d) == '\n'
6850                    && bufp->newline_anchor)
6851             {
6852               break;
6853             }
6854           goto fail;
6855
6856
6857         /* Match at the very beginning of the data.  */
6858         case begbuf:
6859           DEBUG_PRINT1 ("EXECUTING begbuf.\n");
6860           if (AT_STRINGS_BEG (d))
6861             break;
6862           goto fail;
6863
6864
6865         /* Match at the very end of the data.  */
6866         case endbuf:
6867           DEBUG_PRINT1 ("EXECUTING endbuf.\n");
6868           if (AT_STRINGS_END (d))
6869             break;
6870           goto fail;
6871
6872
6873         /* on_failure_keep_string_jump is used to optimize `.*\n'.  It
6874            pushes NULL as the value for the string on the stack.  Then
6875            `pop_failure_point' will keep the current value for the
6876            string, instead of restoring it.  To see why, consider
6877            matching `foo\nbar' against `.*\n'.  The .* matches the foo;
6878            then the . fails against the \n.  But the next thing we want
6879            to do is match the \n against the \n; if we restored the
6880            string value, we would be back at the foo.
6881
6882            Because this is used only in specific cases, we don't need to
6883            check all the things that `on_failure_jump' does, to make
6884            sure the right things get saved on the stack.  Hence we don't
6885            share its code.  The only reason to push anything on the
6886            stack at all is that otherwise we would have to change
6887            `anychar's code to do something besides goto fail in this
6888            case; that seems worse than this.  */
6889         case on_failure_keep_string_jump:
6890           DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
6891
6892           EXTRACT_NUMBER_AND_INCR (mcnt, p);
6893 #ifdef _LIBC
6894           DEBUG_PRINT3 (" %d (to %p):\n", mcnt, p + mcnt);
6895 #else
6896           DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
6897 #endif
6898
6899           PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
6900           break;
6901
6902
6903         /* Uses of on_failure_jump:
6904
6905            Each alternative starts with an on_failure_jump that points
6906            to the beginning of the next alternative.  Each alternative
6907            except the last ends with a jump that in effect jumps past
6908            the rest of the alternatives.  (They really jump to the
6909            ending jump of the following alternative, because tensioning
6910            these jumps is a hassle.)
6911
6912            Repeats start with an on_failure_jump that points past both
6913            the repetition text and either the following jump or
6914            pop_failure_jump back to this on_failure_jump.  */
6915         case on_failure_jump:
6916         on_failure:
6917           DEBUG_PRINT1 ("EXECUTING on_failure_jump");
6918
6919           EXTRACT_NUMBER_AND_INCR (mcnt, p);
6920 #ifdef _LIBC
6921           DEBUG_PRINT3 (" %d (to %p)", mcnt, p + mcnt);
6922 #else
6923           DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
6924 #endif
6925
6926           /* If this on_failure_jump comes right before a group (i.e.,
6927              the original * applied to a group), save the information
6928              for that group and all inner ones, so that if we fail back
6929              to this point, the group's information will be correct.
6930              For example, in \(a*\)*\1, we need the preceding group,
6931              and in \(zz\(a*\)b*\)\2, we need the inner group.  */
6932
6933           /* We can't use `p' to check ahead because we push
6934              a failure point to `p + mcnt' after we do this.  */
6935           p1 = p;
6936
6937           /* We need to skip no_op's before we look for the
6938              start_memory in case this on_failure_jump is happening as
6939              the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
6940              against aba.  */
6941           while (p1 < pend && (re_opcode_t) *p1 == no_op)
6942             p1++;
6943
6944           if (p1 < pend && (re_opcode_t) *p1 == start_memory)
6945             {
6946               /* We have a new highest active register now.  This will
6947                  get reset at the start_memory we are about to get to,
6948                  but we will have saved all the registers relevant to
6949                  this repetition op, as described above.  */
6950               highest_active_reg = *(p1 + 1) + *(p1 + 2);
6951               if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6952                 lowest_active_reg = *(p1 + 1);
6953             }
6954
6955           DEBUG_PRINT1 (":\n");
6956           PUSH_FAILURE_POINT (p + mcnt, d, -2);
6957           break;
6958
6959
6960         /* A smart repeat ends with `maybe_pop_jump'.
6961            We change it to either `pop_failure_jump' or `jump'.  */
6962         case maybe_pop_jump:
6963           EXTRACT_NUMBER_AND_INCR (mcnt, p);
6964           DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
6965           {
6966             register UCHAR_T *p2 = p;
6967
6968             /* Compare the beginning of the repeat with what in the
6969                pattern follows its end. If we can establish that there
6970                is nothing that they would both match, i.e., that we
6971                would have to backtrack because of (as in, e.g., `a*a')
6972                then we can change to pop_failure_jump, because we'll
6973                never have to backtrack.
6974
6975                This is not true in the case of alternatives: in
6976                `(a|ab)*' we do need to backtrack to the `ab' alternative
6977                (e.g., if the string was `ab').  But instead of trying to
6978                detect that here, the alternative has put on a dummy
6979                failure point which is what we will end up popping.  */
6980
6981             /* Skip over open/close-group commands.
6982                If what follows this loop is a ...+ construct,
6983                look at what begins its body, since we will have to
6984                match at least one of that.  */
6985             while (1)
6986               {
6987                 if (p2 + 2 < pend
6988                     && ((re_opcode_t) *p2 == stop_memory
6989                         || (re_opcode_t) *p2 == start_memory))
6990                   p2 += 3;
6991                 else if (p2 + 2 + 2 * OFFSET_ADDRESS_SIZE < pend
6992                          && (re_opcode_t) *p2 == dummy_failure_jump)
6993                   p2 += 2 + 2 * OFFSET_ADDRESS_SIZE;
6994                 else
6995                   break;
6996               }
6997
6998             p1 = p + mcnt;
6999             /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
7000                to the `maybe_finalize_jump' of this case.  Examine what
7001                follows.  */
7002
7003             /* If we're at the end of the pattern, we can change.  */
7004             if (p2 == pend)
7005               {
7006                 /* Consider what happens when matching ":\(.*\)"
7007                    against ":/".  I don't really understand this code
7008                    yet.  */
7009                 p[-(1+OFFSET_ADDRESS_SIZE)] = (UCHAR_T)
7010                   pop_failure_jump;
7011                 DEBUG_PRINT1
7012                   ("  End of pattern: change to `pop_failure_jump'.\n");
7013               }
7014
7015             else if ((re_opcode_t) *p2 == exactn
7016 #ifdef MBS_SUPPORT
7017                      || (re_opcode_t) *p2 == exactn_bin
7018 #endif
7019                      || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
7020               {
7021                 register UCHAR_T c
7022                   = *p2 == (UCHAR_T) endline ? '\n' : p2[2];
7023
7024                 if (((re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn
7025 #ifdef MBS_SUPPORT
7026                      || (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn_bin
7027 #endif
7028                     ) && p1[3+OFFSET_ADDRESS_SIZE] != c)
7029                   {
7030                     p[-(1+OFFSET_ADDRESS_SIZE)] = (UCHAR_T)
7031                       pop_failure_jump;
7032 #ifdef WCHAR
7033                       DEBUG_PRINT3 ("  %C != %C => pop_failure_jump.\n",
7034                                     (wint_t) c,
7035                                     (wint_t) p1[3+OFFSET_ADDRESS_SIZE]);
7036 #else
7037                       DEBUG_PRINT3 ("  %c != %c => pop_failure_jump.\n",
7038                                     (char) c,
7039                                     (char) p1[3+OFFSET_ADDRESS_SIZE]);
7040 #endif
7041                   }
7042
7043 #ifndef WCHAR
7044                 else if ((re_opcode_t) p1[3] == charset
7045                          || (re_opcode_t) p1[3] == charset_not)
7046                   {
7047                     int negate = (re_opcode_t) p1[3] == charset_not;
7048
7049                     if (c < (unsigned) (p1[4] * BYTEWIDTH)
7050                         && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
7051                       negate = !negate;
7052
7053                     /* `negate' is equal to 1 if c would match, which means
7054                         that we can't change to pop_failure_jump.  */
7055                     if (!negate)
7056                       {
7057                         p[-3] = (unsigned char) pop_failure_jump;
7058                         DEBUG_PRINT1 ("  No match => pop_failure_jump.\n");
7059                       }
7060                   }
7061 #endif /* not WCHAR */
7062               }
7063 #ifndef WCHAR
7064             else if ((re_opcode_t) *p2 == charset)
7065               {
7066                 /* We win if the first character of the loop is not part
7067                    of the charset.  */
7068                 if ((re_opcode_t) p1[3] == exactn
7069                     && ! ((int) p2[1] * BYTEWIDTH > (int) p1[5]
7070                           && (p2[2 + p1[5] / BYTEWIDTH]
7071                               & (1 << (p1[5] % BYTEWIDTH)))))
7072                   {
7073                     p[-3] = (unsigned char) pop_failure_jump;
7074                     DEBUG_PRINT1 ("  No match => pop_failure_jump.\n");
7075                   }
7076
7077                 else if ((re_opcode_t) p1[3] == charset_not)
7078                   {
7079                     int idx;
7080                     /* We win if the charset_not inside the loop
7081                        lists every character listed in the charset after.  */
7082                     for (idx = 0; idx < (int) p2[1]; idx++)
7083                       if (! (p2[2 + idx] == 0
7084                              || (idx < (int) p1[4]
7085                                  && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
7086                         break;
7087
7088                     if (idx == p2[1])
7089                       {
7090                         p[-3] = (unsigned char) pop_failure_jump;
7091                         DEBUG_PRINT1 ("  No match => pop_failure_jump.\n");
7092                       }
7093                   }
7094                 else if ((re_opcode_t) p1[3] == charset)
7095                   {
7096                     int idx;
7097                     /* We win if the charset inside the loop
7098                        has no overlap with the one after the loop.  */
7099                     for (idx = 0;
7100                          idx < (int) p2[1] && idx < (int) p1[4];
7101                          idx++)
7102                       if ((p2[2 + idx] & p1[5 + idx]) != 0)
7103                         break;
7104
7105                     if (idx == p2[1] || idx == p1[4])
7106                       {
7107                         p[-3] = (unsigned char) pop_failure_jump;
7108                         DEBUG_PRINT1 ("  No match => pop_failure_jump.\n");
7109                       }
7110                   }
7111               }
7112 #endif /* not WCHAR */
7113           }
7114           p -= OFFSET_ADDRESS_SIZE;     /* Point at relative address again.  */
7115           if ((re_opcode_t) p[-1] != pop_failure_jump)
7116             {
7117               p[-1] = (UCHAR_T) jump;
7118               DEBUG_PRINT1 ("  Match => jump.\n");
7119               goto unconditional_jump;
7120             }
7121         /* Note fall through.  */
7122
7123
7124         /* The end of a simple repeat has a pop_failure_jump back to
7125            its matching on_failure_jump, where the latter will push a
7126            failure point.  The pop_failure_jump takes off failure
7127            points put on by this pop_failure_jump's matching
7128            on_failure_jump; we got through the pattern to here from the
7129            matching on_failure_jump, so didn't fail.  */
7130         case pop_failure_jump:
7131           {
7132             /* We need to pass separate storage for the lowest and
7133                highest registers, even though we don't care about the
7134                actual values.  Otherwise, we will restore only one
7135                register from the stack, since lowest will == highest in
7136                `pop_failure_point'.  */
7137             active_reg_t dummy_low_reg, dummy_high_reg;
7138             UCHAR_T *pdummy = NULL;
7139             const CHAR_T *sdummy = NULL;
7140
7141             DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
7142             POP_FAILURE_POINT (sdummy, pdummy,
7143                                dummy_low_reg, dummy_high_reg,
7144                                reg_dummy, reg_dummy, reg_info_dummy);
7145           }
7146           /* Note fall through.  */
7147
7148         unconditional_jump:
7149 #ifdef _LIBC
7150           DEBUG_PRINT2 ("\n%p: ", p);
7151 #else
7152           DEBUG_PRINT2 ("\n0x%x: ", p);
7153 #endif
7154           /* Note fall through.  */
7155
7156         /* Unconditionally jump (without popping any failure points).  */
7157         case jump:
7158           EXTRACT_NUMBER_AND_INCR (mcnt, p);    /* Get the amount to jump.  */
7159           DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
7160           p += mcnt;                            /* Do the jump.  */
7161 #ifdef _LIBC
7162           DEBUG_PRINT2 ("(to %p).\n", p);
7163 #else
7164           DEBUG_PRINT2 ("(to 0x%x).\n", p);
7165 #endif
7166           break;
7167
7168
7169         /* We need this opcode so we can detect where alternatives end
7170            in `group_match_null_string_p' et al.  */
7171         case jump_past_alt:
7172           DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
7173           goto unconditional_jump;
7174
7175
7176         /* Normally, the on_failure_jump pushes a failure point, which
7177            then gets popped at pop_failure_jump.  We will end up at
7178            pop_failure_jump, also, and with a pattern of, say, `a+', we
7179            are skipping over the on_failure_jump, so we have to push
7180            something meaningless for pop_failure_jump to pop.  */
7181         case dummy_failure_jump:
7182           DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
7183           /* It doesn't matter what we push for the string here.  What
7184              the code at `fail' tests is the value for the pattern.  */
7185           PUSH_FAILURE_POINT (NULL, NULL, -2);
7186           goto unconditional_jump;
7187
7188
7189         /* At the end of an alternative, we need to push a dummy failure
7190            point in case we are followed by a `pop_failure_jump', because
7191            we don't want the failure point for the alternative to be
7192            popped.  For example, matching `(a|ab)*' against `aab'
7193            requires that we match the `ab' alternative.  */
7194         case push_dummy_failure:
7195           DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
7196           /* See comments just above at `dummy_failure_jump' about the
7197              two zeroes.  */
7198           PUSH_FAILURE_POINT (NULL, NULL, -2);
7199           break;
7200
7201         /* Have to succeed matching what follows at least n times.
7202            After that, handle like `on_failure_jump'.  */
7203         case succeed_n:
7204           EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
7205           DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
7206
7207           assert (mcnt >= 0);
7208           /* Originally, this is how many times we HAVE to succeed.  */
7209           if (mcnt > 0)
7210             {
7211                mcnt--;
7212                p += OFFSET_ADDRESS_SIZE;
7213                STORE_NUMBER_AND_INCR (p, mcnt);
7214 #ifdef _LIBC
7215                DEBUG_PRINT3 ("  Setting %p to %d.\n", p - OFFSET_ADDRESS_SIZE
7216                              , mcnt);
7217 #else
7218                DEBUG_PRINT3 ("  Setting 0x%x to %d.\n", p - OFFSET_ADDRESS_SIZE
7219                              , mcnt);
7220 #endif
7221             }
7222           else if (mcnt == 0)
7223             {
7224 #ifdef _LIBC
7225               DEBUG_PRINT2 ("  Setting two bytes from %p to no_op.\n",
7226                             p + OFFSET_ADDRESS_SIZE);
7227 #else
7228               DEBUG_PRINT2 ("  Setting two bytes from 0x%x to no_op.\n",
7229                             p + OFFSET_ADDRESS_SIZE);
7230 #endif /* _LIBC */
7231
7232 #ifdef WCHAR
7233               p[1] = (UCHAR_T) no_op;
7234 #else
7235               p[2] = (UCHAR_T) no_op;
7236               p[3] = (UCHAR_T) no_op;
7237 #endif /* WCHAR */
7238               goto on_failure;
7239             }
7240           break;
7241
7242         case jump_n:
7243           EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
7244           DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
7245
7246           /* Originally, this is how many times we CAN jump.  */
7247           if (mcnt)
7248             {
7249                mcnt--;
7250                STORE_NUMBER (p + OFFSET_ADDRESS_SIZE, mcnt);
7251
7252 #ifdef _LIBC
7253                DEBUG_PRINT3 ("  Setting %p to %d.\n", p + OFFSET_ADDRESS_SIZE,
7254                              mcnt);
7255 #else
7256                DEBUG_PRINT3 ("  Setting 0x%x to %d.\n", p + OFFSET_ADDRESS_SIZE,
7257                              mcnt);
7258 #endif /* _LIBC */
7259                goto unconditional_jump;
7260             }
7261           /* If don't have to jump any more, skip over the rest of command.  */
7262           else
7263             p += 2 * OFFSET_ADDRESS_SIZE;
7264           break;
7265
7266         case set_number_at:
7267           {
7268             DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
7269
7270             EXTRACT_NUMBER_AND_INCR (mcnt, p);
7271             p1 = p + mcnt;
7272             EXTRACT_NUMBER_AND_INCR (mcnt, p);
7273 #ifdef _LIBC
7274             DEBUG_PRINT3 ("  Setting %p to %d.\n", p1, mcnt);
7275 #else
7276             DEBUG_PRINT3 ("  Setting 0x%x to %d.\n", p1, mcnt);
7277 #endif
7278             STORE_NUMBER (p1, mcnt);
7279             break;
7280           }
7281
7282 #if 0
7283         /* The DEC Alpha C compiler 3.x generates incorrect code for the
7284            test  WORDCHAR_P (d - 1) != WORDCHAR_P (d)  in the expansion of
7285            AT_WORD_BOUNDARY, so this code is disabled.  Expanding the
7286            macro and introducing temporary variables works around the bug.  */
7287
7288         case wordbound:
7289           DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7290           if (AT_WORD_BOUNDARY (d))
7291             break;
7292           goto fail;
7293
7294         case notwordbound:
7295           DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7296           if (AT_WORD_BOUNDARY (d))
7297             goto fail;
7298           break;
7299 #else
7300         case wordbound:
7301         {
7302           boolean prevchar, thischar;
7303
7304           DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7305           if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7306             break;
7307
7308           prevchar = WORDCHAR_P (d - 1);
7309           thischar = WORDCHAR_P (d);
7310           if (prevchar != thischar)
7311             break;
7312           goto fail;
7313         }
7314
7315       case notwordbound:
7316         {
7317           boolean prevchar, thischar;
7318
7319           DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7320           if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7321             goto fail;
7322
7323           prevchar = WORDCHAR_P (d - 1);
7324           thischar = WORDCHAR_P (d);
7325           if (prevchar != thischar)
7326             goto fail;
7327           break;
7328         }
7329 #endif
7330
7331         case wordbeg:
7332           DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
7333           if (!AT_STRINGS_END (d) && WORDCHAR_P (d)
7334               && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
7335             break;
7336           goto fail;
7337
7338         case wordend:
7339           DEBUG_PRINT1 ("EXECUTING wordend.\n");
7340           if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
7341               && (AT_STRINGS_END (d) || !WORDCHAR_P (d)))
7342             break;
7343           goto fail;
7344
7345 #ifdef emacs
7346         case before_dot:
7347           DEBUG_PRINT1 ("EXECUTING before_dot.\n");
7348           if (PTR_CHAR_POS ((unsigned char *) d) >= point)
7349             goto fail;
7350           break;
7351
7352         case at_dot:
7353           DEBUG_PRINT1 ("EXECUTING at_dot.\n");
7354           if (PTR_CHAR_POS ((unsigned char *) d) != point)
7355             goto fail;
7356           break;
7357
7358         case after_dot:
7359           DEBUG_PRINT1 ("EXECUTING after_dot.\n");
7360           if (PTR_CHAR_POS ((unsigned char *) d) <= point)
7361             goto fail;
7362           break;
7363
7364         case syntaxspec:
7365           DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
7366           mcnt = *p++;
7367           goto matchsyntax;
7368
7369         case wordchar:
7370           DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
7371           mcnt = (int) Sword;
7372         matchsyntax:
7373           PREFETCH ();
7374           /* Can't use *d++ here; SYNTAX may be an unsafe macro.  */
7375           d++;
7376           if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt)
7377             goto fail;
7378           SET_REGS_MATCHED ();
7379           break;
7380
7381         case notsyntaxspec:
7382           DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
7383           mcnt = *p++;
7384           goto matchnotsyntax;
7385
7386         case notwordchar:
7387           DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
7388           mcnt = (int) Sword;
7389         matchnotsyntax:
7390           PREFETCH ();
7391           /* Can't use *d++ here; SYNTAX may be an unsafe macro.  */
7392           d++;
7393           if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt)
7394             goto fail;
7395           SET_REGS_MATCHED ();
7396           break;
7397
7398 #else /* not emacs */
7399         case wordchar:
7400           DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
7401           PREFETCH ();
7402           if (!WORDCHAR_P (d))
7403             goto fail;
7404           SET_REGS_MATCHED ();
7405           d++;
7406           break;
7407
7408         case notwordchar:
7409           DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
7410           PREFETCH ();
7411           if (WORDCHAR_P (d))
7412             goto fail;
7413           SET_REGS_MATCHED ();
7414           d++;
7415           break;
7416 #endif /* not emacs */
7417
7418         default:
7419           abort ();
7420         }
7421       continue;  /* Successfully executed one pattern command; keep going.  */
7422
7423
7424     /* We goto here if a matching operation fails. */
7425     fail:
7426       if (!FAIL_STACK_EMPTY ())
7427         { /* A restart point is known.  Restore to that state.  */
7428           DEBUG_PRINT1 ("\nFAIL:\n");
7429           POP_FAILURE_POINT (d, p,
7430                              lowest_active_reg, highest_active_reg,
7431                              regstart, regend, reg_info);
7432
7433           /* If this failure point is a dummy, try the next one.  */
7434           if (!p)
7435             goto fail;
7436
7437           /* If we failed to the end of the pattern, don't examine *p.  */
7438           assert (p <= pend);
7439           if (p < pend)
7440             {
7441               boolean is_a_jump_n = false;
7442
7443               /* If failed to a backwards jump that's part of a repetition
7444                  loop, need to pop this failure point and use the next one.  */
7445               switch ((re_opcode_t) *p)
7446                 {
7447                 case jump_n:
7448                   is_a_jump_n = true;
7449                 case maybe_pop_jump:
7450                 case pop_failure_jump:
7451                 case jump:
7452                   p1 = p + 1;
7453                   EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7454                   p1 += mcnt;
7455
7456                   if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
7457                       || (!is_a_jump_n
7458                           && (re_opcode_t) *p1 == on_failure_jump))
7459                     goto fail;
7460                   break;
7461                 default:
7462                   /* do nothing */ ;
7463                 }
7464             }
7465
7466           if (d >= string1 && d <= end1)
7467             dend = end_match_1;
7468         }
7469       else
7470         break;   /* Matching at this starting point really fails.  */
7471     } /* for (;;) */
7472
7473   if (best_regs_set)
7474     goto restore_best_regs;
7475
7476   FREE_VARIABLES ();
7477
7478   return -1;                            /* Failure to match.  */
7479 } /* re_match_2 */
7480 \f
7481 /* Subroutine definitions for re_match_2.  */
7482
7483
7484 /* We are passed P pointing to a register number after a start_memory.
7485
7486    Return true if the pattern up to the corresponding stop_memory can
7487    match the empty string, and false otherwise.
7488
7489    If we find the matching stop_memory, sets P to point to one past its number.
7490    Otherwise, sets P to an undefined byte less than or equal to END.
7491
7492    We don't handle duplicates properly (yet).  */
7493
7494 static boolean
7495 PREFIX(group_match_null_string_p) (UCHAR_T **p, UCHAR_T *end,
7496                                    PREFIX(register_info_type) *reg_info)
7497 {
7498   int mcnt;
7499   /* Point to after the args to the start_memory.  */
7500   UCHAR_T *p1 = *p + 2;
7501
7502   while (p1 < end)
7503     {
7504       /* Skip over opcodes that can match nothing, and return true or
7505          false, as appropriate, when we get to one that can't, or to the
7506          matching stop_memory.  */
7507
7508       switch ((re_opcode_t) *p1)
7509         {
7510         /* Could be either a loop or a series of alternatives.  */
7511         case on_failure_jump:
7512           p1++;
7513           EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7514
7515           /* If the next operation is not a jump backwards in the
7516              pattern.  */
7517
7518           if (mcnt >= 0)
7519             {
7520               /* Go through the on_failure_jumps of the alternatives,
7521                  seeing if any of the alternatives cannot match nothing.
7522                  The last alternative starts with only a jump,
7523                  whereas the rest start with on_failure_jump and end
7524                  with a jump, e.g., here is the pattern for `a|b|c':
7525
7526                  /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
7527                  /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
7528                  /exactn/1/c
7529
7530                  So, we have to first go through the first (n-1)
7531                  alternatives and then deal with the last one separately.  */
7532
7533
7534               /* Deal with the first (n-1) alternatives, which start
7535                  with an on_failure_jump (see above) that jumps to right
7536                  past a jump_past_alt.  */
7537
7538               while ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] ==
7539                      jump_past_alt)
7540                 {
7541                   /* `mcnt' holds how many bytes long the alternative
7542                      is, including the ending `jump_past_alt' and
7543                      its number.  */
7544
7545                   if (!PREFIX(alt_match_null_string_p) (p1, p1 + mcnt -
7546                                                 (1 + OFFSET_ADDRESS_SIZE),
7547                                                 reg_info))
7548                     return false;
7549
7550                   /* Move to right after this alternative, including the
7551                      jump_past_alt.  */
7552                   p1 += mcnt;
7553
7554                   /* Break if it's the beginning of an n-th alternative
7555                      that doesn't begin with an on_failure_jump.  */
7556                   if ((re_opcode_t) *p1 != on_failure_jump)
7557                     break;
7558
7559                   /* Still have to check that it's not an n-th
7560                      alternative that starts with an on_failure_jump.  */
7561                   p1++;
7562                   EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7563                   if ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] !=
7564                       jump_past_alt)
7565                     {
7566                       /* Get to the beginning of the n-th alternative.  */
7567                       p1 -= 1 + OFFSET_ADDRESS_SIZE;
7568                       break;
7569                     }
7570                 }
7571
7572               /* Deal with the last alternative: go back and get number
7573                  of the `jump_past_alt' just before it.  `mcnt' contains
7574                  the length of the alternative.  */
7575               EXTRACT_NUMBER (mcnt, p1 - OFFSET_ADDRESS_SIZE);
7576
7577               if (!PREFIX(alt_match_null_string_p) (p1, p1 + mcnt, reg_info))
7578                 return false;
7579
7580               p1 += mcnt;       /* Get past the n-th alternative.  */
7581             } /* if mcnt > 0 */
7582           break;
7583
7584
7585         case stop_memory:
7586           assert (p1[1] == **p);
7587           *p = p1 + 2;
7588           return true;
7589
7590
7591         default:
7592           if (!PREFIX(common_op_match_null_string_p) (&p1, end, reg_info))
7593             return false;
7594         }
7595     } /* while p1 < end */
7596
7597   return false;
7598 } /* group_match_null_string_p */
7599
7600
7601 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
7602    It expects P to be the first byte of a single alternative and END one
7603    byte past the last. The alternative can contain groups.  */
7604
7605 static boolean
7606 PREFIX(alt_match_null_string_p) (UCHAR_T *p, UCHAR_T *end,
7607                                  PREFIX(register_info_type) *reg_info)
7608 {
7609   int mcnt;
7610   UCHAR_T *p1 = p;
7611
7612   while (p1 < end)
7613     {
7614       /* Skip over opcodes that can match nothing, and break when we get
7615          to one that can't.  */
7616
7617       switch ((re_opcode_t) *p1)
7618         {
7619         /* It's a loop.  */
7620         case on_failure_jump:
7621           p1++;
7622           EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7623           p1 += mcnt;
7624           break;
7625
7626         default:
7627           if (!PREFIX(common_op_match_null_string_p) (&p1, end, reg_info))
7628             return false;
7629         }
7630     }  /* while p1 < end */
7631
7632   return true;
7633 } /* alt_match_null_string_p */
7634
7635
7636 /* Deals with the ops common to group_match_null_string_p and
7637    alt_match_null_string_p.
7638
7639    Sets P to one after the op and its arguments, if any.  */
7640
7641 static boolean
7642 PREFIX(common_op_match_null_string_p) (UCHAR_T **p, UCHAR_T *end,
7643                                        PREFIX(register_info_type) *reg_info)
7644 {
7645   int mcnt;
7646   boolean ret;
7647   int reg_no;
7648   UCHAR_T *p1 = *p;
7649
7650   switch ((re_opcode_t) *p1++)
7651     {
7652     case no_op:
7653     case begline:
7654     case endline:
7655     case begbuf:
7656     case endbuf:
7657     case wordbeg:
7658     case wordend:
7659     case wordbound:
7660     case notwordbound:
7661 #ifdef emacs
7662     case before_dot:
7663     case at_dot:
7664     case after_dot:
7665 #endif
7666       break;
7667
7668     case start_memory:
7669       reg_no = *p1;
7670       assert (reg_no > 0 && reg_no <= MAX_REGNUM);
7671       ret = PREFIX(group_match_null_string_p) (&p1, end, reg_info);
7672
7673       /* Have to set this here in case we're checking a group which
7674          contains a group and a back reference to it.  */
7675
7676       if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
7677         REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
7678
7679       if (!ret)
7680         return false;
7681       break;
7682
7683     /* If this is an optimized succeed_n for zero times, make the jump.  */
7684     case jump:
7685       EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7686       if (mcnt >= 0)
7687         p1 += mcnt;
7688       else
7689         return false;
7690       break;
7691
7692     case succeed_n:
7693       /* Get to the number of times to succeed.  */
7694       p1 += OFFSET_ADDRESS_SIZE;
7695       EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7696
7697       if (mcnt == 0)
7698         {
7699           p1 -= 2 * OFFSET_ADDRESS_SIZE;
7700           EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7701           p1 += mcnt;
7702         }
7703       else
7704         return false;
7705       break;
7706
7707     case duplicate:
7708       if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
7709         return false;
7710       break;
7711
7712     case set_number_at:
7713       p1 += 2 * OFFSET_ADDRESS_SIZE;
7714
7715     default:
7716       /* All other opcodes mean we cannot match the empty string.  */
7717       return false;
7718   }
7719
7720   *p = p1;
7721   return true;
7722 } /* common_op_match_null_string_p */
7723
7724
7725 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
7726    bytes; nonzero otherwise.  */
7727
7728 static int
7729 PREFIX(bcmp_translate) (const CHAR_T *s1, const CHAR_T *s2, register int len,
7730                         RE_TRANSLATE_TYPE translate)
7731 {
7732   register const UCHAR_T *p1 = (const UCHAR_T *) s1;
7733   register const UCHAR_T *p2 = (const UCHAR_T *) s2;
7734   while (len)
7735     {
7736 #ifdef WCHAR
7737       if (((*p1<=0xff)?translate[*p1++]:*p1++)
7738           != ((*p2<=0xff)?translate[*p2++]:*p2++))
7739         return 1;
7740 #else /* BYTE */
7741       if (translate[*p1++] != translate[*p2++]) return 1;
7742 #endif /* WCHAR */
7743       len--;
7744     }
7745   return 0;
7746 }
7747 \f
7748
7749 #else /* not INSIDE_RECURSION */
7750
7751 /* Entry points for GNU code.  */
7752
7753 /* re_compile_pattern is the GNU regular expression compiler: it
7754    compiles PATTERN (of length SIZE) and puts the result in BUFP.
7755    Returns 0 if the pattern was valid, otherwise an error string.
7756
7757    Assumes the `allocated' (and perhaps `buffer') and `translate' fields
7758    are set in BUFP on entry.
7759
7760    We call regex_compile to do the actual compilation.  */
7761
7762 const char *
7763 re_compile_pattern (const char *pattern, size_t length,
7764                     struct re_pattern_buffer *bufp)
7765 {
7766   reg_errcode_t ret;
7767
7768   /* GNU code is written to assume at least RE_NREGS registers will be set
7769      (and at least one extra will be -1).  */
7770   bufp->regs_allocated = REGS_UNALLOCATED;
7771
7772   /* And GNU code determines whether or not to get register information
7773      by passing null for the REGS argument to re_match, etc., not by
7774      setting no_sub.  */
7775   bufp->no_sub = 0;
7776
7777   /* Match anchors at newline.  */
7778   bufp->newline_anchor = 1;
7779
7780 # ifdef MBS_SUPPORT
7781   if (MB_CUR_MAX != 1)
7782     ret = wcs_regex_compile (pattern, length, re_syntax_options, bufp);
7783   else
7784 # endif
7785     ret = byte_regex_compile (pattern, length, re_syntax_options, bufp);
7786
7787   if (!ret)
7788     return NULL;
7789   return gettext (re_error_msgid[(int) ret]);
7790 }
7791 #ifdef _LIBC
7792 weak_alias (__re_compile_pattern, re_compile_pattern)
7793 #endif
7794 \f
7795 /* Entry points compatible with 4.2 BSD regex library.  We don't define
7796    them unless specifically requested.  */
7797
7798 #if defined _REGEX_RE_COMP || defined _LIBC
7799
7800 /* BSD has one and only one pattern buffer.  */
7801 static struct re_pattern_buffer re_comp_buf;
7802
7803 char *
7804 #ifdef _LIBC
7805 /* Make these definitions weak in libc, so POSIX programs can redefine
7806    these names if they don't use our functions, and still use
7807    regcomp/regexec below without link errors.  */
7808 weak_function
7809 #endif
7810 re_comp (const char *s)
7811 {
7812   reg_errcode_t ret;
7813
7814   if (!s)
7815     {
7816       if (!re_comp_buf.buffer)
7817         return gettext ("No previous regular expression");
7818       return 0;
7819     }
7820
7821   if (!re_comp_buf.buffer)
7822     {
7823       re_comp_buf.buffer = (unsigned char *) malloc (200);
7824       if (re_comp_buf.buffer == NULL)
7825         return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
7826       re_comp_buf.allocated = 200;
7827
7828       re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
7829       if (re_comp_buf.fastmap == NULL)
7830         return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
7831     }
7832
7833   /* Since `re_exec' always passes NULL for the `regs' argument, we
7834      don't need to initialize the pattern buffer fields which affect it.  */
7835
7836   /* Match anchors at newlines.  */
7837   re_comp_buf.newline_anchor = 1;
7838
7839 # ifdef MBS_SUPPORT
7840   if (MB_CUR_MAX != 1)
7841     ret = wcs_regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
7842   else
7843 # endif
7844     ret = byte_regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
7845
7846   if (!ret)
7847     return NULL;
7848
7849   /* Yes, we're discarding `const' here if !HAVE_LIBINTL.  */
7850   return (char *) gettext (re_error_msgid[(int) ret]);
7851 }
7852
7853
7854 int
7855 #ifdef _LIBC
7856 weak_function
7857 #endif
7858 re_exec (const char *s)
7859 {
7860   const int len = strlen (s);
7861   return
7862     0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
7863 }
7864
7865 #endif /* _REGEX_RE_COMP */
7866 \f
7867 /* POSIX.2 functions.  Don't define these for Emacs.  */
7868
7869 #ifndef emacs
7870
7871 /* regcomp takes a regular expression as a string and compiles it.
7872
7873    PREG is a regex_t *.  We do not expect any fields to be initialized,
7874    since POSIX says we shouldn't.  Thus, we set
7875
7876      `buffer' to the compiled pattern;
7877      `used' to the length of the compiled pattern;
7878      `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
7879        REG_EXTENDED bit in CFLAGS is set; otherwise, to
7880        RE_SYNTAX_POSIX_BASIC;
7881      `newline_anchor' to REG_NEWLINE being set in CFLAGS;
7882      `fastmap' to an allocated space for the fastmap;
7883      `fastmap_accurate' to zero;
7884      `re_nsub' to the number of subexpressions in PATTERN.
7885
7886    PATTERN is the address of the pattern string.
7887
7888    CFLAGS is a series of bits which affect compilation.
7889
7890      If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
7891      use POSIX basic syntax.
7892
7893      If REG_NEWLINE is set, then . and [^...] don't match newline.
7894      Also, regexec will try a match beginning after every newline.
7895
7896      If REG_ICASE is set, then we considers upper- and lowercase
7897      versions of letters to be equivalent when matching.
7898
7899      If REG_NOSUB is set, then when PREG is passed to regexec, that
7900      routine will report only success or failure, and nothing about the
7901      registers.
7902
7903    It returns 0 if it succeeds, nonzero if it doesn't.  (See regex.h for
7904    the return codes and their meanings.)  */
7905
7906 int
7907 regcomp (regex_t *preg, const char *pattern, int cflags)
7908 {
7909   reg_errcode_t ret;
7910   reg_syntax_t syntax
7911     = (cflags & REG_EXTENDED) ?
7912       RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
7913
7914   /* regex_compile will allocate the space for the compiled pattern.  */
7915   preg->buffer = 0;
7916   preg->allocated = 0;
7917   preg->used = 0;
7918
7919   /* Try to allocate space for the fastmap.  */
7920   preg->fastmap = (char *) malloc (1 << BYTEWIDTH);
7921
7922   if (cflags & REG_ICASE)
7923     {
7924       unsigned i;
7925
7926       preg->translate
7927         = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
7928                                       * sizeof (*(RE_TRANSLATE_TYPE)0));
7929       if (preg->translate == NULL)
7930         return (int) REG_ESPACE;
7931
7932       /* Map uppercase characters to corresponding lowercase ones.  */
7933       for (i = 0; i < CHAR_SET_SIZE; i++)
7934         preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : (int) i;
7935     }
7936   else
7937     preg->translate = NULL;
7938
7939   /* If REG_NEWLINE is set, newlines are treated differently.  */
7940   if (cflags & REG_NEWLINE)
7941     { /* REG_NEWLINE implies neither . nor [^...] match newline.  */
7942       syntax &= ~RE_DOT_NEWLINE;
7943       syntax |= RE_HAT_LISTS_NOT_NEWLINE;
7944       /* It also changes the matching behavior.  */
7945       preg->newline_anchor = 1;
7946     }
7947   else
7948     preg->newline_anchor = 0;
7949
7950   preg->no_sub = !!(cflags & REG_NOSUB);
7951
7952   /* POSIX says a null character in the pattern terminates it, so we
7953      can use strlen here in compiling the pattern.  */
7954 # ifdef MBS_SUPPORT
7955   if (MB_CUR_MAX != 1)
7956     ret = wcs_regex_compile (pattern, strlen (pattern), syntax, preg);
7957   else
7958 # endif
7959     ret = byte_regex_compile (pattern, strlen (pattern), syntax, preg);
7960
7961   /* POSIX doesn't distinguish between an unmatched open-group and an
7962      unmatched close-group: both are REG_EPAREN.  */
7963   if (ret == REG_ERPAREN) ret = REG_EPAREN;
7964
7965   if (ret == REG_NOERROR && preg->fastmap)
7966     {
7967       /* Compute the fastmap now, since regexec cannot modify the pattern
7968          buffer.  */
7969       if (re_compile_fastmap (preg) == -2)
7970         {
7971           /* Some error occurred while computing the fastmap, just forget
7972              about it.  */
7973           free (preg->fastmap);
7974           preg->fastmap = NULL;
7975         }
7976     }
7977
7978   return (int) ret;
7979 }
7980 #ifdef _LIBC
7981 weak_alias (__regcomp, regcomp)
7982 #endif
7983
7984
7985 /* regexec searches for a given pattern, specified by PREG, in the
7986    string STRING.
7987
7988    If NMATCH is zero or REG_NOSUB was set in the cflags argument to
7989    `regcomp', we ignore PMATCH.  Otherwise, we assume PMATCH has at
7990    least NMATCH elements, and we set them to the offsets of the
7991    corresponding matched substrings.
7992
7993    EFLAGS specifies `execution flags' which affect matching: if
7994    REG_NOTBOL is set, then ^ does not match at the beginning of the
7995    string; if REG_NOTEOL is set, then $ does not match at the end.
7996
7997    We return 0 if we find a match and REG_NOMATCH if not.  */
7998
7999 int
8000 regexec (const regex_t *preg, const char *string, size_t nmatch,
8001          regmatch_t pmatch[], int eflags)
8002 {
8003   int ret;
8004   struct re_registers regs;
8005   regex_t private_preg;
8006   int len = strlen (string);
8007   boolean want_reg_info = !preg->no_sub && nmatch > 0;
8008
8009   private_preg = *preg;
8010
8011   private_preg.not_bol = !!(eflags & REG_NOTBOL);
8012   private_preg.not_eol = !!(eflags & REG_NOTEOL);
8013
8014   /* The user has told us exactly how many registers to return
8015      information about, via `nmatch'.  We have to pass that on to the
8016      matching routines.  */
8017   private_preg.regs_allocated = REGS_FIXED;
8018
8019   if (want_reg_info)
8020     {
8021       regs.num_regs = nmatch;
8022       regs.start = TALLOC (nmatch * 2, regoff_t);
8023       if (regs.start == NULL)
8024         return (int) REG_NOMATCH;
8025       regs.end = regs.start + nmatch;
8026     }
8027
8028   /* Perform the searching operation.  */
8029   ret = re_search (&private_preg, string, len,
8030                    /* start: */ 0, /* range: */ len,
8031                    want_reg_info ? &regs : (struct re_registers *) 0);
8032
8033   /* Copy the register information to the POSIX structure.  */
8034   if (want_reg_info)
8035     {
8036       if (ret >= 0)
8037         {
8038           unsigned r;
8039
8040           for (r = 0; r < nmatch; r++)
8041             {
8042               pmatch[r].rm_so = regs.start[r];
8043               pmatch[r].rm_eo = regs.end[r];
8044             }
8045         }
8046
8047       /* If we needed the temporary register info, free the space now.  */
8048       free (regs.start);
8049     }
8050
8051   /* We want zero return to mean success, unlike `re_search'.  */
8052   return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
8053 }
8054 #ifdef _LIBC
8055 weak_alias (__regexec, regexec)
8056 #endif
8057
8058
8059 /* Returns a message corresponding to an error code, ERRCODE, returned
8060    from either regcomp or regexec.   We don't use PREG here.  */
8061
8062 size_t
8063 regerror (int errcode, const regex_t *preg ATTRIBUTE_UNUSED,
8064           char *errbuf, size_t errbuf_size)
8065 {
8066   const char *msg;
8067   size_t msg_size;
8068
8069   if (errcode < 0
8070       || errcode >= (int) (sizeof (re_error_msgid)
8071                            / sizeof (re_error_msgid[0])))
8072     /* Only error codes returned by the rest of the code should be passed
8073        to this routine.  If we are given anything else, or if other regex
8074        code generates an invalid error code, then the program has a bug.
8075        Dump core so we can fix it.  */
8076     abort ();
8077
8078   msg = gettext (re_error_msgid[errcode]);
8079
8080   msg_size = strlen (msg) + 1; /* Includes the null.  */
8081
8082   if (errbuf_size != 0)
8083     {
8084       if (msg_size > errbuf_size)
8085         {
8086 #if defined HAVE_MEMPCPY || defined _LIBC
8087           *((char *) mempcpy (errbuf, msg, errbuf_size - 1)) = '\0';
8088 #else
8089           memcpy (errbuf, msg, errbuf_size - 1);
8090           errbuf[errbuf_size - 1] = 0;
8091 #endif
8092         }
8093       else
8094         memcpy (errbuf, msg, msg_size);
8095     }
8096
8097   return msg_size;
8098 }
8099 #ifdef _LIBC
8100 weak_alias (__regerror, regerror)
8101 #endif
8102
8103
8104 /* Free dynamically allocated space used by PREG.  */
8105
8106 void
8107 regfree (regex_t *preg)
8108 {
8109   if (preg->buffer != NULL)
8110     free (preg->buffer);
8111   preg->buffer = NULL;
8112
8113   preg->allocated = 0;
8114   preg->used = 0;
8115
8116   if (preg->fastmap != NULL)
8117     free (preg->fastmap);
8118   preg->fastmap = NULL;
8119   preg->fastmap_accurate = 0;
8120
8121   if (preg->translate != NULL)
8122     free (preg->translate);
8123   preg->translate = NULL;
8124 }
8125 #ifdef _LIBC
8126 weak_alias (__regfree, regfree)
8127 #endif
8128
8129 #endif /* not emacs  */
8130
8131 #endif /* not INSIDE_RECURSION */
8132
8133 \f
8134 #undef STORE_NUMBER
8135 #undef STORE_NUMBER_AND_INCR
8136 #undef EXTRACT_NUMBER
8137 #undef EXTRACT_NUMBER_AND_INCR
8138
8139 #undef DEBUG_PRINT_COMPILED_PATTERN
8140 #undef DEBUG_PRINT_DOUBLE_STRING
8141
8142 #undef INIT_FAIL_STACK
8143 #undef RESET_FAIL_STACK
8144 #undef DOUBLE_FAIL_STACK
8145 #undef PUSH_PATTERN_OP
8146 #undef PUSH_FAILURE_POINTER
8147 #undef PUSH_FAILURE_INT
8148 #undef PUSH_FAILURE_ELT
8149 #undef POP_FAILURE_POINTER
8150 #undef POP_FAILURE_INT
8151 #undef POP_FAILURE_ELT
8152 #undef DEBUG_PUSH
8153 #undef DEBUG_POP
8154 #undef PUSH_FAILURE_POINT
8155 #undef POP_FAILURE_POINT
8156
8157 #undef REG_UNSET_VALUE
8158 #undef REG_UNSET
8159
8160 #undef PATFETCH
8161 #undef PATFETCH_RAW
8162 #undef PATUNFETCH
8163 #undef TRANSLATE
8164
8165 #undef INIT_BUF_SIZE
8166 #undef GET_BUFFER_SPACE
8167 #undef BUF_PUSH
8168 #undef BUF_PUSH_2
8169 #undef BUF_PUSH_3
8170 #undef STORE_JUMP
8171 #undef STORE_JUMP2
8172 #undef INSERT_JUMP
8173 #undef INSERT_JUMP2
8174 #undef EXTEND_BUFFER
8175 #undef GET_UNSIGNED_NUMBER
8176 #undef FREE_STACK_RETURN
8177
8178 # undef POINTER_TO_OFFSET
8179 # undef MATCHING_IN_FRST_STRING
8180 # undef PREFETCH
8181 # undef AT_STRINGS_BEG
8182 # undef AT_STRINGS_END
8183 # undef WORDCHAR_P
8184 # undef FREE_VAR
8185 # undef FREE_VARIABLES
8186 # undef NO_HIGHEST_ACTIVE_REG
8187 # undef NO_LOWEST_ACTIVE_REG
8188
8189 # undef CHAR_T
8190 # undef UCHAR_T
8191 # undef COMPILED_BUFFER_VAR
8192 # undef OFFSET_ADDRESS_SIZE
8193 # undef CHAR_CLASS_SIZE
8194 # undef PREFIX
8195 # undef ARG_PREFIX
8196 # undef PUT_CHAR
8197 # undef BYTE
8198 # undef WCHAR
8199
8200 # define DEFINED_ONCE