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