OpenCores
URL https://opencores.org/ocsvn/or1k/or1k/trunk

Subversion Repositories or1k

[/] [or1k/] [trunk/] [linux/] [uClibc/] [libc/] [misc/] [regex/] [regex.c] - Blame information for rev 1325

Go to most recent revision | Details | Compare with Previous | View Log

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

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.