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