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