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