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