OSDN Git Service

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