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