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