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