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