source: vendor/gcc/current/libiberty/regex.c

Last change on this file was 1391, checked in by bird, 21 years ago

GCC v3.3.3 sources.

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