blob: 682123c0ddcc340a4249b44ef464833eee88d55e [file] [log] [blame]
Tanguy Pruvot36efc942011-11-20 14:41:41 +01001/* Extended regular expression matching and search library, version
2 0.12. (Implements POSIX draft P10003.2/D11.2, except for
3 internationalization features.)
4
5 Copyright (C) 1993, 1994, 1995, 1996 Free Software Foundation, Inc.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
20 USA. */
21
22/* AIX requires this to be the first thing in the file. */
23#if defined (_AIX) && !defined (REGEX_MALLOC)
24 #pragma alloca
25#endif
26
27#undef _GNU_SOURCE
28#define _GNU_SOURCE
29
30#include "cs_config.h"
31
32#define os_random random
33#define HAVE_PTHREAD 1
34
35#ifdef HAVE_CONFIG_H
36#include <config.h>
37#endif
38
39/* We need this for `regex.h', and perhaps for the Emacs include files. */
40#include <sys/types.h>
41
42/* This is for other GNU distributions with internationalized messages. */
43#if HAVE_LIBINTL_H || defined (_LIBC)
44# include <libintl.h>
45#else
46# define gettext(msgid) (msgid)
47#endif
48
49#ifndef gettext_noop
50/* This define is so xgettext can find the internationalizable
51 strings. */
52#define gettext_noop(String) String
53#endif
54
55/* The `emacs' switch turns on certain matching commands
56 that make sense only in Emacs. */
57#ifdef emacs
58
59#include "lisp.h"
60#include "buffer.h"
61#include "syntax.h"
62
63#else /* not emacs */
64
65/* If we are not linking with Emacs proper,
66 we can't use the relocating allocator
67 even if config.h says that we can. */
68#undef REL_ALLOC
69
70#if defined (STDC_HEADERS) || defined (_LIBC)
71#include <stdlib.h>
72#else
73char *malloc ();
74char *realloc ();
75#endif
76
77/* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
78 If nothing else has been done, use the method below. */
79#ifdef INHIBIT_STRING_HEADER
80#if !(defined (HAVE_BZERO) && defined (HAVE_BCOPY))
81#if !defined (bzero) && !defined (bcopy)
82#undef INHIBIT_STRING_HEADER
83#endif
84#endif
85#endif
86
87/* This is the normal way of making sure we have a bcopy and a bzero.
88 This is used in most programs--a few other programs avoid this
89 by defining INHIBIT_STRING_HEADER. */
90#ifndef INHIBIT_STRING_HEADER
91#if defined (HAVE_STRING_H) || defined (STDC_HEADERS) || defined (_LIBC)
92#include <string.h>
93#ifndef bcmp
94#define bcmp(s1, s2, n) memcmp ((s1), (s2), (n))
95#endif
96#ifndef bcopy
97#define bcopy(s, d, n) memcpy ((d), (s), (n))
98#endif
99#ifndef bzero
100#define bzero(s, n) memset ((s), 0, (n))
101#endif
102#else
103#include <strings.h>
104#endif
105#endif
106
107/* Define the syntax stuff for \<, \>, etc. */
108
109/* This must be nonzero for the wordchar and notwordchar pattern
110 commands in re_match_2. */
111#ifndef Sword
112#define Sword 1
113#endif
114
115#ifdef SWITCH_ENUM_BUG
116#define SWITCH_ENUM_CAST(x) ((int)(x))
117#else
118#define SWITCH_ENUM_CAST(x) (x)
119#endif
120
121#ifdef SYNTAX_TABLE
122
123extern char *re_syntax_table;
124
125#else /* not SYNTAX_TABLE */
126
127/* How many characters in the character set. */
128#define CHAR_SET_SIZE 256
129
130static char re_syntax_table[CHAR_SET_SIZE];
131
132static void
133init_syntax_once ()
134{
135 register int c;
136 static int done = 0;
137
138 if (done)
139 return;
140
141 bzero (re_syntax_table, sizeof re_syntax_table);
142
143 for (c = 'a'; c <= 'z'; c++)
144 re_syntax_table[c] = Sword;
145
146 for (c = 'A'; c <= 'Z'; c++)
147 re_syntax_table[c] = Sword;
148
149 for (c = '0'; c <= '9'; c++)
150 re_syntax_table[c] = Sword;
151
152 re_syntax_table['_'] = Sword;
153
154 done = 1;
155}
156
157#endif /* not SYNTAX_TABLE */
158
159#define SYNTAX(c) re_syntax_table[c]
160
161#endif /* not emacs */
162
163/* Get the interface, including the syntax bits. */
maxwen27116ba2015-08-14 21:41:28 +0200164#include "bb_regex.h"
Tanguy Pruvot36efc942011-11-20 14:41:41 +0100165
166/* isalpha etc. are used for the character classes. */
167#include <ctype.h>
168
169/* Jim Meyering writes:
170
171 "... Some ctype macros are valid only for character codes that
172 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
173 using /bin/cc or gcc but without giving an ansi option). So, all
174 ctype uses should be through macros like ISPRINT... If
175 STDC_HEADERS is defined, then autoconf has verified that the ctype
176 macros don't need to be guarded with references to isascii. ...
177 Defining IN_CTYPE_DOMAIN to 1 should let any compiler worth its salt
178 eliminate the && through constant folding." */
179
180#if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII))
181#define IN_CTYPE_DOMAIN(c) 1
182#else
183#define IN_CTYPE_DOMAIN(c) isascii(c)
184#endif
185
186#ifdef isblank
187#define ISBLANK(c) (IN_CTYPE_DOMAIN (c) && isblank (c))
188#else
189#define ISBLANK(c) ((c) == ' ' || (c) == '\t')
190#endif
191#ifdef isgraph
192#define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isgraph (c))
193#else
194#define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isprint (c) && !isspace (c))
195#endif
196
197#define ISPRINT(c) (IN_CTYPE_DOMAIN (c) && isprint (c))
198#define ISDIGIT(c) (IN_CTYPE_DOMAIN (c) && isdigit (c))
199#define ISALNUM(c) (IN_CTYPE_DOMAIN (c) && isalnum (c))
200#define ISALPHA(c) (IN_CTYPE_DOMAIN (c) && isalpha (c))
201#define ISCNTRL(c) (IN_CTYPE_DOMAIN (c) && iscntrl (c))
202#define ISLOWER(c) (IN_CTYPE_DOMAIN (c) && islower (c))
203#define ISPUNCT(c) (IN_CTYPE_DOMAIN (c) && ispunct (c))
204#define ISSPACE(c) (IN_CTYPE_DOMAIN (c) && isspace (c))
205#define ISUPPER(c) (IN_CTYPE_DOMAIN (c) && isupper (c))
206#define ISXDIGIT(c) (IN_CTYPE_DOMAIN (c) && isxdigit (c))
207
208#ifndef NULL
209#define NULL (void *)0
210#endif
211
212/* We remove any previous definition of `SIGN_EXTEND_CHAR',
213 since ours (we hope) works properly with all combinations of
214 machines, compilers, `char' and `unsigned char' argument types.
215 (Per Bothner suggested the basic approach.) */
216#undef SIGN_EXTEND_CHAR
217#if __STDC__
218#define SIGN_EXTEND_CHAR(c) ((signed char) (c))
219#else /* not __STDC__ */
220/* As in Harbison and Steele. */
221#define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
222#endif
223
224/* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
225 use `alloca' instead of `malloc'. This is because using malloc in
226 re_search* or re_match* could cause memory leaks when C-g is used in
227 Emacs; also, malloc is slower and causes storage fragmentation. On
228 the other hand, malloc is more portable, and easier to debug.
229
230 Because we sometimes use alloca, some routines have to be macros,
231 not functions -- `alloca'-allocated space disappears at the end of the
232 function it is called in. */
233
234#ifdef REGEX_MALLOC
235
236#define REGEX_ALLOCATE malloc
237#define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
238#define REGEX_FREE free
239
240#else /* not REGEX_MALLOC */
241
242/* Emacs already defines alloca, sometimes. */
243#ifndef alloca
244
245/* Make alloca work the best possible way. */
246#ifdef __GNUC__
247#define alloca __builtin_alloca
248#else /* not __GNUC__ */
249#if HAVE_ALLOCA_H
250#include <alloca.h>
251#else /* not __GNUC__ or HAVE_ALLOCA_H */
252#if 0 /* It is a bad idea to declare alloca. We always cast the result. */
253#ifndef _AIX /* Already did AIX, up at the top. */
254char *alloca ();
255#endif /* not _AIX */
256#endif
257#endif /* not HAVE_ALLOCA_H */
258#endif /* not __GNUC__ */
259
260#endif /* not alloca */
261
262#define REGEX_ALLOCATE alloca
263
264/* Assumes a `char *destination' variable. */
265#define REGEX_REALLOCATE(source, osize, nsize) \
266 (destination = (char *) alloca (nsize), \
267 bcopy (source, destination, osize), \
268 destination)
269
270/* No need to do anything to free, after alloca. */
271#define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
272
273#endif /* not REGEX_MALLOC */
274
275/* Define how to allocate the failure stack. */
276
277#if defined (REL_ALLOC) && defined (REGEX_MALLOC)
278
279#define REGEX_ALLOCATE_STACK(size) \
280 r_alloc (&failure_stack_ptr, (size))
281#define REGEX_REALLOCATE_STACK(source, osize, nsize) \
282 r_re_alloc (&failure_stack_ptr, (nsize))
283#define REGEX_FREE_STACK(ptr) \
284 r_alloc_free (&failure_stack_ptr)
285
286#else /* not using relocating allocator */
287
288#ifdef REGEX_MALLOC
289
290#define REGEX_ALLOCATE_STACK malloc
291#define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
292#define REGEX_FREE_STACK free
293
294#else /* not REGEX_MALLOC */
295
296#define REGEX_ALLOCATE_STACK alloca
297
298#define REGEX_REALLOCATE_STACK(source, osize, nsize) \
299 REGEX_REALLOCATE (source, osize, nsize)
300/* No need to explicitly free anything. */
301#define REGEX_FREE_STACK(arg)
302
303#endif /* not REGEX_MALLOC */
304#endif /* not using relocating allocator */
305
306
307/* True if `size1' is non-NULL and PTR is pointing anywhere inside
308 `string1' or just past its end. This works if PTR is NULL, which is
309 a good thing. */
310#define FIRST_STRING_P(ptr) \
311 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
312
313/* (Re)Allocate N items of type T using malloc, or fail. */
314#define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
315#define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
316#define RETALLOC_IF(addr, n, t) \
317 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
318#define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
319
320#define BYTEWIDTH 8 /* In bits. */
321
322#define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
323
324#undef MAX
325#undef MIN
326#define MAX(a, b) ((a) > (b) ? (a) : (b))
327#define MIN(a, b) ((a) < (b) ? (a) : (b))
328
329typedef char boolean;
330#define false 0
331#define true 1
332
333static int re_match_2_internal ();
334
335/* These are the command codes that appear in compiled regular
336 expressions. Some opcodes are followed by argument bytes. A
337 command code can specify any interpretation whatsoever for its
338 arguments. Zero bytes may appear in the compiled regular expression. */
339
340typedef enum
341{
342 no_op = 0,
343
344 /* Succeed right away--no more backtracking. */
345 succeed,
346
347 /* Followed by one byte giving n, then by n literal bytes. */
348 exactn,
349
350 /* Matches any (more or less) character. */
351 anychar,
352
353 /* Matches any one char belonging to specified set. First
354 following byte is number of bitmap bytes. Then come bytes
355 for a bitmap saying which chars are in. Bits in each byte
356 are ordered low-bit-first. A character is in the set if its
357 bit is 1. A character too large to have a bit in the map is
358 automatically not in the set. */
359 charset,
360
361 /* Same parameters as charset, but match any character that is
362 not one of those specified. */
363 charset_not,
364
365 /* Start remembering the text that is matched, for storing in a
366 register. Followed by one byte with the register number, in
367 the range 0 to one less than the pattern buffer's re_nsub
368 field. Then followed by one byte with the number of groups
369 inner to this one. (This last has to be part of the
370 start_memory only because we need it in the on_failure_jump
371 of re_match_2.) */
372 start_memory,
373
374 /* Stop remembering the text that is matched and store it in a
375 memory register. Followed by one byte with the register
376 number, in the range 0 to one less than `re_nsub' in the
377 pattern buffer, and one byte with the number of inner groups,
378 just like `start_memory'. (We need the number of inner
379 groups here because we don't have any easy way of finding the
380 corresponding start_memory when we're at a stop_memory.) */
381 stop_memory,
382
383 /* Match a duplicate of something remembered. Followed by one
384 byte containing the register number. */
385 duplicate,
386
387 /* Fail unless at beginning of line. */
388 begline,
389
390 /* Fail unless at end of line. */
391 endline,
392
393 /* Succeeds if at beginning of buffer (if emacs) or at beginning
394 of string to be matched (if not). */
395 begbuf,
396
397 /* Analogously, for end of buffer/string. */
398 endbuf,
399
400 /* Followed by two byte relative address to which to jump. */
401 jump,
402
403 /* Same as jump, but marks the end of an alternative. */
404 jump_past_alt,
405
406 /* Followed by two-byte relative address of place to resume at
407 in case of failure. */
408 on_failure_jump,
409
410 /* Like on_failure_jump, but pushes a placeholder instead of the
411 current string position when executed. */
412 on_failure_keep_string_jump,
413
414 /* Throw away latest failure point and then jump to following
415 two-byte relative address. */
416 pop_failure_jump,
417
418 /* Change to pop_failure_jump if know won't have to backtrack to
419 match; otherwise change to jump. This is used to jump
420 back to the beginning of a repeat. If what follows this jump
421 clearly won't match what the repeat does, such that we can be
422 sure that there is no use backtracking out of repetitions
423 already matched, then we change it to a pop_failure_jump.
424 Followed by two-byte address. */
425 maybe_pop_jump,
426
427 /* Jump to following two-byte address, and push a dummy failure
428 point. This failure point will be thrown away if an attempt
429 is made to use it for a failure. A `+' construct makes this
430 before the first repeat. Also used as an intermediary kind
431 of jump when compiling an alternative. */
432 dummy_failure_jump,
433
434 /* Push a dummy failure point and continue. Used at the end of
435 alternatives. */
436 push_dummy_failure,
437
438 /* Followed by two-byte relative address and two-byte number n.
439 After matching N times, jump to the address upon failure. */
440 succeed_n,
441
442 /* Followed by two-byte relative address, and two-byte number n.
443 Jump to the address N times, then fail. */
444 jump_n,
445
446 /* Set the following two-byte relative address to the
447 subsequent two-byte number. The address *includes* the two
448 bytes of number. */
449 set_number_at,
450
451 wordchar, /* Matches any word-constituent character. */
452 notwordchar, /* Matches any char that is not a word-constituent. */
453
454 wordbeg, /* Succeeds if at word beginning. */
455 wordend, /* Succeeds if at word end. */
456
457 wordbound, /* Succeeds if at a word boundary. */
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +0200458 notwordbound, /* Succeeds if not at a word boundary. */
Tanguy Pruvot36efc942011-11-20 14:41:41 +0100459
460#ifdef emacs
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +0200461 before_dot, /* Succeeds if before point. */
Tanguy Pruvot36efc942011-11-20 14:41:41 +0100462 at_dot, /* Succeeds if at point. */
463 after_dot, /* Succeeds if after point. */
464
465 /* Matches any character whose syntax is specified. Followed by
466 a byte which contains a syntax code, e.g., Sword. */
467 syntaxspec,
468
469 /* Matches any character whose syntax is not that specified. */
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +0200470 notsyntaxspec,
Tanguy Pruvot36efc942011-11-20 14:41:41 +0100471#endif /* emacs */
472} re_opcode_t;
473
474/* Common operations on the compiled pattern. */
475
476/* Store NUMBER in two contiguous bytes starting at DESTINATION. */
477
478#define STORE_NUMBER(destination, number) \
479 do { \
480 (destination)[0] = (number) & 0377; \
481 (destination)[1] = (number) >> 8; \
482 } while (0)
483
484/* Same as STORE_NUMBER, except increment DESTINATION to
485 the byte after where the number is stored. Therefore, DESTINATION
486 must be an lvalue. */
487
488#define STORE_NUMBER_AND_INCR(destination, number) \
489 do { \
490 STORE_NUMBER (destination, number); \
491 (destination) += 2; \
492 } while (0)
493
494/* Put into DESTINATION a number stored in two contiguous bytes starting
495 at SOURCE. */
496
497#define EXTRACT_NUMBER(destination, source) \
498 do { \
499 (destination) = *(source) & 0377; \
500 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
501 } while (0)
502
503#ifdef DEBUG
504static void
505extract_number (dest, source)
506 int *dest;
507 unsigned char *source;
508{
509 int temp = SIGN_EXTEND_CHAR (*(source + 1));
510 *dest = *source & 0377;
511 *dest += temp << 8;
512}
513
514#ifndef EXTRACT_MACROS /* To debug the macros. */
515#undef EXTRACT_NUMBER
516#define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
517#endif /* not EXTRACT_MACROS */
518
519#endif /* DEBUG */
520
521/* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
522 SOURCE must be an lvalue. */
523
524#define EXTRACT_NUMBER_AND_INCR(destination, source) \
525 do { \
526 EXTRACT_NUMBER (destination, source); \
527 (source) += 2; \
528 } while (0)
529
530#ifdef DEBUG
531static void
532extract_number_and_incr (destination, source)
533 int *destination;
534 unsigned char **source;
535{
536 extract_number (destination, *source);
537 *source += 2;
538}
539
540#ifndef EXTRACT_MACROS
541#undef EXTRACT_NUMBER_AND_INCR
542#define EXTRACT_NUMBER_AND_INCR(dest, src) \
543 extract_number_and_incr (&dest, &src)
544#endif /* not EXTRACT_MACROS */
545
546#endif /* DEBUG */
547
548/* If DEBUG is defined, Regex prints many voluminous messages about what
549 it is doing (if the variable `debug' is nonzero). If linked with the
550 main program in `iregex.c', you can enter patterns and strings
551 interactively. And if linked with the main program in `main.c' and
552 the other test files, you can run the already-written tests. */
553
554#ifdef DEBUG
555
556/* We use standard I/O for debugging. */
557#include <stdio.h>
558
559/* It is useful to test things that ``must'' be true when debugging. */
560#include <assert.h>
561
562static int debug = 0;
563
564#define DEBUG_STATEMENT(e) e
565#define DEBUG_PRINT1(x) if (debug) printf (x)
566#define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
567#define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
568#define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
569#define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
570 if (debug) print_partial_compiled_pattern (s, e)
571#define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
572 if (debug) print_double_string (w, s1, sz1, s2, sz2)
573
574
575/* Print the fastmap in human-readable form. */
576
577void
578print_fastmap (fastmap)
579 char *fastmap;
580{
581 unsigned was_a_range = 0;
582 unsigned i = 0;
583
584 while (i < (1 << BYTEWIDTH))
585 {
586 if (fastmap[i++])
587 {
588 was_a_range = 0;
589 putchar (i - 1);
590 while (i < (1 << BYTEWIDTH) && fastmap[i])
591 {
592 was_a_range = 1;
593 i++;
594 }
595 if (was_a_range)
596 {
597 printf ("-");
598 putchar (i - 1);
599 }
600 }
601 }
602 putchar ('\n');
603}
604
605
606/* Print a compiled pattern string in human-readable form, starting at
607 the START pointer into it and ending just before the pointer END. */
608
609void
610print_partial_compiled_pattern (start, end)
611 unsigned char *start;
612 unsigned char *end;
613{
614 int mcnt, mcnt2;
615 unsigned char *p = start;
616 unsigned char *pend = end;
617
618 if (start == NULL)
619 {
620 printf ("(null)\n");
621 return;
622 }
623
624 /* Loop over pattern commands. */
625 while (p < pend)
626 {
627 printf ("%d:\t", p - start);
628
629 switch ((re_opcode_t) *p++)
630 {
631 case no_op:
632 printf ("/no_op");
633 break;
634
635 case exactn:
636 mcnt = *p++;
637 printf ("/exactn/%d", mcnt);
638 do
639 {
640 putchar ('/');
641 putchar (*p++);
642 }
643 while (--mcnt);
644 break;
645
646 case start_memory:
647 mcnt = *p++;
648 printf ("/start_memory/%d/%d", mcnt, *p++);
649 break;
650
651 case stop_memory:
652 mcnt = *p++;
653 printf ("/stop_memory/%d/%d", mcnt, *p++);
654 break;
655
656 case duplicate:
657 printf ("/duplicate/%d", *p++);
658 break;
659
660 case anychar:
661 printf ("/anychar");
662 break;
663
664 case charset:
665 case charset_not:
666 {
667 register int c, last = -100;
668 register int in_range = 0;
669
670 printf ("/charset [%s",
671 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
672
673 assert (p + *p < pend);
674
675 for (c = 0; c < 256; c++)
676 if (c / 8 < *p
677 && (p[1 + (c/8)] & (1 << (c % 8))))
678 {
679 /* Are we starting a range? */
680 if (last + 1 == c && ! in_range)
681 {
682 putchar ('-');
683 in_range = 1;
684 }
685 /* Have we broken a range? */
686 else if (last + 1 != c && in_range)
687 {
688 putchar (last);
689 in_range = 0;
690 }
691
692 if (! in_range)
693 putchar (c);
694
695 last = c;
696 }
697
698 if (in_range)
699 putchar (last);
700
701 putchar (']');
702
703 p += 1 + *p;
704 }
705 break;
706
707 case begline:
708 printf ("/begline");
709 break;
710
711 case endline:
712 printf ("/endline");
713 break;
714
715 case on_failure_jump:
716 extract_number_and_incr (&mcnt, &p);
717 printf ("/on_failure_jump to %d", p + mcnt - start);
718 break;
719
720 case on_failure_keep_string_jump:
721 extract_number_and_incr (&mcnt, &p);
722 printf ("/on_failure_keep_string_jump to %d", p + mcnt - start);
723 break;
724
725 case dummy_failure_jump:
726 extract_number_and_incr (&mcnt, &p);
727 printf ("/dummy_failure_jump to %d", p + mcnt - start);
728 break;
729
730 case push_dummy_failure:
731 printf ("/push_dummy_failure");
732 break;
733
734 case maybe_pop_jump:
735 extract_number_and_incr (&mcnt, &p);
736 printf ("/maybe_pop_jump to %d", p + mcnt - start);
737 break;
738
739 case pop_failure_jump:
740 extract_number_and_incr (&mcnt, &p);
741 printf ("/pop_failure_jump to %d", p + mcnt - start);
742 break;
743
744 case jump_past_alt:
745 extract_number_and_incr (&mcnt, &p);
746 printf ("/jump_past_alt to %d", p + mcnt - start);
747 break;
748
749 case jump:
750 extract_number_and_incr (&mcnt, &p);
751 printf ("/jump to %d", p + mcnt - start);
752 break;
753
754 case succeed_n:
755 extract_number_and_incr (&mcnt, &p);
756 extract_number_and_incr (&mcnt2, &p);
757 printf ("/succeed_n to %d, %d times", p + mcnt - start, mcnt2);
758 break;
759
760 case jump_n:
761 extract_number_and_incr (&mcnt, &p);
762 extract_number_and_incr (&mcnt2, &p);
763 printf ("/jump_n to %d, %d times", p + mcnt - start, mcnt2);
764 break;
765
766 case set_number_at:
767 extract_number_and_incr (&mcnt, &p);
768 extract_number_and_incr (&mcnt2, &p);
769 printf ("/set_number_at location %d to %d", p + mcnt - start, mcnt2);
770 break;
771
772 case wordbound:
773 printf ("/wordbound");
774 break;
775
776 case notwordbound:
777 printf ("/notwordbound");
778 break;
779
780 case wordbeg:
781 printf ("/wordbeg");
782 break;
783
784 case wordend:
785 printf ("/wordend");
786
787#ifdef emacs
788 case before_dot:
789 printf ("/before_dot");
790 break;
791
792 case at_dot:
793 printf ("/at_dot");
794 break;
795
796 case after_dot:
797 printf ("/after_dot");
798 break;
799
800 case syntaxspec:
801 printf ("/syntaxspec");
802 mcnt = *p++;
803 printf ("/%d", mcnt);
804 break;
805
806 case notsyntaxspec:
807 printf ("/notsyntaxspec");
808 mcnt = *p++;
809 printf ("/%d", mcnt);
810 break;
811#endif /* emacs */
812
813 case wordchar:
814 printf ("/wordchar");
815 break;
816
817 case notwordchar:
818 printf ("/notwordchar");
819 break;
820
821 case begbuf:
822 printf ("/begbuf");
823 break;
824
825 case endbuf:
826 printf ("/endbuf");
827 break;
828
829 default:
830 printf ("?%d", *(p-1));
831 }
832
833 putchar ('\n');
834 }
835
836 printf ("%d:\tend of pattern.\n", p - start);
837}
838
839
840void
841print_compiled_pattern (bufp)
842 struct re_pattern_buffer *bufp;
843{
844 unsigned char *buffer = bufp->buffer;
845
846 print_partial_compiled_pattern (buffer, buffer + bufp->used);
847 printf ("%d bytes used/%d bytes allocated.\n", bufp->used, bufp->allocated);
848
849 if (bufp->fastmap_accurate && bufp->fastmap)
850 {
851 printf ("fastmap: ");
852 print_fastmap (bufp->fastmap);
853 }
854
855 printf ("re_nsub: %d\t", bufp->re_nsub);
856 printf ("regs_alloc: %d\t", bufp->regs_allocated);
857 printf ("can_be_null: %d\t", bufp->can_be_null);
858 printf ("newline_anchor: %d\n", bufp->newline_anchor);
859 printf ("no_sub: %d\t", bufp->no_sub);
860 printf ("not_bol: %d\t", bufp->not_bol);
861 printf ("not_eol: %d\t", bufp->not_eol);
862 printf ("syntax: %d\n", bufp->syntax);
863 /* Perhaps we should print the translate table? */
864}
865
866
867void
868print_double_string (where, string1, size1, string2, size2)
869 const char *where;
870 const char *string1;
871 const char *string2;
872 int size1;
873 int size2;
874{
875 unsigned this_char;
876
877 if (where == NULL)
878 printf ("(null)");
879 else
880 {
881 if (FIRST_STRING_P (where))
882 {
883 for (this_char = where - string1; this_char < size1; this_char++)
884 putchar (string1[this_char]);
885
886 where = string2;
887 }
888
889 for (this_char = where - string2; this_char < size2; this_char++)
890 putchar (string2[this_char]);
891 }
892}
893
894#else /* not DEBUG */
895
896#undef assert
897#define assert(e)
898
899#define DEBUG_STATEMENT(e)
900#define DEBUG_PRINT1(x)
901#define DEBUG_PRINT2(x1, x2)
902#define DEBUG_PRINT3(x1, x2, x3)
903#define DEBUG_PRINT4(x1, x2, x3, x4)
904#define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
905#define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
906
907#endif /* not DEBUG */
908
909/* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
910 also be assigned to arbitrarily: each pattern buffer stores its own
911 syntax, so it can be changed between regex compilations. */
912/* This has no initializer because initialized variables in Emacs
913 become read-only after dumping. */
914reg_syntax_t re_syntax_options;
915
916
917/* Specify the precise syntax of regexps for compilation. This provides
918 for compatibility for various utilities which historically have
919 different, incompatible syntaxes.
920
921 The argument SYNTAX is a bit mask comprised of the various bits
922 defined in regex.h. We return the old syntax. */
923
924reg_syntax_t
maxwen27116ba2015-08-14 21:41:28 +0200925bb_re_set_syntax (syntax)
Tanguy Pruvot36efc942011-11-20 14:41:41 +0100926 reg_syntax_t syntax;
927{
928 reg_syntax_t ret = re_syntax_options;
929
930 re_syntax_options = syntax;
931 return ret;
932}
933
934/* This table gives an error message for each of the error codes listed
935 in regex.h. Obviously the order here has to be same as there.
936 POSIX doesn't require that we do anything for REG_NOERROR,
937 but why not be nice? */
938
939static const char *re_error_msgid[] =
940 {
941 gettext_noop ("Success"), /* REG_NOERROR */
942 gettext_noop ("No match"), /* REG_NOMATCH */
943 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
944 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
945 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
946 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
947 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
948 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
949 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
950 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
951 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
952 gettext_noop ("Invalid range end"), /* REG_ERANGE */
953 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
954 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
955 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
956 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
957 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
958 };
959
960/* Avoiding alloca during matching, to placate r_alloc. */
961
962/* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
963 searching and matching functions should not call alloca. On some
964 systems, alloca is implemented in terms of malloc, and if we're
965 using the relocating allocator routines, then malloc could cause a
966 relocation, which might (if the strings being searched are in the
967 ralloc heap) shift the data out from underneath the regexp
968 routines.
969
970 Here's another reason to avoid allocation: Emacs
971 processes input from X in a signal handler; processing X input may
972 call malloc; if input arrives while a matching routine is calling
973 malloc, then we're scrod. But Emacs can't just block input while
974 calling matching routines; then we don't notice interrupts when
975 they come in. So, Emacs blocks input around all regexp calls
976 except the matching calls, which it leaves unprotected, in the
977 faith that they will not malloc. */
978
979/* Normally, this is fine. */
980#define MATCH_MAY_ALLOCATE
981
982/* When using GNU C, we are not REALLY using the C alloca, no matter
983 what config.h may say. So don't take precautions for it. */
984#ifdef __GNUC__
985#undef C_ALLOCA
986#endif
987
988/* The match routines may not allocate if (1) they would do it with malloc
989 and (2) it's not safe for them to use malloc.
990 Note that if REL_ALLOC is defined, matching would not use malloc for the
991 failure stack, but we would still use it for the register vectors;
992 so REL_ALLOC should not affect this. */
993#if (defined (C_ALLOCA) || defined (REGEX_MALLOC)) && defined (emacs)
994#undef MATCH_MAY_ALLOCATE
995#endif
996
997
998/* Failure stack declarations and macros; both re_compile_fastmap and
999 re_match_2 use a failure stack. These have to be macros because of
1000 REGEX_ALLOCATE_STACK. */
1001
1002
1003/* Number of failure points for which to initially allocate space
1004 when matching. If this number is exceeded, we allocate more
1005 space, so it is not a hard limit. */
1006#ifndef INIT_FAILURE_ALLOC
1007#define INIT_FAILURE_ALLOC 5
1008#endif
1009
1010/* Roughly the maximum number of failure points on the stack. Would be
1011 exactly that if always used MAX_FAILURE_ITEMS items each time we failed.
1012 This is a variable only so users of regex can assign to it; we never
1013 change it ourselves. */
1014#if defined (MATCH_MAY_ALLOCATE)
1015/* 4400 was enough to cause a crash on Alpha OSF/1,
1016 whose default stack limit is 2mb. */
1017int re_max_failures = 20000;
1018#else
1019int re_max_failures = 2000;
1020#endif
1021
1022union fail_stack_elt
1023{
1024 unsigned char *pointer;
1025 int integer;
1026};
1027
1028typedef union fail_stack_elt fail_stack_elt_t;
1029
1030typedef struct
1031{
1032 fail_stack_elt_t *stack;
1033 unsigned size;
1034 unsigned avail; /* Offset of next open position. */
1035} fail_stack_type;
1036
1037#define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
1038#define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1039#define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1040
1041
1042/* Define macros to initialize and free the failure stack.
1043 Do `return -2' if the alloc fails. */
1044
1045#ifdef MATCH_MAY_ALLOCATE
1046#define INIT_FAIL_STACK() \
1047 do { \
1048 fail_stack.stack = (fail_stack_elt_t *) \
1049 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
1050 \
1051 if (fail_stack.stack == NULL) \
1052 return -2; \
1053 \
1054 fail_stack.size = INIT_FAILURE_ALLOC; \
1055 fail_stack.avail = 0; \
1056 } while (0)
1057
1058#define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1059#else
1060#define INIT_FAIL_STACK() \
1061 do { \
1062 fail_stack.avail = 0; \
1063 } while (0)
1064
1065#define RESET_FAIL_STACK()
1066#endif
1067
1068
1069/* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
1070
1071 Return 1 if succeeds, and 0 if either ran out of memory
1072 allocating space for it or it was already too large.
1073
1074 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1075
1076#define DOUBLE_FAIL_STACK(fail_stack) \
1077 ((fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS \
1078 ? 0 \
1079 : ((fail_stack).stack = (fail_stack_elt_t *) \
1080 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1081 (fail_stack).size * sizeof (fail_stack_elt_t), \
1082 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
1083 \
1084 (fail_stack).stack == NULL \
1085 ? 0 \
1086 : ((fail_stack).size <<= 1, \
1087 1)))
1088
1089
1090/* Push pointer POINTER on FAIL_STACK.
1091 Return 1 if was able to do so and 0 if ran out of memory allocating
1092 space to do so. */
1093#define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1094 ((FAIL_STACK_FULL () \
1095 && !DOUBLE_FAIL_STACK (FAIL_STACK)) \
1096 ? 0 \
1097 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1098 1))
1099
1100/* Push a pointer value onto the failure stack.
1101 Assumes the variable `fail_stack'. Probably should only
1102 be called from within `PUSH_FAILURE_POINT'. */
1103#define PUSH_FAILURE_POINTER(item) \
1104 fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
1105
1106/* This pushes an integer-valued item onto the failure stack.
1107 Assumes the variable `fail_stack'. Probably should only
1108 be called from within `PUSH_FAILURE_POINT'. */
1109#define PUSH_FAILURE_INT(item) \
1110 fail_stack.stack[fail_stack.avail++].integer = (item)
1111
1112/* Push a fail_stack_elt_t value onto the failure stack.
1113 Assumes the variable `fail_stack'. Probably should only
1114 be called from within `PUSH_FAILURE_POINT'. */
1115#define PUSH_FAILURE_ELT(item) \
1116 fail_stack.stack[fail_stack.avail++] = (item)
1117
1118/* These three POP... operations complement the three PUSH... operations.
1119 All assume that `fail_stack' is nonempty. */
1120#define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1121#define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1122#define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1123
1124/* Used to omit pushing failure point id's when we're not debugging. */
1125#ifdef DEBUG
1126#define DEBUG_PUSH PUSH_FAILURE_INT
1127#define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1128#else
1129#define DEBUG_PUSH(item)
1130#define DEBUG_POP(item_addr)
1131#endif
1132
1133
1134/* Push the information about the state we will need
1135 if we ever fail back to it.
1136
1137 Requires variables fail_stack, regstart, regend, reg_info, and
1138 num_regs be declared. DOUBLE_FAIL_STACK requires `destination' be
1139 declared.
1140
1141 Does `return FAILURE_CODE' if runs out of memory. */
1142
1143#define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
1144 do { \
1145 char *destination; \
1146 /* Must be int, so when we don't save any registers, the arithmetic \
1147 of 0 + -1 isn't done as unsigned. */ \
1148 int this_reg; \
1149 \
1150 DEBUG_STATEMENT (failure_id++); \
1151 DEBUG_STATEMENT (nfailure_points_pushed++); \
1152 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1153 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
1154 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1155 \
1156 DEBUG_PRINT2 (" slots needed: %d\n", NUM_FAILURE_ITEMS); \
1157 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
1158 \
1159 /* Ensure we have enough space allocated for what we will push. */ \
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +02001160 while ((int) REMAINING_AVAIL_SLOTS < (int) NUM_FAILURE_ITEMS) \
Tanguy Pruvot36efc942011-11-20 14:41:41 +01001161 { \
1162 if (!DOUBLE_FAIL_STACK (fail_stack)) \
1163 return failure_code; \
1164 \
1165 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
1166 (fail_stack).size); \
1167 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1168 } \
1169 \
1170 /* Push the info, starting with the registers. */ \
1171 DEBUG_PRINT1 ("\n"); \
1172 \
1173 if (1) \
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +02001174 for (this_reg = lowest_active_reg; \
1175 this_reg <= (int) highest_active_reg; \
Tanguy Pruvot36efc942011-11-20 14:41:41 +01001176 this_reg++) \
1177 { \
1178 DEBUG_PRINT2 (" Pushing reg: %d\n", this_reg); \
1179 DEBUG_STATEMENT (num_regs_pushed++); \
1180 \
1181 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
1182 PUSH_FAILURE_POINTER (regstart[this_reg]); \
1183 \
1184 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
1185 PUSH_FAILURE_POINTER (regend[this_reg]); \
1186 \
1187 DEBUG_PRINT2 (" info: 0x%x\n ", reg_info[this_reg]); \
1188 DEBUG_PRINT2 (" match_null=%d", \
1189 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1190 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1191 DEBUG_PRINT2 (" matched_something=%d", \
1192 MATCHED_SOMETHING (reg_info[this_reg])); \
1193 DEBUG_PRINT2 (" ever_matched=%d", \
1194 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1195 DEBUG_PRINT1 ("\n"); \
1196 PUSH_FAILURE_ELT (reg_info[this_reg].word); \
1197 } \
1198 \
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +02001199 DEBUG_PRINT2(" Pushing low active reg: %d\n", lowest_active_reg); \
Tanguy Pruvot36efc942011-11-20 14:41:41 +01001200 PUSH_FAILURE_INT (lowest_active_reg); \
1201 \
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +02001202 DEBUG_PRINT2(" Pushing high active reg: %d\n", highest_active_reg);\
Tanguy Pruvot36efc942011-11-20 14:41:41 +01001203 PUSH_FAILURE_INT (highest_active_reg); \
1204 \
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +02001205 DEBUG_PRINT2(" Pushing pattern 0x%x: ", pattern_place); \
Tanguy Pruvot36efc942011-11-20 14:41:41 +01001206 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1207 PUSH_FAILURE_POINTER (pattern_place); \
1208 \
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +02001209 DEBUG_PRINT2(" Pushing string 0x%x: `", string_place); \
Tanguy Pruvot36efc942011-11-20 14:41:41 +01001210 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1211 size2); \
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +02001212 DEBUG_PRINT1("'\n"); \
Tanguy Pruvot36efc942011-11-20 14:41:41 +01001213 PUSH_FAILURE_POINTER (string_place); \
1214 \
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +02001215 DEBUG_PRINT2(" Pushing failure id: %u\n", failure_id); \
Tanguy Pruvot36efc942011-11-20 14:41:41 +01001216 DEBUG_PUSH (failure_id); \
1217 } while (0)
1218
1219/* This is the number of items that are pushed and popped on the stack
1220 for each register. */
1221#define NUM_REG_ITEMS 3
1222
1223/* Individual items aside from the registers. */
1224#ifdef DEBUG
1225#define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1226#else
1227#define NUM_NONREG_ITEMS 4
1228#endif
1229
1230/* We push at most this many items on the stack. */
1231/* We used to use (num_regs - 1), which is the number of registers
1232 this regexp will save; but that was changed to 5
1233 to avoid stack overflow for a regexp with lots of parens. */
1234#define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1235
1236/* We actually push this many items. */
1237#define NUM_FAILURE_ITEMS \
1238 (((0 \
1239 ? 0 : highest_active_reg - lowest_active_reg + 1) \
1240 * NUM_REG_ITEMS) \
1241 + NUM_NONREG_ITEMS)
1242
1243/* How many items can still be added to the stack without overflowing it. */
1244#define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1245
1246
1247/* Pops what PUSH_FAIL_STACK pushes.
1248
1249 We restore into the parameters, all of which should be lvalues:
1250 STR -- the saved data position.
1251 PAT -- the saved pattern position.
1252 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1253 REGSTART, REGEND -- arrays of string positions.
1254 REG_INFO -- array of information about each subexpression.
1255
1256 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1257 `pend', `string1', `size1', `string2', and `size2'. */
1258
1259#define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1260{ \
1261 DEBUG_STATEMENT (fail_stack_elt_t failure_id;) \
1262 int this_reg; \
1263 const unsigned char *string_temp; \
1264 \
1265 assert (!FAIL_STACK_EMPTY ()); \
1266 \
1267 /* Remove failure points and point to how many regs pushed. */ \
1268 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1269 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1270 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1271 \
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +02001272 assert ((int) fail_stack.avail >= (int) NUM_NONREG_ITEMS); \
Tanguy Pruvot36efc942011-11-20 14:41:41 +01001273 \
1274 DEBUG_POP (&failure_id); \
1275 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
1276 \
1277 /* If the saved string location is NULL, it came from an \
1278 on_failure_keep_string_jump opcode, and we want to throw away the \
1279 saved NULL, thus retaining our current position in the string. */ \
1280 string_temp = POP_FAILURE_POINTER (); \
1281 if (string_temp != NULL) \
1282 str = (const char *) string_temp; \
1283 \
1284 DEBUG_PRINT2 (" Popping string 0x%x: `", str); \
1285 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1286 DEBUG_PRINT1 ("'\n"); \
1287 \
1288 pat = (unsigned char *) POP_FAILURE_POINTER (); \
1289 DEBUG_PRINT2 (" Popping pattern 0x%x: ", pat); \
1290 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1291 \
1292 /* Restore register info. */ \
1293 high_reg = (unsigned) POP_FAILURE_INT (); \
1294 DEBUG_PRINT2 (" Popping high active reg: %d\n", high_reg); \
1295 \
1296 low_reg = (unsigned) POP_FAILURE_INT (); \
1297 DEBUG_PRINT2 (" Popping low active reg: %d\n", low_reg); \
1298 \
1299 if (1) \
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +02001300 for (this_reg = high_reg; this_reg >= (int) low_reg; this_reg--) \
Tanguy Pruvot36efc942011-11-20 14:41:41 +01001301 { \
1302 DEBUG_PRINT2 (" Popping reg: %d\n", this_reg); \
1303 \
1304 reg_info[this_reg].word = POP_FAILURE_ELT (); \
1305 DEBUG_PRINT2 (" info: 0x%x\n", reg_info[this_reg]); \
1306 \
1307 regend[this_reg] = (const char *) POP_FAILURE_POINTER (); \
1308 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
1309 \
1310 regstart[this_reg] = (const char *) POP_FAILURE_POINTER (); \
1311 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
1312 } \
1313 else \
1314 { \
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +02001315 for (this_reg = highest_active_reg; this_reg > (int) high_reg; \
1316 this_reg--) \
Tanguy Pruvot36efc942011-11-20 14:41:41 +01001317 { \
1318 reg_info[this_reg].word.integer = 0; \
1319 regend[this_reg] = 0; \
1320 regstart[this_reg] = 0; \
1321 } \
1322 highest_active_reg = high_reg; \
1323 } \
1324 \
1325 set_regs_matched_done = 0; \
1326 DEBUG_STATEMENT (nfailure_points_popped++); \
1327} /* POP_FAILURE_POINT */
1328
1329
1330
1331/* Structure for per-register (a.k.a. per-group) information.
1332 Other register information, such as the
1333 starting and ending positions (which are addresses), and the list of
1334 inner groups (which is a bits list) are maintained in separate
1335 variables.
1336
1337 We are making a (strictly speaking) nonportable assumption here: that
1338 the compiler will pack our bit fields into something that fits into
1339 the type of `word', i.e., is something that fits into one item on the
1340 failure stack. */
1341
1342typedef union
1343{
1344 fail_stack_elt_t word;
1345 struct
1346 {
1347 /* This field is one if this group can match the empty string,
1348 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1349#define MATCH_NULL_UNSET_VALUE 3
1350 unsigned match_null_string_p : 2;
1351 unsigned is_active : 1;
1352 unsigned matched_something : 1;
1353 unsigned ever_matched_something : 1;
1354 } bits;
1355} register_info_type;
1356
1357#define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1358#define IS_ACTIVE(R) ((R).bits.is_active)
1359#define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1360#define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1361
1362
1363/* Call this when have matched a real character; it sets `matched' flags
1364 for the subexpressions which we are currently inside. Also records
1365 that those subexprs have matched. */
1366#define SET_REGS_MATCHED() \
1367 do \
1368 { \
1369 if (!set_regs_matched_done) \
1370 { \
1371 unsigned r; \
1372 set_regs_matched_done = 1; \
1373 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1374 { \
1375 MATCHED_SOMETHING (reg_info[r]) \
1376 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1377 = 1; \
1378 } \
1379 } \
1380 } \
1381 while (0)
1382
1383/* Registers are set to a sentinel when they haven't yet matched. */
1384static char reg_unset_dummy;
1385#define REG_UNSET_VALUE (&reg_unset_dummy)
1386#define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1387
1388/* Subroutine declarations and macros for regex_compile. */
1389
1390static void store_op1 (), store_op2 ();
1391static void insert_op1 (), insert_op2 ();
1392static boolean at_begline_loc_p (), at_endline_loc_p ();
1393static boolean group_in_compile_stack ();
1394static reg_errcode_t compile_range ();
1395
1396/* Fetch the next character in the uncompiled pattern---translating it
1397 if necessary. Also cast from a signed character in the constant
1398 string passed to us by the user to an unsigned char that we can use
1399 as an array index (in, e.g., `translate'). */
1400#ifndef PATFETCH
1401#define PATFETCH(c) \
1402 do {if (p == pend) return REG_EEND; \
1403 c = (unsigned char) *p++; \
1404 if (translate) c = (unsigned char) translate[c]; \
1405 } while (0)
1406#endif
1407
1408/* Fetch the next character in the uncompiled pattern, with no
1409 translation. */
1410#define PATFETCH_RAW(c) \
1411 do {if (p == pend) return REG_EEND; \
1412 c = (unsigned char) *p++; \
1413 } while (0)
1414
1415/* Go backwards one character in the pattern. */
1416#define PATUNFETCH p--
1417
1418
1419/* If `translate' is non-null, return translate[D], else just D. We
1420 cast the subscript to translate because some data is declared as
1421 `char *', to avoid warnings when a string constant is passed. But
1422 when we use a character as a subscript we must make it unsigned. */
1423#ifndef TRANSLATE
1424#define TRANSLATE(d) \
1425 (translate ? (char) translate[(unsigned char) (d)] : (d))
1426#endif
1427
1428
1429/* Macros for outputting the compiled pattern into `buffer'. */
1430
1431/* If the buffer isn't allocated when it comes in, use this. */
1432#define INIT_BUF_SIZE 32
1433
1434/* Make sure we have at least N more bytes of space in buffer. */
1435#define GET_BUFFER_SPACE(n) \
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +02001436 while (b - bufp->buffer + (n) > (int) bufp->allocated) \
Tanguy Pruvot36efc942011-11-20 14:41:41 +01001437 EXTEND_BUFFER ()
1438
1439/* Make sure we have one more byte of buffer space and then add C to it. */
1440#define BUF_PUSH(c) \
1441 do { \
1442 GET_BUFFER_SPACE (1); \
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +02001443 *b++ = (unsigned char) (c); \
Tanguy Pruvot36efc942011-11-20 14:41:41 +01001444 } while (0)
1445
1446
1447/* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1448#define BUF_PUSH_2(c1, c2) \
1449 do { \
1450 GET_BUFFER_SPACE (2); \
1451 *b++ = (unsigned char) (c1); \
1452 *b++ = (unsigned char) (c2); \
1453 } while (0)
1454
1455
1456/* As with BUF_PUSH_2, except for three bytes. */
1457#define BUF_PUSH_3(c1, c2, c3) \
1458 do { \
1459 GET_BUFFER_SPACE (3); \
1460 *b++ = (unsigned char) (c1); \
1461 *b++ = (unsigned char) (c2); \
1462 *b++ = (unsigned char) (c3); \
1463 } while (0)
1464
1465
1466/* Store a jump with opcode OP at LOC to location TO. We store a
1467 relative address offset by the three bytes the jump itself occupies. */
1468#define STORE_JUMP(op, loc, to) \
1469 store_op1 (op, loc, (to) - (loc) - 3)
1470
1471/* Likewise, for a two-argument jump. */
1472#define STORE_JUMP2(op, loc, to, arg) \
1473 store_op2 (op, loc, (to) - (loc) - 3, arg)
1474
1475/* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1476#define INSERT_JUMP(op, loc, to) \
1477 insert_op1 (op, loc, (to) - (loc) - 3, b)
1478
1479/* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1480#define INSERT_JUMP2(op, loc, to, arg) \
1481 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1482
1483
1484/* This is not an arbitrary limit: the arguments which represent offsets
1485 into the pattern are two bytes long. So if 2^16 bytes turns out to
1486 be too small, many things would have to change. */
1487#define MAX_BUF_SIZE (1L << 16)
1488
1489
1490/* Extend the buffer by twice its current size via realloc and
1491 reset the pointers that pointed into the old block to point to the
1492 correct places in the new one. If extending the buffer results in it
1493 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1494#define EXTEND_BUFFER() \
1495 do { \
1496 unsigned char *old_buffer = bufp->buffer; \
1497 if (bufp->allocated == MAX_BUF_SIZE) \
1498 return REG_ESIZE; \
1499 bufp->allocated <<= 1; \
1500 if (bufp->allocated > MAX_BUF_SIZE) \
1501 bufp->allocated = MAX_BUF_SIZE; \
1502 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
1503 if (bufp->buffer == NULL) \
1504 return REG_ESPACE; \
1505 /* If the buffer moved, move all the pointers into it. */ \
1506 if (old_buffer != bufp->buffer) \
1507 { \
1508 b = (b - old_buffer) + bufp->buffer; \
1509 begalt = (begalt - old_buffer) + bufp->buffer; \
1510 if (fixup_alt_jump) \
1511 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
1512 if (laststart) \
1513 laststart = (laststart - old_buffer) + bufp->buffer; \
1514 if (pending_exact) \
1515 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
1516 } \
1517 } while (0)
1518
1519
1520/* Since we have one byte reserved for the register number argument to
1521 {start,stop}_memory, the maximum number of groups we can report
1522 things about is what fits in that byte. */
1523#define MAX_REGNUM 255
1524
1525/* But patterns can have more than `MAX_REGNUM' registers. We just
1526 ignore the excess. */
1527typedef unsigned regnum_t;
1528
1529
1530/* Macros for the compile stack. */
1531
1532/* Since offsets can go either forwards or backwards, this type needs to
1533 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1534typedef int pattern_offset_t;
1535
1536typedef struct
1537{
1538 pattern_offset_t begalt_offset;
1539 pattern_offset_t fixup_alt_jump;
1540 pattern_offset_t inner_group_offset;
1541 pattern_offset_t laststart_offset;
1542 regnum_t regnum;
1543} compile_stack_elt_t;
1544
1545
1546typedef struct
1547{
1548 compile_stack_elt_t *stack;
1549 unsigned size;
1550 unsigned avail; /* Offset of next open position. */
1551} compile_stack_type;
1552
1553
1554#define INIT_COMPILE_STACK_SIZE 32
1555
1556#define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1557#define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1558
1559/* The next available element. */
1560#define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1561
1562
1563/* Set the bit for character C in a list. */
1564#define SET_LIST_BIT(c) \
1565 (b[((unsigned char) (c)) / BYTEWIDTH] \
1566 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1567
1568
1569/* Get the next unsigned number in the uncompiled pattern. */
1570#define GET_UNSIGNED_NUMBER(num) \
1571 { if (p != pend) \
1572 { \
1573 PATFETCH (c); \
1574 while (ISDIGIT (c)) \
1575 { \
1576 if (num < 0) \
1577 num = 0; \
1578 num = num * 10 + c - '0'; \
1579 if (p == pend) \
1580 break; \
1581 PATFETCH (c); \
1582 } \
1583 } \
1584 }
1585
1586#define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1587
1588#define IS_CHAR_CLASS(string) \
1589 (STREQ (string, "alpha") || STREQ (string, "upper") \
1590 || STREQ (string, "lower") || STREQ (string, "digit") \
1591 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1592 || STREQ (string, "space") || STREQ (string, "print") \
1593 || STREQ (string, "punct") || STREQ (string, "graph") \
1594 || STREQ (string, "cntrl") || STREQ (string, "blank"))
1595
1596#ifndef MATCH_MAY_ALLOCATE
1597
1598/* If we cannot allocate large objects within re_match_2_internal,
1599 we make the fail stack and register vectors global.
1600 The fail stack, we grow to the maximum size when a regexp
1601 is compiled.
1602 The register vectors, we adjust in size each time we
1603 compile a regexp, according to the number of registers it needs. */
1604
1605static fail_stack_type fail_stack;
1606
1607/* Size with which the following vectors are currently allocated.
1608 That is so we can make them bigger as needed,
1609 but never make them smaller. */
1610static int regs_allocated_size;
1611
1612static const char ** regstart, ** regend;
1613static const char ** old_regstart, ** old_regend;
1614static const char **best_regstart, **best_regend;
1615static register_info_type *reg_info;
1616static const char **reg_dummy;
1617static register_info_type *reg_info_dummy;
1618
1619/* Make the register vectors big enough for NUM_REGS registers,
1620 but don't make them smaller. */
1621
1622static
1623regex_grow_registers (num_regs)
1624 int num_regs;
1625{
1626 if (num_regs > regs_allocated_size)
1627 {
1628 RETALLOC_IF (regstart, num_regs, const char *);
1629 RETALLOC_IF (regend, num_regs, const char *);
1630 RETALLOC_IF (old_regstart, num_regs, const char *);
1631 RETALLOC_IF (old_regend, num_regs, const char *);
1632 RETALLOC_IF (best_regstart, num_regs, const char *);
1633 RETALLOC_IF (best_regend, num_regs, const char *);
1634 RETALLOC_IF (reg_info, num_regs, register_info_type);
1635 RETALLOC_IF (reg_dummy, num_regs, const char *);
1636 RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
1637
1638 regs_allocated_size = num_regs;
1639 }
1640}
1641
1642#endif /* not MATCH_MAY_ALLOCATE */
1643
1644/* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1645 Returns one of error codes defined in `regex.h', or zero for success.
1646
1647 Assumes the `allocated' (and perhaps `buffer') and `translate'
1648 fields are set in BUFP on entry.
1649
1650 If it succeeds, results are put in BUFP (if it returns an error, the
1651 contents of BUFP are undefined):
1652 `buffer' is the compiled pattern;
1653 `syntax' is set to SYNTAX;
1654 `used' is set to the length of the compiled pattern;
1655 `fastmap_accurate' is zero;
1656 `re_nsub' is the number of subexpressions in PATTERN;
1657 `not_bol' and `not_eol' are zero;
1658
1659 The `fastmap' and `newline_anchor' fields are neither
1660 examined nor set. */
1661
1662/* Return, freeing storage we allocated. */
1663#define FREE_STACK_RETURN(value) \
1664 return (free (compile_stack.stack), value)
1665
1666static reg_errcode_t
1667regex_compile (pattern, size, syntax, bufp)
1668 const char *pattern;
1669 int size;
1670 reg_syntax_t syntax;
1671 struct re_pattern_buffer *bufp;
1672{
1673 /* We fetch characters from PATTERN here. Even though PATTERN is
1674 `char *' (i.e., signed), we declare these variables as unsigned, so
1675 they can be reliably used as array indices. */
1676 register unsigned char c, c1;
1677
1678 /* A random temporary spot in PATTERN. */
1679 const char *p1;
1680
1681 /* Points to the end of the buffer, where we should append. */
1682 register unsigned char *b;
1683
1684 /* Keeps track of unclosed groups. */
1685 compile_stack_type compile_stack;
1686
1687 /* Points to the current (ending) position in the pattern. */
1688 const char *p = pattern;
1689 const char *pend = pattern + size;
1690
1691 /* How to translate the characters in the pattern. */
1692 RE_TRANSLATE_TYPE translate = bufp->translate;
1693
1694 /* Address of the count-byte of the most recently inserted `exactn'
1695 command. This makes it possible to tell if a new exact-match
1696 character can be added to that command or if the character requires
1697 a new `exactn' command. */
1698 unsigned char *pending_exact = 0;
1699
1700 /* Address of start of the most recently finished expression.
1701 This tells, e.g., postfix * where to find the start of its
1702 operand. Reset at the beginning of groups and alternatives. */
1703 unsigned char *laststart = 0;
1704
1705 /* Address of beginning of regexp, or inside of last group. */
1706 unsigned char *begalt;
1707
1708 /* Place in the uncompiled pattern (i.e., the {) to
1709 which to go back if the interval is invalid. */
1710 const char *beg_interval;
1711
1712 /* Address of the place where a forward jump should go to the end of
1713 the containing expression. Each alternative of an `or' -- except the
1714 last -- ends with a forward jump of this sort. */
1715 unsigned char *fixup_alt_jump = 0;
1716
1717 /* Counts open-groups as they are encountered. Remembered for the
1718 matching close-group on the compile stack, so the same register
1719 number is put in the stop_memory as the start_memory. */
1720 regnum_t regnum = 0;
1721
1722#ifdef DEBUG
1723 DEBUG_PRINT1 ("\nCompiling pattern: ");
1724 if (debug)
1725 {
1726 unsigned debug_count;
1727
1728 for (debug_count = 0; debug_count < size; debug_count++)
1729 putchar (pattern[debug_count]);
1730 putchar ('\n');
1731 }
1732#endif /* DEBUG */
1733
1734 /* Initialize the compile stack. */
1735 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
1736 if (compile_stack.stack == NULL)
1737 return REG_ESPACE;
1738
1739 compile_stack.size = INIT_COMPILE_STACK_SIZE;
1740 compile_stack.avail = 0;
1741
1742 /* Initialize the pattern buffer. */
1743 bufp->syntax = syntax;
1744 bufp->fastmap_accurate = 0;
1745 bufp->not_bol = bufp->not_eol = 0;
1746
1747 /* Set `used' to zero, so that if we return an error, the pattern
1748 printer (for debugging) will think there's no pattern. We reset it
1749 at the end. */
1750 bufp->used = 0;
1751
1752 /* Always count groups, whether or not bufp->no_sub is set. */
1753 bufp->re_nsub = 0;
1754
1755#if !defined (emacs) && !defined (SYNTAX_TABLE)
1756 /* Initialize the syntax table. */
1757 init_syntax_once ();
1758#endif
1759
1760 if (bufp->allocated == 0)
1761 {
1762 if (bufp->buffer)
1763 { /* If zero allocated, but buffer is non-null, try to realloc
1764 enough space. This loses if buffer's address is bogus, but
1765 that is the user's responsibility. */
1766 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
1767 }
1768 else
1769 { /* Caller did not allocate a buffer. Do it for them. */
1770 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
1771 }
1772 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
1773
1774 bufp->allocated = INIT_BUF_SIZE;
1775 }
1776
1777 begalt = b = bufp->buffer;
1778
1779 /* Loop through the uncompiled pattern until we're at the end. */
1780 while (p != pend)
1781 {
1782 PATFETCH (c);
1783
1784 switch (c)
1785 {
1786 case '^':
1787 {
1788 if ( /* If at start of pattern, it's an operator. */
1789 p == pattern + 1
1790 /* If context independent, it's an operator. */
1791 || syntax & RE_CONTEXT_INDEP_ANCHORS
1792 /* Otherwise, depends on what's come before. */
1793 || at_begline_loc_p (pattern, p, syntax))
1794 BUF_PUSH (begline);
1795 else
1796 goto normal_char;
1797 }
1798 break;
1799
1800
1801 case '$':
1802 {
1803 if ( /* If at end of pattern, it's an operator. */
1804 p == pend
1805 /* If context independent, it's an operator. */
1806 || syntax & RE_CONTEXT_INDEP_ANCHORS
1807 /* Otherwise, depends on what's next. */
1808 || at_endline_loc_p (p, pend, syntax))
1809 BUF_PUSH (endline);
1810 else
1811 goto normal_char;
1812 }
1813 break;
1814
1815
1816 case '+':
1817 case '?':
1818 if ((syntax & RE_BK_PLUS_QM)
1819 || (syntax & RE_LIMITED_OPS))
1820 goto normal_char;
1821 handle_plus:
1822 case '*':
1823 /* If there is no previous pattern... */
1824 if (!laststart)
1825 {
1826 if (syntax & RE_CONTEXT_INVALID_OPS)
1827 FREE_STACK_RETURN (REG_BADRPT);
1828 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
1829 goto normal_char;
1830 }
1831
1832 {
1833 /* Are we optimizing this jump? */
1834 boolean keep_string_p = false;
1835
1836 /* 1 means zero (many) matches is allowed. */
1837 char zero_times_ok = 0, many_times_ok = 0;
1838
1839 /* If there is a sequence of repetition chars, collapse it
1840 down to just one (the right one). We can't combine
1841 interval operators with these because of, e.g., `a{2}*',
1842 which should only match an even number of `a's. */
1843
1844 for (;;)
1845 {
1846 zero_times_ok |= c != '+';
1847 many_times_ok |= c != '?';
1848
1849 if (p == pend)
1850 break;
1851
1852 PATFETCH (c);
1853
1854 if (c == '*'
1855 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
1856 ;
1857
1858 else if (syntax & RE_BK_PLUS_QM && c == '\\')
1859 {
1860 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
1861
1862 PATFETCH (c1);
1863 if (!(c1 == '+' || c1 == '?'))
1864 {
1865 PATUNFETCH;
1866 PATUNFETCH;
1867 break;
1868 }
1869
1870 c = c1;
1871 }
1872 else
1873 {
1874 PATUNFETCH;
1875 break;
1876 }
1877
1878 /* If we get here, we found another repeat character. */
1879 }
1880
1881 /* Star, etc. applied to an empty pattern is equivalent
1882 to an empty pattern. */
1883 if (!laststart)
1884 break;
1885
1886 /* Now we know whether or not zero matches is allowed
1887 and also whether or not two or more matches is allowed. */
1888 if (many_times_ok)
1889 { /* More than one repetition is allowed, so put in at the
1890 end a backward relative jump from `b' to before the next
1891 jump we're going to put in below (which jumps from
1892 laststart to after this jump).
1893
1894 But if we are at the `*' in the exact sequence `.*\n',
1895 insert an unconditional jump backwards to the .,
1896 instead of the beginning of the loop. This way we only
1897 push a failure point once, instead of every time
1898 through the loop. */
1899 assert (p - 1 > pattern);
1900
1901 /* Allocate the space for the jump. */
1902 GET_BUFFER_SPACE (3);
1903
1904 /* We know we are not at the first character of the pattern,
1905 because laststart was nonzero. And we've already
1906 incremented `p', by the way, to be the character after
1907 the `*'. Do we have to do something analogous here
1908 for null bytes, because of RE_DOT_NOT_NULL? */
1909 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
1910 && zero_times_ok
1911 && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
1912 && !(syntax & RE_DOT_NEWLINE))
1913 { /* We have .*\n. */
1914 STORE_JUMP (jump, b, laststart);
1915 keep_string_p = true;
1916 }
1917 else
1918 /* Anything else. */
1919 STORE_JUMP (maybe_pop_jump, b, laststart - 3);
1920
1921 /* We've added more stuff to the buffer. */
1922 b += 3;
1923 }
1924
1925 /* On failure, jump from laststart to b + 3, which will be the
1926 end of the buffer after this jump is inserted. */
1927 GET_BUFFER_SPACE (3);
1928 INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
1929 : on_failure_jump,
1930 laststart, b + 3);
1931 pending_exact = 0;
1932 b += 3;
1933
1934 if (!zero_times_ok)
1935 {
1936 /* At least one repetition is required, so insert a
1937 `dummy_failure_jump' before the initial
1938 `on_failure_jump' instruction of the loop. This
1939 effects a skip over that instruction the first time
1940 we hit that loop. */
1941 GET_BUFFER_SPACE (3);
1942 INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
1943 b += 3;
1944 }
1945 }
1946 break;
1947
1948
1949 case '.':
1950 laststart = b;
1951 BUF_PUSH (anychar);
1952 break;
1953
1954
1955 case '[':
1956 {
1957 boolean had_char_class = false;
1958
1959 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
1960
1961 /* Ensure that we have enough space to push a charset: the
1962 opcode, the length count, and the bitset; 34 bytes in all. */
1963 GET_BUFFER_SPACE (34);
1964
1965 laststart = b;
1966
1967 /* We test `*p == '^' twice, instead of using an if
1968 statement, so we only need one BUF_PUSH. */
1969 BUF_PUSH (*p == '^' ? charset_not : charset);
1970 if (*p == '^')
1971 p++;
1972
1973 /* Remember the first position in the bracket expression. */
1974 p1 = p;
1975
1976 /* Push the number of bytes in the bitmap. */
1977 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
1978
1979 /* Clear the whole map. */
1980 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
1981
1982 /* charset_not matches newline according to a syntax bit. */
1983 if ((re_opcode_t) b[-2] == charset_not
1984 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
1985 SET_LIST_BIT ('\n');
1986
1987 /* Read in characters and ranges, setting map bits. */
1988 for (;;)
1989 {
1990 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
1991
1992 PATFETCH (c);
1993
1994 /* \ might escape characters inside [...] and [^...]. */
1995 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
1996 {
1997 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
1998
1999 PATFETCH (c1);
2000 SET_LIST_BIT (c1);
2001 continue;
2002 }
2003
2004 /* Could be the end of the bracket expression. If it's
2005 not (i.e., when the bracket expression is `[]' so
2006 far), the ']' character bit gets set way below. */
2007 if (c == ']' && p != p1 + 1)
2008 break;
2009
2010 /* Look ahead to see if it's a range when the last thing
2011 was a character class. */
2012 if (had_char_class && c == '-' && *p != ']')
2013 FREE_STACK_RETURN (REG_ERANGE);
2014
2015 /* Look ahead to see if it's a range when the last thing
2016 was a character: if this is a hyphen not at the
2017 beginning or the end of a list, then it's the range
2018 operator. */
2019 if (c == '-'
2020 && !(p - 2 >= pattern && p[-2] == '[')
2021 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
2022 && *p != ']')
2023 {
2024 reg_errcode_t ret
2025 = compile_range (&p, pend, translate, syntax, b);
2026 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2027 }
2028
2029 else if (p[0] == '-' && p[1] != ']')
2030 { /* This handles ranges made up of characters only. */
2031 reg_errcode_t ret;
2032
2033 /* Move past the `-'. */
2034 PATFETCH (c1);
2035
2036 ret = compile_range (&p, pend, translate, syntax, b);
2037 if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2038 }
2039
2040 /* See if we're at the beginning of a possible character
2041 class. */
2042
2043 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2044 { /* Leave room for the null. */
2045 char str[CHAR_CLASS_MAX_LENGTH + 1];
2046
2047 PATFETCH (c);
2048 c1 = 0;
2049
2050 /* If pattern is `[[:'. */
2051 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2052
2053 for (;;)
2054 {
2055 PATFETCH (c);
2056 if (c == ':' || c == ']' || p == pend
2057 || c1 == CHAR_CLASS_MAX_LENGTH)
2058 break;
2059 str[c1++] = c;
2060 }
2061 str[c1] = '\0';
2062
2063 /* If isn't a word bracketed by `[:' and:`]':
2064 undo the ending character, the letters, and leave
2065 the leading `:' and `[' (but set bits for them). */
2066 if (c == ':' && *p == ']')
2067 {
2068 int ch;
2069 boolean is_alnum = STREQ (str, "alnum");
2070 boolean is_alpha = STREQ (str, "alpha");
2071 boolean is_blank = STREQ (str, "blank");
2072 boolean is_cntrl = STREQ (str, "cntrl");
2073 boolean is_digit = STREQ (str, "digit");
2074 boolean is_graph = STREQ (str, "graph");
2075 boolean is_lower = STREQ (str, "lower");
2076 boolean is_print = STREQ (str, "print");
2077 boolean is_punct = STREQ (str, "punct");
2078 boolean is_space = STREQ (str, "space");
2079 boolean is_upper = STREQ (str, "upper");
2080 boolean is_xdigit = STREQ (str, "xdigit");
2081
2082 if (!IS_CHAR_CLASS (str))
2083 FREE_STACK_RETURN (REG_ECTYPE);
2084
2085 /* Throw away the ] at the end of the character
2086 class. */
2087 PATFETCH (c);
2088
2089 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2090
2091 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
2092 {
2093 int translated = TRANSLATE (ch);
2094 /* This was split into 3 if's to
2095 avoid an arbitrary limit in some compiler. */
2096 if ( (is_alnum && ISALNUM (ch))
2097 || (is_alpha && ISALPHA (ch))
2098 || (is_blank && ISBLANK (ch))
2099 || (is_cntrl && ISCNTRL (ch)))
2100 SET_LIST_BIT (translated);
2101 if ( (is_digit && ISDIGIT (ch))
2102 || (is_graph && ISGRAPH (ch))
2103 || (is_lower && ISLOWER (ch))
2104 || (is_print && ISPRINT (ch)))
2105 SET_LIST_BIT (translated);
2106 if ( (is_punct && ISPUNCT (ch))
2107 || (is_space && ISSPACE (ch))
2108 || (is_upper && ISUPPER (ch))
2109 || (is_xdigit && ISXDIGIT (ch)))
2110 SET_LIST_BIT (translated);
2111 }
2112 had_char_class = true;
2113 }
2114 else
2115 {
2116 c1++;
2117 while (c1--)
2118 PATUNFETCH;
2119 SET_LIST_BIT ('[');
2120 SET_LIST_BIT (':');
2121 had_char_class = false;
2122 }
2123 }
2124 else
2125 {
2126 had_char_class = false;
2127 SET_LIST_BIT (c);
2128 }
2129 }
2130
2131 /* Discard any (non)matching list bytes that are all 0 at the
2132 end of the map. Decrease the map-length byte too. */
2133 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2134 b[-1]--;
2135 b += b[-1];
2136 }
2137 break;
2138
2139
2140 case '(':
2141 if (syntax & RE_NO_BK_PARENS)
2142 goto handle_open;
2143 else
2144 goto normal_char;
2145
2146
2147 case ')':
2148 if (syntax & RE_NO_BK_PARENS)
2149 goto handle_close;
2150 else
2151 goto normal_char;
2152
2153
2154 case '\n':
2155 if (syntax & RE_NEWLINE_ALT)
2156 goto handle_alt;
2157 else
2158 goto normal_char;
2159
2160
2161 case '|':
2162 if (syntax & RE_NO_BK_VBAR)
2163 goto handle_alt;
2164 else
2165 goto normal_char;
2166
2167
2168 case '{':
2169 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
2170 goto handle_interval;
2171 else
2172 goto normal_char;
2173
2174
2175 case '\\':
2176 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2177
2178 /* Do not translate the character after the \, so that we can
2179 distinguish, e.g., \B from \b, even if we normally would
2180 translate, e.g., B to b. */
2181 PATFETCH_RAW (c);
2182
2183 switch (c)
2184 {
2185 case '(':
2186 if (syntax & RE_NO_BK_PARENS)
2187 goto normal_backslash;
2188
2189 handle_open:
2190 bufp->re_nsub++;
2191 regnum++;
2192
2193 if (COMPILE_STACK_FULL)
2194 {
2195 RETALLOC (compile_stack.stack, compile_stack.size << 1,
2196 compile_stack_elt_t);
2197 if (compile_stack.stack == NULL) return REG_ESPACE;
2198
2199 compile_stack.size <<= 1;
2200 }
2201
2202 /* These are the values to restore when we hit end of this
2203 group. They are all relative offsets, so that if the
2204 whole pattern moves because of realloc, they will still
2205 be valid. */
2206 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
2207 COMPILE_STACK_TOP.fixup_alt_jump
2208 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
2209 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
2210 COMPILE_STACK_TOP.regnum = regnum;
2211
2212 /* We will eventually replace the 0 with the number of
2213 groups inner to this one. But do not push a
2214 start_memory for groups beyond the last one we can
2215 represent in the compiled pattern. */
2216 if (regnum <= MAX_REGNUM)
2217 {
2218 COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
2219 BUF_PUSH_3 (start_memory, regnum, 0);
2220 }
2221
2222 compile_stack.avail++;
2223
2224 fixup_alt_jump = 0;
2225 laststart = 0;
2226 begalt = b;
2227 /* If we've reached MAX_REGNUM groups, then this open
2228 won't actually generate any code, so we'll have to
2229 clear pending_exact explicitly. */
2230 pending_exact = 0;
2231 break;
2232
2233
2234 case ')':
2235 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
2236
2237 if (COMPILE_STACK_EMPTY)
2238 {
2239 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2240 goto normal_backslash;
2241 else
2242 FREE_STACK_RETURN (REG_ERPAREN);
2243 }
2244
2245 handle_close:
2246 if (fixup_alt_jump)
2247 { /* Push a dummy failure point at the end of the
2248 alternative for a possible future
2249 `pop_failure_jump' to pop. See comments at
2250 `push_dummy_failure' in `re_match_2'. */
2251 BUF_PUSH (push_dummy_failure);
2252
2253 /* We allocated space for this jump when we assigned
2254 to `fixup_alt_jump', in the `handle_alt' case below. */
2255 STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
2256 }
2257
2258 /* See similar code for backslashed left paren above. */
2259 if (COMPILE_STACK_EMPTY)
2260 {
2261 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2262 goto normal_char;
2263 else
2264 FREE_STACK_RETURN (REG_ERPAREN);
2265 }
2266
2267 /* Since we just checked for an empty stack above, this
2268 ``can't happen''. */
2269 assert (compile_stack.avail != 0);
2270 {
2271 /* We don't just want to restore into `regnum', because
2272 later groups should continue to be numbered higher,
2273 as in `(ab)c(de)' -- the second group is #2. */
2274 regnum_t this_group_regnum;
2275
2276 compile_stack.avail--;
2277 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
2278 fixup_alt_jump
2279 = COMPILE_STACK_TOP.fixup_alt_jump
2280 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
2281 : 0;
2282 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
2283 this_group_regnum = COMPILE_STACK_TOP.regnum;
2284 /* If we've reached MAX_REGNUM groups, then this open
2285 won't actually generate any code, so we'll have to
2286 clear pending_exact explicitly. */
2287 pending_exact = 0;
2288
2289 /* We're at the end of the group, so now we know how many
2290 groups were inside this one. */
2291 if (this_group_regnum <= MAX_REGNUM)
2292 {
2293 unsigned char *inner_group_loc
2294 = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
2295
2296 *inner_group_loc = regnum - this_group_regnum;
2297 BUF_PUSH_3 (stop_memory, this_group_regnum,
2298 regnum - this_group_regnum);
2299 }
2300 }
2301 break;
2302
2303
2304 case '|': /* `\|'. */
2305 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
2306 goto normal_backslash;
2307 handle_alt:
2308 if (syntax & RE_LIMITED_OPS)
2309 goto normal_char;
2310
2311 /* Insert before the previous alternative a jump which
2312 jumps to this alternative if the former fails. */
2313 GET_BUFFER_SPACE (3);
2314 INSERT_JUMP (on_failure_jump, begalt, b + 6);
2315 pending_exact = 0;
2316 b += 3;
2317
2318 /* The alternative before this one has a jump after it
2319 which gets executed if it gets matched. Adjust that
2320 jump so it will jump to this alternative's analogous
2321 jump (put in below, which in turn will jump to the next
2322 (if any) alternative's such jump, etc.). The last such
2323 jump jumps to the correct final destination. A picture:
2324 _____ _____
2325 | | | |
2326 | v | v
2327 a | b | c
2328
2329 If we are at `b', then fixup_alt_jump right now points to a
2330 three-byte space after `a'. We'll put in the jump, set
2331 fixup_alt_jump to right after `b', and leave behind three
2332 bytes which we'll fill in when we get to after `c'. */
2333
2334 if (fixup_alt_jump)
2335 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2336
2337 /* Mark and leave space for a jump after this alternative,
2338 to be filled in later either by next alternative or
2339 when know we're at the end of a series of alternatives. */
2340 fixup_alt_jump = b;
2341 GET_BUFFER_SPACE (3);
2342 b += 3;
2343
2344 laststart = 0;
2345 begalt = b;
2346 break;
2347
2348
2349 case '{':
2350 /* If \{ is a literal. */
2351 if (!(syntax & RE_INTERVALS)
2352 /* If we're at `\{' and it's not the open-interval
2353 operator. */
2354 || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
2355 || (p - 2 == pattern && p == pend))
2356 goto normal_backslash;
2357
2358 handle_interval:
2359 {
2360 /* If got here, then the syntax allows intervals. */
2361
2362 /* At least (most) this many matches must be made. */
2363 int lower_bound = -1, upper_bound = -1;
2364
2365 beg_interval = p - 1;
2366
2367 if (p == pend)
2368 {
2369 if (syntax & RE_NO_BK_BRACES)
2370 goto unfetch_interval;
2371 else
2372 FREE_STACK_RETURN (REG_EBRACE);
2373 }
2374
2375 GET_UNSIGNED_NUMBER (lower_bound);
2376
2377 if (c == ',')
2378 {
2379 GET_UNSIGNED_NUMBER (upper_bound);
2380 if (upper_bound < 0) upper_bound = RE_DUP_MAX;
2381 }
2382 else
2383 /* Interval such as `{1}' => match exactly once. */
2384 upper_bound = lower_bound;
2385
2386 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
2387 || lower_bound > upper_bound)
2388 {
2389 if (syntax & RE_NO_BK_BRACES)
2390 goto unfetch_interval;
2391 else
2392 FREE_STACK_RETURN (REG_BADBR);
2393 }
2394
2395 if (!(syntax & RE_NO_BK_BRACES))
2396 {
2397 if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
2398
2399 PATFETCH (c);
2400 }
2401
2402 if (c != '}')
2403 {
2404 if (syntax & RE_NO_BK_BRACES)
2405 goto unfetch_interval;
2406 else
2407 FREE_STACK_RETURN (REG_BADBR);
2408 }
2409
2410 /* We just parsed a valid interval. */
2411
2412 /* If it's invalid to have no preceding re. */
2413 if (!laststart)
2414 {
2415 if (syntax & RE_CONTEXT_INVALID_OPS)
2416 FREE_STACK_RETURN (REG_BADRPT);
2417 else if (syntax & RE_CONTEXT_INDEP_OPS)
2418 laststart = b;
2419 else
2420 goto unfetch_interval;
2421 }
2422
2423 /* If the upper bound is zero, don't want to succeed at
2424 all; jump from `laststart' to `b + 3', which will be
2425 the end of the buffer after we insert the jump. */
2426 if (upper_bound == 0)
2427 {
2428 GET_BUFFER_SPACE (3);
2429 INSERT_JUMP (jump, laststart, b + 3);
2430 b += 3;
2431 }
2432
2433 /* Otherwise, we have a nontrivial interval. When
2434 we're all done, the pattern will look like:
2435 set_number_at <jump count> <upper bound>
2436 set_number_at <succeed_n count> <lower bound>
2437 succeed_n <after jump addr> <succeed_n count>
2438 <body of loop>
2439 jump_n <succeed_n addr> <jump count>
2440 (The upper bound and `jump_n' are omitted if
2441 `upper_bound' is 1, though.) */
2442 else
2443 { /* If the upper bound is > 1, we need to insert
2444 more at the end of the loop. */
2445 unsigned nbytes = 10 + (upper_bound > 1) * 10;
2446
2447 GET_BUFFER_SPACE (nbytes);
2448
2449 /* Initialize lower bound of the `succeed_n', even
2450 though it will be set during matching by its
2451 attendant `set_number_at' (inserted next),
2452 because `re_compile_fastmap' needs to know.
2453 Jump to the `jump_n' we might insert below. */
2454 INSERT_JUMP2 (succeed_n, laststart,
2455 b + 5 + (upper_bound > 1) * 5,
2456 lower_bound);
2457 b += 5;
2458
2459 /* Code to initialize the lower bound. Insert
2460 before the `succeed_n'. The `5' is the last two
2461 bytes of this `set_number_at', plus 3 bytes of
2462 the following `succeed_n'. */
2463 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
2464 b += 5;
2465
2466 if (upper_bound > 1)
2467 { /* More than one repetition is allowed, so
2468 append a backward jump to the `succeed_n'
2469 that starts this interval.
2470
2471 When we've reached this during matching,
2472 we'll have matched the interval once, so
2473 jump back only `upper_bound - 1' times. */
2474 STORE_JUMP2 (jump_n, b, laststart + 5,
2475 upper_bound - 1);
2476 b += 5;
2477
2478 /* The location we want to set is the second
2479 parameter of the `jump_n'; that is `b-2' as
2480 an absolute address. `laststart' will be
2481 the `set_number_at' we're about to insert;
2482 `laststart+3' the number to set, the source
2483 for the relative address. But we are
2484 inserting into the middle of the pattern --
2485 so everything is getting moved up by 5.
2486 Conclusion: (b - 2) - (laststart + 3) + 5,
2487 i.e., b - laststart.
2488
2489 We insert this at the beginning of the loop
2490 so that if we fail during matching, we'll
2491 reinitialize the bounds. */
2492 insert_op2 (set_number_at, laststart, b - laststart,
2493 upper_bound - 1, b);
2494 b += 5;
2495 }
2496 }
2497 pending_exact = 0;
2498 beg_interval = NULL;
2499 }
2500 break;
2501
2502 unfetch_interval:
2503 /* If an invalid interval, match the characters as literals. */
2504 assert (beg_interval);
2505 p = beg_interval;
2506 beg_interval = NULL;
2507
2508 /* normal_char and normal_backslash need `c'. */
2509 PATFETCH (c);
2510
2511 if (!(syntax & RE_NO_BK_BRACES))
2512 {
2513 if (p > pattern && p[-1] == '\\')
2514 goto normal_backslash;
2515 }
2516 goto normal_char;
2517
2518#ifdef emacs
2519 /* There is no way to specify the before_dot and after_dot
2520 operators. rms says this is ok. --karl */
2521 case '=':
2522 BUF_PUSH (at_dot);
2523 break;
2524
2525 case 's':
2526 laststart = b;
2527 PATFETCH (c);
2528 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
2529 break;
2530
2531 case 'S':
2532 laststart = b;
2533 PATFETCH (c);
2534 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
2535 break;
2536#endif /* emacs */
2537
2538
2539 case 'w':
2540 laststart = b;
2541 BUF_PUSH (wordchar);
2542 break;
2543
2544
2545 case 'W':
2546 laststart = b;
2547 BUF_PUSH (notwordchar);
2548 break;
2549
2550
2551 case '<':
2552 BUF_PUSH (wordbeg);
2553 break;
2554
2555 case '>':
2556 BUF_PUSH (wordend);
2557 break;
2558
2559 case 'b':
2560 BUF_PUSH (wordbound);
2561 break;
2562
2563 case 'B':
2564 BUF_PUSH (notwordbound);
2565 break;
2566
2567 case '`':
2568 BUF_PUSH (begbuf);
2569 break;
2570
2571 case '\'':
2572 BUF_PUSH (endbuf);
2573 break;
2574
2575 case '1': case '2': case '3': case '4': case '5':
2576 case '6': case '7': case '8': case '9':
2577 if (syntax & RE_NO_BK_REFS)
2578 goto normal_char;
2579
2580 c1 = c - '0';
2581
2582 if (c1 > regnum)
2583 FREE_STACK_RETURN (REG_ESUBREG);
2584
2585 /* Can't back reference to a subexpression if inside of it. */
2586 if (group_in_compile_stack (compile_stack, c1))
2587 goto normal_char;
2588
2589 laststart = b;
2590 BUF_PUSH_2 (duplicate, c1);
2591 break;
2592
2593
2594 case '+':
2595 case '?':
2596 if (syntax & RE_BK_PLUS_QM)
2597 goto handle_plus;
2598 else
2599 goto normal_backslash;
2600
2601 default:
2602 normal_backslash:
2603 /* You might think it would be useful for \ to mean
2604 not to translate; but if we don't translate it
2605 it will never match anything. */
2606 c = TRANSLATE (c);
2607 goto normal_char;
2608 }
2609 break;
2610
2611
2612 default:
2613 /* Expects the character in `c'. */
2614 normal_char:
2615 /* If no exactn currently being built. */
2616 if (!pending_exact
2617
2618 /* If last exactn not at current position. */
2619 || pending_exact + *pending_exact + 1 != b
2620
2621 /* We have only one byte following the exactn for the count. */
2622 || *pending_exact == (1 << BYTEWIDTH) - 1
2623
2624 /* If followed by a repetition operator. */
2625 || *p == '*' || *p == '^'
2626 || ((syntax & RE_BK_PLUS_QM)
2627 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
2628 : (*p == '+' || *p == '?'))
2629 || ((syntax & RE_INTERVALS)
2630 && ((syntax & RE_NO_BK_BRACES)
2631 ? *p == '{'
2632 : (p[0] == '\\' && p[1] == '{'))))
2633 {
2634 /* Start building a new exactn. */
2635
2636 laststart = b;
2637
2638 BUF_PUSH_2 (exactn, 0);
2639 pending_exact = b - 1;
2640 }
2641
2642 BUF_PUSH (c);
2643 (*pending_exact)++;
2644 break;
2645 } /* switch (c) */
2646 } /* while p != pend */
2647
2648
2649 /* Through the pattern now. */
2650
2651 if (fixup_alt_jump)
2652 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2653
2654 if (!COMPILE_STACK_EMPTY)
2655 FREE_STACK_RETURN (REG_EPAREN);
2656
2657 /* If we don't want backtracking, force success
2658 the first time we reach the end of the compiled pattern. */
2659 if (syntax & RE_NO_POSIX_BACKTRACKING)
2660 BUF_PUSH (succeed);
2661
2662 free (compile_stack.stack);
2663
2664 /* We have succeeded; set the length of the buffer. */
2665 bufp->used = b - bufp->buffer;
2666
2667#ifdef DEBUG
2668 if (debug)
2669 {
2670 DEBUG_PRINT1 ("\nCompiled pattern: \n");
2671 print_compiled_pattern (bufp);
2672 }
2673#endif /* DEBUG */
2674
2675#ifndef MATCH_MAY_ALLOCATE
2676 /* Initialize the failure stack to the largest possible stack. This
2677 isn't necessary unless we're trying to avoid calling alloca in
2678 the search and match routines. */
2679 {
2680 int num_regs = bufp->re_nsub + 1;
2681
2682 /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
2683 is strictly greater than re_max_failures, the largest possible stack
2684 is 2 * re_max_failures failure points. */
2685 if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
2686 {
2687 fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
2688
2689#ifdef emacs
2690 if (! fail_stack.stack)
2691 fail_stack.stack
2692 = (fail_stack_elt_t *) xmalloc (fail_stack.size
2693 * sizeof (fail_stack_elt_t));
2694 else
2695 fail_stack.stack
2696 = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
2697 (fail_stack.size
2698 * sizeof (fail_stack_elt_t)));
2699#else /* not emacs */
2700 if (! fail_stack.stack)
2701 fail_stack.stack
2702 = (fail_stack_elt_t *) malloc (fail_stack.size
2703 * sizeof (fail_stack_elt_t));
2704 else
2705 fail_stack.stack
2706 = (fail_stack_elt_t *) realloc (fail_stack.stack,
2707 (fail_stack.size
2708 * sizeof (fail_stack_elt_t)));
2709#endif /* not emacs */
2710 }
2711
2712 regex_grow_registers (num_regs);
2713 }
2714#endif /* not MATCH_MAY_ALLOCATE */
2715
2716 return REG_NOERROR;
2717} /* regex_compile */
2718
2719/* Subroutines for `regex_compile'. */
2720
2721/* Store OP at LOC followed by two-byte integer parameter ARG. */
2722
2723static void
2724store_op1 (op, loc, arg)
2725 re_opcode_t op;
2726 unsigned char *loc;
2727 int arg;
2728{
2729 *loc = (unsigned char) op;
2730 STORE_NUMBER (loc + 1, arg);
2731}
2732
2733
2734/* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
2735
2736static void
2737store_op2 (op, loc, arg1, arg2)
2738 re_opcode_t op;
2739 unsigned char *loc;
2740 int arg1, arg2;
2741{
2742 *loc = (unsigned char) op;
2743 STORE_NUMBER (loc + 1, arg1);
2744 STORE_NUMBER (loc + 3, arg2);
2745}
2746
2747
2748/* Copy the bytes from LOC to END to open up three bytes of space at LOC
2749 for OP followed by two-byte integer parameter ARG. */
2750
2751static void
2752insert_op1 (op, loc, arg, end)
2753 re_opcode_t op;
2754 unsigned char *loc;
2755 int arg;
2756 unsigned char *end;
2757{
2758 register unsigned char *pfrom = end;
2759 register unsigned char *pto = end + 3;
2760
2761 while (pfrom != loc)
2762 *--pto = *--pfrom;
2763
2764 store_op1 (op, loc, arg);
2765}
2766
2767
2768/* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
2769
2770static void
2771insert_op2 (op, loc, arg1, arg2, end)
2772 re_opcode_t op;
2773 unsigned char *loc;
2774 int arg1, arg2;
2775 unsigned char *end;
2776{
2777 register unsigned char *pfrom = end;
2778 register unsigned char *pto = end + 5;
2779
2780 while (pfrom != loc)
2781 *--pto = *--pfrom;
2782
2783 store_op2 (op, loc, arg1, arg2);
2784}
2785
2786
2787/* P points to just after a ^ in PATTERN. Return true if that ^ comes
2788 after an alternative or a begin-subexpression. We assume there is at
2789 least one character before the ^. */
2790
2791static boolean
2792at_begline_loc_p (pattern, p, syntax)
2793 const char *pattern, *p;
2794 reg_syntax_t syntax;
2795{
2796 const char *prev = p - 2;
2797 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
2798
2799 return
2800 /* After a subexpression? */
2801 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
2802 /* After an alternative? */
2803 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
2804}
2805
2806
2807/* The dual of at_begline_loc_p. This one is for $. We assume there is
2808 at least one character after the $, i.e., `P < PEND'. */
2809
2810static boolean
2811at_endline_loc_p (p, pend, syntax)
2812 const char *p, *pend;
2813 int syntax;
2814{
2815 const char *next = p;
2816 boolean next_backslash = *next == '\\';
2817 const char *next_next = p + 1 < pend ? p + 1 : 0;
2818
2819 return
2820 /* Before a subexpression? */
2821 (syntax & RE_NO_BK_PARENS ? *next == ')'
2822 : next_backslash && next_next && *next_next == ')')
2823 /* Before an alternative? */
2824 || (syntax & RE_NO_BK_VBAR ? *next == '|'
2825 : next_backslash && next_next && *next_next == '|');
2826}
2827
2828
2829/* Returns true if REGNUM is in one of COMPILE_STACK's elements and
2830 false if it's not. */
2831
2832static boolean
2833group_in_compile_stack (compile_stack, regnum)
2834 compile_stack_type compile_stack;
2835 regnum_t regnum;
2836{
2837 int this_element;
2838
2839 for (this_element = compile_stack.avail - 1;
2840 this_element >= 0;
2841 this_element--)
2842 if (compile_stack.stack[this_element].regnum == regnum)
2843 return true;
2844
2845 return false;
2846}
2847
2848
2849/* Read the ending character of a range (in a bracket expression) from the
2850 uncompiled pattern *P_PTR (which ends at PEND). We assume the
2851 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
2852 Then we set the translation of all bits between the starting and
2853 ending characters (inclusive) in the compiled pattern B.
2854
2855 Return an error code.
2856
2857 We use these short variable names so we can use the same macros as
2858 `regex_compile' itself. */
2859
2860static reg_errcode_t
2861compile_range (p_ptr, pend, translate, syntax, b)
2862 const char **p_ptr, *pend;
2863 RE_TRANSLATE_TYPE translate;
2864 reg_syntax_t syntax;
2865 unsigned char *b;
2866{
2867 unsigned this_char;
2868
2869 const char *p = *p_ptr;
2870 int range_start, range_end;
2871
2872 if (p == pend)
2873 return REG_ERANGE;
2874
2875 /* Even though the pattern is a signed `char *', we need to fetch
2876 with unsigned char *'s; if the high bit of the pattern character
2877 is set, the range endpoints will be negative if we fetch using a
2878 signed char *.
2879
2880 We also want to fetch the endpoints without translating them; the
2881 appropriate translation is done in the bit-setting loop below. */
2882 /* The SVR4 compiler on the 3B2 had trouble with unsigned const char *. */
2883 range_start = ((const unsigned char *) p)[-2];
2884 range_end = ((const unsigned char *) p)[0];
2885
2886 /* Have to increment the pointer into the pattern string, so the
2887 caller isn't still at the ending character. */
2888 (*p_ptr)++;
2889
2890 /* If the start is after the end, the range is empty. */
2891 if (range_start > range_end)
2892 return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
2893
2894 /* Here we see why `this_char' has to be larger than an `unsigned
2895 char' -- the range is inclusive, so if `range_end' == 0xff
2896 (assuming 8-bit characters), we would otherwise go into an infinite
2897 loop, since all characters <= 0xff. */
2898 for (this_char = range_start; this_char <= range_end; this_char++)
2899 {
2900 SET_LIST_BIT (TRANSLATE (this_char));
2901 }
2902
2903 return REG_NOERROR;
2904}
2905
2906/* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
2907 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
2908 characters can start a string that matches the pattern. This fastmap
2909 is used by re_search to skip quickly over impossible starting points.
2910
2911 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
2912 area as BUFP->fastmap.
2913
2914 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
2915 the pattern buffer.
2916
2917 Returns 0 if we succeed, -2 if an internal error. */
2918
2919int
maxwen27116ba2015-08-14 21:41:28 +02002920bb_re_compile_fastmap (bufp)
Tanguy Pruvot36efc942011-11-20 14:41:41 +01002921 struct re_pattern_buffer *bufp;
2922{
2923 int j, k;
2924#ifdef MATCH_MAY_ALLOCATE
2925 fail_stack_type fail_stack;
2926#endif
2927#ifndef REGEX_MALLOC
2928 char *destination;
2929#endif
2930 /* We don't push any register information onto the failure stack. */
2931 unsigned num_regs = 0;
2932
2933 register char *fastmap = bufp->fastmap;
2934 unsigned char *pattern = bufp->buffer;
2935 unsigned long size = bufp->used;
2936 unsigned char *p = pattern;
2937 register unsigned char *pend = pattern + size;
2938
2939 /* This holds the pointer to the failure stack, when
2940 it is allocated relocatably. */
2941#ifdef REL_ALLOC
2942 fail_stack_elt_t *failure_stack_ptr;
2943#endif
2944
2945 /* Assume that each path through the pattern can be null until
2946 proven otherwise. We set this false at the bottom of switch
2947 statement, to which we get only if a particular path doesn't
2948 match the empty string. */
2949 boolean path_can_be_null = true;
2950
2951 /* We aren't doing a `succeed_n' to begin with. */
2952 boolean succeed_n_p = false;
2953
2954 assert (fastmap != NULL && p != NULL);
2955
2956 INIT_FAIL_STACK ();
2957 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
2958 bufp->fastmap_accurate = 1; /* It will be when we're done. */
2959 bufp->can_be_null = 0;
2960
2961 while (1)
2962 {
2963 if (p == pend || *p == succeed)
2964 {
2965 /* We have reached the (effective) end of pattern. */
2966 if (!FAIL_STACK_EMPTY ())
2967 {
2968 bufp->can_be_null |= path_can_be_null;
2969
2970 /* Reset for next path. */
2971 path_can_be_null = true;
2972
2973 p = fail_stack.stack[--fail_stack.avail].pointer;
2974
2975 continue;
2976 }
2977 else
2978 break;
2979 }
2980
2981 /* We should never be about to go beyond the end of the pattern. */
2982 assert (p < pend);
2983
2984 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
2985 {
2986
2987 /* I guess the idea here is to simply not bother with a fastmap
2988 if a backreference is used, since it's too hard to figure out
2989 the fastmap for the corresponding group. Setting
2990 `can_be_null' stops `re_search_2' from using the fastmap, so
2991 that is all we do. */
2992 case duplicate:
2993 bufp->can_be_null = 1;
2994 goto done;
2995
2996
2997 /* Following are the cases which match a character. These end
2998 with `break'. */
2999
3000 case exactn:
3001 fastmap[p[1]] = 1;
3002 break;
3003
3004
3005 case charset:
3006 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3007 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
3008 fastmap[j] = 1;
3009 break;
3010
3011
3012 case charset_not:
3013 /* Chars beyond end of map must be allowed. */
3014 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
3015 fastmap[j] = 1;
3016
3017 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
3018 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
3019 fastmap[j] = 1;
3020 break;
3021
3022
3023 case wordchar:
3024 for (j = 0; j < (1 << BYTEWIDTH); j++)
3025 if (SYNTAX (j) == Sword)
3026 fastmap[j] = 1;
3027 break;
3028
3029
3030 case notwordchar:
3031 for (j = 0; j < (1 << BYTEWIDTH); j++)
3032 if (SYNTAX (j) != Sword)
3033 fastmap[j] = 1;
3034 break;
3035
3036
3037 case anychar:
3038 {
3039 int fastmap_newline = fastmap['\n'];
3040
3041 /* `.' matches anything ... */
3042 for (j = 0; j < (1 << BYTEWIDTH); j++)
3043 fastmap[j] = 1;
3044
3045 /* ... except perhaps newline. */
3046 if (!(bufp->syntax & RE_DOT_NEWLINE))
3047 fastmap['\n'] = fastmap_newline;
3048
3049 /* Return if we have already set `can_be_null'; if we have,
3050 then the fastmap is irrelevant. Something's wrong here. */
3051 else if (bufp->can_be_null)
3052 goto done;
3053
3054 /* Otherwise, have to check alternative paths. */
3055 break;
3056 }
3057
3058#ifdef emacs
3059 case syntaxspec:
3060 k = *p++;
3061 for (j = 0; j < (1 << BYTEWIDTH); j++)
3062 if (SYNTAX (j) == (enum syntaxcode) k)
3063 fastmap[j] = 1;
3064 break;
3065
3066
3067 case notsyntaxspec:
3068 k = *p++;
3069 for (j = 0; j < (1 << BYTEWIDTH); j++)
3070 if (SYNTAX (j) != (enum syntaxcode) k)
3071 fastmap[j] = 1;
3072 break;
3073
3074
3075 /* All cases after this match the empty string. These end with
3076 `continue'. */
3077
3078
3079 case before_dot:
3080 case at_dot:
3081 case after_dot:
3082 continue;
3083#endif /* emacs */
3084
3085
3086 case no_op:
3087 case begline:
3088 case endline:
3089 case begbuf:
3090 case endbuf:
3091 case wordbound:
3092 case notwordbound:
3093 case wordbeg:
3094 case wordend:
3095 case push_dummy_failure:
3096 continue;
3097
3098
3099 case jump_n:
3100 case pop_failure_jump:
3101 case maybe_pop_jump:
3102 case jump:
3103 case jump_past_alt:
3104 case dummy_failure_jump:
3105 EXTRACT_NUMBER_AND_INCR (j, p);
3106 p += j;
3107 if (j > 0)
3108 continue;
3109
3110 /* Jump backward implies we just went through the body of a
3111 loop and matched nothing. Opcode jumped to should be
3112 `on_failure_jump' or `succeed_n'. Just treat it like an
3113 ordinary jump. For a * loop, it has pushed its failure
3114 point already; if so, discard that as redundant. */
3115 if ((re_opcode_t) *p != on_failure_jump
3116 && (re_opcode_t) *p != succeed_n)
3117 continue;
3118
3119 p++;
3120 EXTRACT_NUMBER_AND_INCR (j, p);
3121 p += j;
3122
3123 /* If what's on the stack is where we are now, pop it. */
3124 if (!FAIL_STACK_EMPTY ()
3125 && fail_stack.stack[fail_stack.avail - 1].pointer == p)
3126 fail_stack.avail--;
3127
3128 continue;
3129
3130
3131 case on_failure_jump:
3132 case on_failure_keep_string_jump:
3133 handle_on_failure_jump:
3134 EXTRACT_NUMBER_AND_INCR (j, p);
3135
3136 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
3137 end of the pattern. We don't want to push such a point,
3138 since when we restore it above, entering the switch will
3139 increment `p' past the end of the pattern. We don't need
3140 to push such a point since we obviously won't find any more
3141 fastmap entries beyond `pend'. Such a pattern can match
3142 the null string, though. */
3143 if (p + j < pend)
3144 {
3145 if (!PUSH_PATTERN_OP (p + j, fail_stack))
3146 {
3147 RESET_FAIL_STACK ();
3148 return -2;
3149 }
3150 }
3151 else
3152 bufp->can_be_null = 1;
3153
3154 if (succeed_n_p)
3155 {
3156 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
3157 succeed_n_p = false;
3158 }
3159
3160 continue;
3161
3162
3163 case succeed_n:
3164 /* Get to the number of times to succeed. */
3165 p += 2;
3166
3167 /* Increment p past the n for when k != 0. */
3168 EXTRACT_NUMBER_AND_INCR (k, p);
3169 if (k == 0)
3170 {
3171 p -= 4;
3172 succeed_n_p = true; /* Spaghetti code alert. */
3173 goto handle_on_failure_jump;
3174 }
3175 continue;
3176
3177
3178 case set_number_at:
3179 p += 4;
3180 continue;
3181
3182
3183 case start_memory:
3184 case stop_memory:
3185 p += 2;
3186 continue;
3187
3188
3189 default:
3190 abort (); /* We have listed all the cases. */
3191 } /* switch *p++ */
3192
3193 /* Getting here means we have found the possible starting
3194 characters for one path of the pattern -- and that the empty
3195 string does not match. We need not follow this path further.
3196 Instead, look at the next alternative (remembered on the
3197 stack), or quit if no more. The test at the top of the loop
3198 does these things. */
3199 path_can_be_null = false;
3200 p = pend;
3201 } /* while p */
3202
3203 /* Set `can_be_null' for the last path (also the first path, if the
3204 pattern is empty). */
3205 bufp->can_be_null |= path_can_be_null;
3206
3207 done:
3208 RESET_FAIL_STACK ();
3209 return 0;
3210} /* re_compile_fastmap */
3211
3212/* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3213 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3214 this memory for recording register information. STARTS and ENDS
3215 must be allocated using the malloc library routine, and must each
3216 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3217
3218 If NUM_REGS == 0, then subsequent matches should allocate their own
3219 register data.
3220
3221 Unless this function is called, the first search or match using
3222 PATTERN_BUFFER will allocate its own register data, without
3223 freeing the old data. */
3224
3225void
maxwen27116ba2015-08-14 21:41:28 +02003226bb_re_set_registers (bufp, regs, num_regs, starts, ends)
Tanguy Pruvot36efc942011-11-20 14:41:41 +01003227 struct re_pattern_buffer *bufp;
3228 struct re_registers *regs;
3229 unsigned num_regs;
3230 regoff_t *starts, *ends;
3231{
3232 if (num_regs)
3233 {
3234 bufp->regs_allocated = REGS_REALLOCATE;
3235 regs->num_regs = num_regs;
3236 regs->start = starts;
3237 regs->end = ends;
3238 }
3239 else
3240 {
3241 bufp->regs_allocated = REGS_UNALLOCATED;
3242 regs->num_regs = 0;
3243 regs->start = regs->end = (regoff_t *) 0;
3244 }
3245}
3246
3247/* Searching routines. */
3248
3249/* Like re_search_2, below, but only one string is specified, and
3250 doesn't let you say where to stop matching. */
3251
3252int
maxwen27116ba2015-08-14 21:41:28 +02003253bb_re_search (bufp, string, size, startpos, range, regs)
Tanguy Pruvot36efc942011-11-20 14:41:41 +01003254 struct re_pattern_buffer *bufp;
3255 const char *string;
3256 int size, startpos, range;
3257 struct re_registers *regs;
3258{
maxwen27116ba2015-08-14 21:41:28 +02003259 return bb_re_search_2 (bufp, NULL, 0, string, size, startpos, range,
Tanguy Pruvot36efc942011-11-20 14:41:41 +01003260 regs, size);
3261}
3262
3263
3264/* Using the compiled pattern in BUFP->buffer, first tries to match the
3265 virtual concatenation of STRING1 and STRING2, starting first at index
3266 STARTPOS, then at STARTPOS + 1, and so on.
3267
3268 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3269
3270 RANGE is how far to scan while trying to match. RANGE = 0 means try
3271 only at STARTPOS; in general, the last start tried is STARTPOS +
3272 RANGE.
3273
3274 In REGS, return the indices of the virtual concatenation of STRING1
3275 and STRING2 that matched the entire BUFP->buffer and its contained
3276 subexpressions.
3277
3278 Do not consider matching one past the index STOP in the virtual
3279 concatenation of STRING1 and STRING2.
3280
3281 We return either the position in the strings at which the match was
3282 found, -1 if no match, or -2 if error (such as failure
3283 stack overflow). */
3284
3285int
maxwen27116ba2015-08-14 21:41:28 +02003286bb_re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
Tanguy Pruvot36efc942011-11-20 14:41:41 +01003287 struct re_pattern_buffer *bufp;
3288 const char *string1, *string2;
3289 int size1, size2;
3290 int startpos;
3291 int range;
3292 struct re_registers *regs;
3293 int stop;
3294{
3295 int val;
3296 register char *fastmap = bufp->fastmap;
3297 register RE_TRANSLATE_TYPE translate = bufp->translate;
3298 int total_size = size1 + size2;
3299 int endpos = startpos + range;
3300 int anchored_start = 0;
3301
3302 /* Check for out-of-range STARTPOS. */
3303 if (startpos < 0 || startpos > total_size)
3304 return -1;
3305
3306 /* Fix up RANGE if it might eventually take us outside
3307 the virtual concatenation of STRING1 and STRING2.
3308 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
3309 if (endpos < 0)
3310 range = 0 - startpos;
3311 else if (endpos > total_size)
3312 range = total_size - startpos;
3313
3314 /* If the search isn't to be a backwards one, don't waste time in a
3315 search for a pattern that must be anchored. */
3316 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
3317 {
3318 if (startpos > 0)
3319 return -1;
3320 else
3321 range = 1;
3322 }
3323
3324#ifdef emacs
3325 /* In a forward search for something that starts with \=.
3326 don't keep searching past point. */
3327 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
3328 {
3329 range = PT - startpos;
3330 if (range <= 0)
3331 return -1;
3332 }
3333#endif /* emacs */
3334
3335 /* Update the fastmap now if not correct already. */
3336 if (fastmap && !bufp->fastmap_accurate)
maxwen27116ba2015-08-14 21:41:28 +02003337 if (bb_re_compile_fastmap (bufp) == -2)
Tanguy Pruvot36efc942011-11-20 14:41:41 +01003338 return -2;
3339
3340 /* See whether the pattern is anchored. */
3341 if (bufp->buffer[0] == begline)
3342 anchored_start = 1;
3343
3344 /* Loop through the string, looking for a place to start matching. */
3345 for (;;)
3346 {
3347 /* If the pattern is anchored,
3348 skip quickly past places we cannot match.
3349 We don't bother to treat startpos == 0 specially
3350 because that case doesn't repeat. */
3351 if (anchored_start && startpos > 0)
3352 {
3353 if (! (bufp->newline_anchor
3354 && ((startpos <= size1 ? string1[startpos - 1]
3355 : string2[startpos - size1 - 1])
3356 == '\n')))
3357 goto advance;
3358 }
3359
3360 /* If a fastmap is supplied, skip quickly over characters that
3361 cannot be the start of a match. If the pattern can match the
3362 null string, however, we don't need to skip characters; we want
3363 the first null string. */
3364 if (fastmap && startpos < total_size && !bufp->can_be_null)
3365 {
3366 if (range > 0) /* Searching forwards. */
3367 {
3368 register const char *d;
3369 register int lim = 0;
3370 int irange = range;
3371
3372 if (startpos < size1 && startpos + range >= size1)
3373 lim = range - (size1 - startpos);
3374
3375 d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
3376
3377 /* Written out as an if-else to avoid testing `translate'
3378 inside the loop. */
3379 if (translate)
3380 while (range > lim
3381 && !fastmap[(unsigned char)
3382 translate[(unsigned char) *d++]])
3383 range--;
3384 else
3385 while (range > lim && !fastmap[(unsigned char) *d++])
3386 range--;
3387
3388 startpos += irange - range;
3389 }
3390 else /* Searching backwards. */
3391 {
3392 register char c = (size1 == 0 || startpos >= size1
3393 ? string2[startpos - size1]
3394 : string1[startpos]);
3395
3396 if (!fastmap[(unsigned char) TRANSLATE (c)])
3397 goto advance;
3398 }
3399 }
3400
3401 /* If can't match the null string, and that's all we have left, fail. */
3402 if (range >= 0 && startpos == total_size && fastmap
3403 && !bufp->can_be_null)
3404 return -1;
3405
3406 val = re_match_2_internal (bufp, string1, size1, string2, size2,
3407 startpos, regs, stop);
3408#ifndef REGEX_MALLOC
3409#ifdef C_ALLOCA
3410 alloca (0);
3411#endif
3412#endif
3413
3414 if (val >= 0)
3415 return startpos;
3416
3417 if (val == -2)
3418 return -2;
3419
3420 advance:
3421 if (!range)
3422 break;
3423 else if (range > 0)
3424 {
3425 range--;
3426 startpos++;
3427 }
3428 else
3429 {
3430 range++;
3431 startpos--;
3432 }
3433 }
3434 return -1;
3435} /* re_search_2 */
3436
3437/* Declarations and macros for re_match_2. */
3438
3439static int bcmp_translate ();
3440static boolean alt_match_null_string_p (),
3441 common_op_match_null_string_p (),
3442 group_match_null_string_p ();
3443
3444/* This converts PTR, a pointer into one of the search strings `string1'
3445 and `string2' into an offset from the beginning of that string. */
3446#define POINTER_TO_OFFSET(ptr) \
3447 (FIRST_STRING_P (ptr) \
3448 ? ((regoff_t) ((ptr) - string1)) \
3449 : ((regoff_t) ((ptr) - string2 + size1)))
3450
3451/* Macros for dealing with the split strings in re_match_2. */
3452
3453#define MATCHING_IN_FIRST_STRING (dend == end_match_1)
3454
3455/* Call before fetching a character with *d. This switches over to
3456 string2 if necessary. */
3457#define PREFETCH() \
3458 while (d == dend) \
3459 { \
3460 /* End of string2 => fail. */ \
3461 if (dend == end_match_2) \
3462 goto fail; \
3463 /* End of string1 => advance to string2. */ \
3464 d = string2; \
3465 dend = end_match_2; \
3466 }
3467
3468
3469/* Test if at very beginning or at very end of the virtual concatenation
3470 of `string1' and `string2'. If only one string, it's `string2'. */
3471#define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
3472#define AT_STRINGS_END(d) ((d) == end2)
3473
3474
3475/* Test if D points to a character which is word-constituent. We have
3476 two special cases to check for: if past the end of string1, look at
3477 the first character in string2; and if before the beginning of
3478 string2, look at the last character in string1. */
3479#define WORDCHAR_P(d) \
3480 (SYNTAX ((d) == end1 ? *string2 \
3481 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
3482 == Sword)
3483
3484/* Disabled due to a compiler bug -- see comment at case wordbound */
3485#if 0
3486/* Test if the character before D and the one at D differ with respect
3487 to being word-constituent. */
3488#define AT_WORD_BOUNDARY(d) \
3489 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
3490 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
3491#endif
3492
3493/* Free everything we malloc. */
3494#ifdef MATCH_MAY_ALLOCATE
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +02003495#define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else {}
Tanguy Pruvot36efc942011-11-20 14:41:41 +01003496#define FREE_VARIABLES() \
3497 do { \
3498 REGEX_FREE_STACK (fail_stack.stack); \
3499 FREE_VAR (regstart); \
3500 FREE_VAR (regend); \
3501 FREE_VAR (old_regstart); \
3502 FREE_VAR (old_regend); \
3503 FREE_VAR (best_regstart); \
3504 FREE_VAR (best_regend); \
3505 FREE_VAR (reg_info); \
3506 FREE_VAR (reg_dummy); \
3507 FREE_VAR (reg_info_dummy); \
3508 } while (0)
3509#else
3510#define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
3511#endif /* not MATCH_MAY_ALLOCATE */
3512
3513/* These values must meet several constraints. They must not be valid
3514 register values; since we have a limit of 255 registers (because
3515 we use only one byte in the pattern for the register number), we can
3516 use numbers larger than 255. They must differ by 1, because of
3517 NUM_FAILURE_ITEMS above. And the value for the lowest register must
3518 be larger than the value for the highest register, so we do not try
3519 to actually save any registers when none are active. */
3520#define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
3521#define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
3522
3523/* Matching routines. */
3524
3525#ifndef emacs /* Emacs never uses this. */
3526/* re_match is like re_match_2 except it takes only a single string. */
3527
3528int
maxwen27116ba2015-08-14 21:41:28 +02003529bb_re_match (bufp, string, size, pos, regs)
Tanguy Pruvot36efc942011-11-20 14:41:41 +01003530 struct re_pattern_buffer *bufp;
3531 const char *string;
3532 int size, pos;
3533 struct re_registers *regs;
3534{
3535 int result = re_match_2_internal (bufp, NULL, 0, string, size,
3536 pos, regs, size);
3537 alloca (0);
3538 return result;
3539}
3540#endif /* not emacs */
3541
3542
3543/* re_match_2 matches the compiled pattern in BUFP against the
3544 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
3545 and SIZE2, respectively). We start matching at POS, and stop
3546 matching at STOP.
3547
3548 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
3549 store offsets for the substring each group matched in REGS. See the
3550 documentation for exactly how many groups we fill.
3551
3552 We return -1 if no match, -2 if an internal error (such as the
3553 failure stack overflowing). Otherwise, we return the length of the
3554 matched substring. */
3555
3556int
maxwen27116ba2015-08-14 21:41:28 +02003557bb_re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
Tanguy Pruvot36efc942011-11-20 14:41:41 +01003558 struct re_pattern_buffer *bufp;
3559 const char *string1, *string2;
3560 int size1, size2;
3561 int pos;
3562 struct re_registers *regs;
3563 int stop;
3564{
3565 int result = re_match_2_internal (bufp, string1, size1, string2, size2,
3566 pos, regs, stop);
3567 alloca (0);
3568 return result;
3569}
3570
3571/* This is a separate function so that we can force an alloca cleanup
3572 afterwards. */
3573static int
3574re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
3575 struct re_pattern_buffer *bufp;
3576 const char *string1, *string2;
3577 int size1, size2;
3578 int pos;
3579 struct re_registers *regs;
3580 int stop;
3581{
3582 /* General temporaries. */
3583 int mcnt;
3584 unsigned char *p1;
3585
3586 /* Just past the end of the corresponding string. */
3587 const char *end1, *end2;
3588
3589 /* Pointers into string1 and string2, just past the last characters in
3590 each to consider matching. */
3591 const char *end_match_1, *end_match_2;
3592
3593 /* Where we are in the data, and the end of the current string. */
3594 const char *d, *dend;
3595
3596 /* Where we are in the pattern, and the end of the pattern. */
3597 unsigned char *p = bufp->buffer;
3598 register unsigned char *pend = p + bufp->used;
3599
3600 /* Mark the opcode just after a start_memory, so we can test for an
3601 empty subpattern when we get to the stop_memory. */
3602 unsigned char *just_past_start_mem = 0;
3603
3604 /* We use this to map every character in the string. */
3605 RE_TRANSLATE_TYPE translate = bufp->translate;
3606
3607 /* Failure point stack. Each place that can handle a failure further
3608 down the line pushes a failure point on this stack. It consists of
3609 restart, regend, and reg_info for all registers corresponding to
3610 the subexpressions we're currently inside, plus the number of such
3611 registers, and, finally, two char *'s. The first char * is where
3612 to resume scanning the pattern; the second one is where to resume
3613 scanning the strings. If the latter is zero, the failure point is
3614 a ``dummy''; if a failure happens and the failure point is a dummy,
3615 it gets discarded and the next next one is tried. */
3616#ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
3617 fail_stack_type fail_stack;
3618#endif
3619#ifdef DEBUG
3620 static unsigned failure_id = 0;
3621 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
3622#endif
3623
3624 /* This holds the pointer to the failure stack, when
3625 it is allocated relocatably. */
3626#ifdef REL_ALLOC
3627 fail_stack_elt_t *failure_stack_ptr;
3628#endif
3629
3630 /* We fill all the registers internally, independent of what we
3631 return, for use in backreferences. The number here includes
3632 an element for register zero. */
3633 unsigned num_regs = bufp->re_nsub + 1;
3634
3635 /* The currently active registers. */
3636 unsigned lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3637 unsigned highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3638
3639 /* Information on the contents of registers. These are pointers into
3640 the input strings; they record just what was matched (on this
3641 attempt) by a subexpression part of the pattern, that is, the
3642 regnum-th regstart pointer points to where in the pattern we began
3643 matching and the regnum-th regend points to right after where we
3644 stopped matching the regnum-th subexpression. (The zeroth register
3645 keeps track of what the whole pattern matches.) */
3646#ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3647 const char **regstart, **regend;
3648#endif
3649
3650 /* If a group that's operated upon by a repetition operator fails to
3651 match anything, then the register for its start will need to be
3652 restored because it will have been set to wherever in the string we
3653 are when we last see its open-group operator. Similarly for a
3654 register's end. */
3655#ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3656 const char **old_regstart, **old_regend;
3657#endif
3658
3659 /* The is_active field of reg_info helps us keep track of which (possibly
3660 nested) subexpressions we are currently in. The matched_something
3661 field of reg_info[reg_num] helps us tell whether or not we have
3662 matched any of the pattern so far this time through the reg_num-th
3663 subexpression. These two fields get reset each time through any
3664 loop their register is in. */
3665#ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
3666 register_info_type *reg_info;
3667#endif
3668
3669 /* The following record the register info as found in the above
3670 variables when we find a match better than any we've seen before.
3671 This happens as we backtrack through the failure points, which in
3672 turn happens only if we have not yet matched the entire string. */
3673 unsigned best_regs_set = false;
3674#ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3675 const char **best_regstart, **best_regend;
3676#endif
3677
3678 /* Logically, this is `best_regend[0]'. But we don't want to have to
3679 allocate space for that if we're not allocating space for anything
3680 else (see below). Also, we never need info about register 0 for
3681 any of the other register vectors, and it seems rather a kludge to
3682 treat `best_regend' differently than the rest. So we keep track of
3683 the end of the best match so far in a separate variable. We
3684 initialize this to NULL so that when we backtrack the first time
3685 and need to test it, it's not garbage. */
3686 const char *match_end = NULL;
3687
3688 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
3689 int set_regs_matched_done = 0;
3690
3691 /* Used when we pop values we don't care about. */
3692#ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3693 const char **reg_dummy;
3694 register_info_type *reg_info_dummy;
3695#endif
3696
3697#ifdef DEBUG
3698 /* Counts the total number of registers pushed. */
3699 unsigned num_regs_pushed = 0;
3700#endif
3701
3702 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
3703
3704 INIT_FAIL_STACK ();
3705
3706#ifdef MATCH_MAY_ALLOCATE
3707 /* Do not bother to initialize all the register variables if there are
3708 no groups in the pattern, as it takes a fair amount of time. If
3709 there are groups, we include space for register 0 (the whole
3710 pattern), even though we never use it, since it simplifies the
3711 array indexing. We should fix this. */
3712 if (bufp->re_nsub)
3713 {
3714 regstart = REGEX_TALLOC (num_regs, const char *);
3715 regend = REGEX_TALLOC (num_regs, const char *);
3716 old_regstart = REGEX_TALLOC (num_regs, const char *);
3717 old_regend = REGEX_TALLOC (num_regs, const char *);
3718 best_regstart = REGEX_TALLOC (num_regs, const char *);
3719 best_regend = REGEX_TALLOC (num_regs, const char *);
3720 reg_info = REGEX_TALLOC (num_regs, register_info_type);
3721 reg_dummy = REGEX_TALLOC (num_regs, const char *);
3722 reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
3723
3724 if (!(regstart && regend && old_regstart && old_regend && reg_info
3725 && best_regstart && best_regend && reg_dummy && reg_info_dummy))
3726 {
3727 FREE_VARIABLES ();
3728 return -2;
3729 }
3730 }
3731 else
3732 {
3733 /* We must initialize all our variables to NULL, so that
3734 `FREE_VARIABLES' doesn't try to free them. */
3735 regstart = regend = old_regstart = old_regend = best_regstart
3736 = best_regend = reg_dummy = NULL;
3737 reg_info = reg_info_dummy = (register_info_type *) NULL;
3738 }
3739#endif /* MATCH_MAY_ALLOCATE */
3740
3741 /* The starting position is bogus. */
3742 if (pos < 0 || pos > size1 + size2)
3743 {
3744 FREE_VARIABLES ();
3745 return -1;
3746 }
3747
3748 /* Initialize subexpression text positions to -1 to mark ones that no
3749 start_memory/stop_memory has been seen for. Also initialize the
3750 register information struct. */
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +02003751 for (mcnt = 1; mcnt < (int) num_regs; mcnt++)
Tanguy Pruvot36efc942011-11-20 14:41:41 +01003752 {
3753 regstart[mcnt] = regend[mcnt]
3754 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
3755
3756 REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
3757 IS_ACTIVE (reg_info[mcnt]) = 0;
3758 MATCHED_SOMETHING (reg_info[mcnt]) = 0;
3759 EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
3760 }
3761
3762 /* We move `string1' into `string2' if the latter's empty -- but not if
3763 `string1' is null. */
3764 if (size2 == 0 && string1 != NULL)
3765 {
3766 string2 = string1;
3767 size2 = size1;
3768 string1 = 0;
3769 size1 = 0;
3770 }
3771 end1 = string1 + size1;
3772 end2 = string2 + size2;
3773
3774 /* Compute where to stop matching, within the two strings. */
3775 if (stop <= size1)
3776 {
3777 end_match_1 = string1 + stop;
3778 end_match_2 = string2;
3779 }
3780 else
3781 {
3782 end_match_1 = end1;
3783 end_match_2 = string2 + stop - size1;
3784 }
3785
3786 /* `p' scans through the pattern as `d' scans through the data.
3787 `dend' is the end of the input string that `d' points within. `d'
3788 is advanced into the following input string whenever necessary, but
3789 this happens before fetching; therefore, at the beginning of the
3790 loop, `d' can be pointing at the end of a string, but it cannot
3791 equal `string2'. */
3792 if (size1 > 0 && pos <= size1)
3793 {
3794 d = string1 + pos;
3795 dend = end_match_1;
3796 }
3797 else
3798 {
3799 d = string2 + pos - size1;
3800 dend = end_match_2;
3801 }
3802
3803 DEBUG_PRINT1 ("The compiled pattern is: ");
3804 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
3805 DEBUG_PRINT1 ("The string to match is: `");
3806 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
3807 DEBUG_PRINT1 ("'\n");
3808
3809 /* This loops over pattern commands. It exits by returning from the
3810 function if the match is complete, or it drops through if the match
3811 fails at this starting point in the input data. */
3812 for (;;)
3813 {
3814 DEBUG_PRINT2 ("\n0x%x: ", p);
3815
3816 if (p == pend)
3817 { /* End of pattern means we might have succeeded. */
3818 DEBUG_PRINT1 ("end of pattern ... ");
3819
3820 /* If we haven't matched the entire string, and we want the
3821 longest match, try backtracking. */
3822 if (d != end_match_2)
3823 {
3824 /* 1 if this match ends in the same string (string1 or string2)
3825 as the best previous match. */
3826 boolean same_str_p = (FIRST_STRING_P (match_end)
3827 == MATCHING_IN_FIRST_STRING);
3828 /* 1 if this match is the best seen so far. */
3829 boolean best_match_p;
3830
3831 /* AIX compiler got confused when this was combined
3832 with the previous declaration. */
3833 if (same_str_p)
3834 best_match_p = d > match_end;
3835 else
3836 best_match_p = !MATCHING_IN_FIRST_STRING;
3837
3838 DEBUG_PRINT1 ("backtracking.\n");
3839
3840 if (!FAIL_STACK_EMPTY ())
3841 { /* More failure points to try. */
3842
3843 /* If exceeds best match so far, save it. */
3844 if (!best_regs_set || best_match_p)
3845 {
3846 best_regs_set = true;
3847 match_end = d;
3848
3849 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
3850
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +02003851 for (mcnt = 1; mcnt < (int) num_regs; mcnt++)
Tanguy Pruvot36efc942011-11-20 14:41:41 +01003852 {
3853 best_regstart[mcnt] = regstart[mcnt];
3854 best_regend[mcnt] = regend[mcnt];
3855 }
3856 }
3857 goto fail;
3858 }
3859
3860 /* If no failure points, don't restore garbage. And if
3861 last match is real best match, don't restore second
3862 best one. */
3863 else if (best_regs_set && !best_match_p)
3864 {
3865 restore_best_regs:
3866 /* Restore best match. It may happen that `dend ==
3867 end_match_1' while the restored d is in string2.
3868 For example, the pattern `x.*y.*z' against the
3869 strings `x-' and `y-z-', if the two strings are
3870 not consecutive in memory. */
3871 DEBUG_PRINT1 ("Restoring best registers.\n");
3872
3873 d = match_end;
3874 dend = ((d >= string1 && d <= end1)
3875 ? end_match_1 : end_match_2);
3876
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +02003877 for (mcnt = 1; mcnt < (int) num_regs; mcnt++)
Tanguy Pruvot36efc942011-11-20 14:41:41 +01003878 {
3879 regstart[mcnt] = best_regstart[mcnt];
3880 regend[mcnt] = best_regend[mcnt];
3881 }
3882 }
3883 } /* d != end_match_2 */
3884
3885 succeed_label:
3886 DEBUG_PRINT1 ("Accepting match.\n");
3887
3888 /* If caller wants register contents data back, do it. */
3889 if (regs && !bufp->no_sub)
3890 {
3891 /* Have the register data arrays been allocated? */
3892 if (bufp->regs_allocated == REGS_UNALLOCATED)
3893 { /* No. So allocate them with malloc. We need one
3894 extra element beyond `num_regs' for the `-1' marker
3895 GNU code uses. */
3896 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
3897 regs->start = TALLOC (regs->num_regs, regoff_t);
3898 regs->end = TALLOC (regs->num_regs, regoff_t);
3899 if (regs->start == NULL || regs->end == NULL)
3900 {
3901 FREE_VARIABLES ();
3902 return -2;
3903 }
3904 bufp->regs_allocated = REGS_REALLOCATE;
3905 }
3906 else if (bufp->regs_allocated == REGS_REALLOCATE)
3907 { /* Yes. If we need more elements than were already
3908 allocated, reallocate them. If we need fewer, just
3909 leave it alone. */
3910 if (regs->num_regs < num_regs + 1)
3911 {
3912 regs->num_regs = num_regs + 1;
3913 RETALLOC (regs->start, regs->num_regs, regoff_t);
3914 RETALLOC (regs->end, regs->num_regs, regoff_t);
3915 if (regs->start == NULL || regs->end == NULL)
3916 {
3917 FREE_VARIABLES ();
3918 return -2;
3919 }
3920 }
3921 }
3922 else
3923 {
3924 /* These braces fend off a "empty body in an else-statement"
3925 warning under GCC when assert expands to nothing. */
3926 assert (bufp->regs_allocated == REGS_FIXED);
3927 }
3928
3929 /* Convert the pointer data in `regstart' and `regend' to
3930 indices. Register zero has to be set differently,
3931 since we haven't kept track of any info for it. */
3932 if (regs->num_regs > 0)
3933 {
3934 regs->start[0] = pos;
3935 regs->end[0] = (MATCHING_IN_FIRST_STRING
3936 ? ((regoff_t) (d - string1))
3937 : ((regoff_t) (d - string2 + size1)));
3938 }
3939
3940 /* Go through the first `min (num_regs, regs->num_regs)'
3941 registers, since that is all we initialized. */
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +02003942 for (mcnt = 1; mcnt < (int) MIN (num_regs, regs->num_regs); mcnt++)
Tanguy Pruvot36efc942011-11-20 14:41:41 +01003943 {
3944 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
3945 regs->start[mcnt] = regs->end[mcnt] = -1;
3946 else
3947 {
3948 regs->start[mcnt]
3949 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
3950 regs->end[mcnt]
3951 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
3952 }
3953 }
3954
3955 /* If the regs structure we return has more elements than
3956 were in the pattern, set the extra elements to -1. If
3957 we (re)allocated the registers, this is the case,
3958 because we always allocate enough to have at least one
3959 -1 at the end. */
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +02003960 for (mcnt = num_regs; mcnt < (int) regs->num_regs; mcnt++)
Tanguy Pruvot36efc942011-11-20 14:41:41 +01003961 regs->start[mcnt] = regs->end[mcnt] = -1;
3962 } /* regs && !bufp->no_sub */
3963
3964 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
3965 nfailure_points_pushed, nfailure_points_popped,
3966 nfailure_points_pushed - nfailure_points_popped);
3967 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
3968
3969 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
3970 ? string1
3971 : string2 - size1);
3972
3973 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
3974
3975 FREE_VARIABLES ();
3976 return mcnt;
3977 }
3978
3979 /* Otherwise match next pattern command. */
3980 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
3981 {
3982 /* Ignore these. Used to ignore the n of succeed_n's which
3983 currently have n == 0. */
3984 case no_op:
3985 DEBUG_PRINT1 ("EXECUTING no_op.\n");
3986 break;
3987
3988 case succeed:
3989 DEBUG_PRINT1 ("EXECUTING succeed.\n");
3990 goto succeed_label;
3991
3992 /* Match the next n pattern characters exactly. The following
3993 byte in the pattern defines n, and the n bytes after that
3994 are the characters to match. */
3995 case exactn:
3996 mcnt = *p++;
3997 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
3998
3999 /* This is written out as an if-else so we don't waste time
4000 testing `translate' inside the loop. */
4001 if (translate)
4002 {
4003 do
4004 {
4005 PREFETCH ();
4006 if ((unsigned char) translate[(unsigned char) *d++]
4007 != (unsigned char) *p++)
4008 goto fail;
4009 }
4010 while (--mcnt);
4011 }
4012 else
4013 {
4014 do
4015 {
4016 PREFETCH ();
4017 if (*d++ != (char) *p++) goto fail;
4018 }
4019 while (--mcnt);
4020 }
4021 SET_REGS_MATCHED ();
4022 break;
4023
4024
4025 /* Match any character except possibly a newline or a null. */
4026 case anychar:
4027 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4028
4029 PREFETCH ();
4030
4031 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
4032 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
4033 goto fail;
4034
4035 SET_REGS_MATCHED ();
4036 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
4037 d++;
4038 break;
4039
4040
4041 case charset:
4042 case charset_not:
4043 {
4044 register unsigned char c;
4045 boolean not = (re_opcode_t) *(p - 1) == charset_not;
4046
4047 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
4048
4049 PREFETCH ();
4050 c = TRANSLATE (*d); /* The character to match. */
4051
4052 /* Cast to `unsigned' instead of `unsigned char' in case the
4053 bit list is a full 32 bytes long. */
4054 if (c < (unsigned) (*p * BYTEWIDTH)
4055 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4056 not = !not;
4057
4058 p += 1 + *p;
4059
4060 if (!not) goto fail;
4061
4062 SET_REGS_MATCHED ();
4063 d++;
4064 break;
4065 }
4066
4067
4068 /* The beginning of a group is represented by start_memory.
4069 The arguments are the register number in the next byte, and the
4070 number of groups inner to this one in the next. The text
4071 matched within the group is recorded (in the internal
4072 registers data structure) under the register number. */
4073 case start_memory:
4074 DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
4075
4076 /* Find out if this group can match the empty string. */
4077 p1 = p; /* To send to group_match_null_string_p. */
4078
4079 if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
4080 REG_MATCH_NULL_STRING_P (reg_info[*p])
4081 = group_match_null_string_p (&p1, pend, reg_info);
4082
4083 /* Save the position in the string where we were the last time
4084 we were at this open-group operator in case the group is
4085 operated upon by a repetition operator, e.g., with `(a*)*b'
4086 against `ab'; then we want to ignore where we are now in
4087 the string in case this attempt to match fails. */
4088 old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4089 ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
4090 : regstart[*p];
4091 DEBUG_PRINT2 (" old_regstart: %d\n",
4092 POINTER_TO_OFFSET (old_regstart[*p]));
4093
4094 regstart[*p] = d;
4095 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
4096
4097 IS_ACTIVE (reg_info[*p]) = 1;
4098 MATCHED_SOMETHING (reg_info[*p]) = 0;
4099
4100 /* Clear this whenever we change the register activity status. */
4101 set_regs_matched_done = 0;
4102
4103 /* This is the new highest active register. */
4104 highest_active_reg = *p;
4105
4106 /* If nothing was active before, this is the new lowest active
4107 register. */
4108 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4109 lowest_active_reg = *p;
4110
4111 /* Move past the register number and inner group count. */
4112 p += 2;
4113 just_past_start_mem = p;
4114
4115 break;
4116
4117
4118 /* The stop_memory opcode represents the end of a group. Its
4119 arguments are the same as start_memory's: the register
4120 number, and the number of inner groups. */
4121 case stop_memory:
4122 DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
4123
4124 /* We need to save the string position the last time we were at
4125 this close-group operator in case the group is operated
4126 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
4127 against `aba'; then we want to ignore where we are now in
4128 the string in case this attempt to match fails. */
4129 old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4130 ? REG_UNSET (regend[*p]) ? d : regend[*p]
4131 : regend[*p];
4132 DEBUG_PRINT2 (" old_regend: %d\n",
4133 POINTER_TO_OFFSET (old_regend[*p]));
4134
4135 regend[*p] = d;
4136 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
4137
4138 /* This register isn't active anymore. */
4139 IS_ACTIVE (reg_info[*p]) = 0;
4140
4141 /* Clear this whenever we change the register activity status. */
4142 set_regs_matched_done = 0;
4143
4144 /* If this was the only register active, nothing is active
4145 anymore. */
4146 if (lowest_active_reg == highest_active_reg)
4147 {
4148 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4149 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4150 }
4151 else
4152 { /* We must scan for the new highest active register, since
4153 it isn't necessarily one less than now: consider
4154 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
4155 new highest active register is 1. */
4156 unsigned char r = *p - 1;
4157 while (r > 0 && !IS_ACTIVE (reg_info[r]))
4158 r--;
4159
4160 /* If we end up at register zero, that means that we saved
4161 the registers as the result of an `on_failure_jump', not
4162 a `start_memory', and we jumped to past the innermost
4163 `stop_memory'. For example, in ((.)*) we save
4164 registers 1 and 2 as a result of the *, but when we pop
4165 back to the second ), we are at the stop_memory 1.
4166 Thus, nothing is active. */
4167 if (r == 0)
4168 {
4169 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4170 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4171 }
4172 else
4173 highest_active_reg = r;
4174 }
4175
4176 /* If just failed to match something this time around with a
4177 group that's operated on by a repetition operator, try to
4178 force exit from the ``loop'', and restore the register
4179 information for this group that we had before trying this
4180 last match. */
4181 if ((!MATCHED_SOMETHING (reg_info[*p])
4182 || just_past_start_mem == p - 1)
4183 && (p + 2) < pend)
4184 {
4185 boolean is_a_jump_n = false;
4186
4187 p1 = p + 2;
4188 mcnt = 0;
4189 switch ((re_opcode_t) *p1++)
4190 {
4191 case jump_n:
4192 is_a_jump_n = true;
4193 case pop_failure_jump:
4194 case maybe_pop_jump:
4195 case jump:
4196 case dummy_failure_jump:
4197 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4198 if (is_a_jump_n)
4199 p1 += 2;
4200 break;
4201
4202 default:
4203 /* do nothing */ ;
4204 }
4205 p1 += mcnt;
4206
4207 /* If the next operation is a jump backwards in the pattern
4208 to an on_failure_jump right before the start_memory
4209 corresponding to this stop_memory, exit from the loop
4210 by forcing a failure after pushing on the stack the
4211 on_failure_jump's jump in the pattern, and d. */
4212 if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
4213 && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
4214 {
4215 /* If this group ever matched anything, then restore
4216 what its registers were before trying this last
4217 failed match, e.g., with `(a*)*b' against `ab' for
4218 regstart[1], and, e.g., with `((a*)*(b*)*)*'
4219 against `aba' for regend[3].
4220
4221 Also restore the registers for inner groups for,
4222 e.g., `((a*)(b*))*' against `aba' (register 3 would
4223 otherwise get trashed). */
4224
4225 if (EVER_MATCHED_SOMETHING (reg_info[*p]))
4226 {
4227 unsigned r;
4228
4229 EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
4230
4231 /* Restore this and inner groups' (if any) registers. */
4232 for (r = *p; r < *p + *(p + 1); r++)
4233 {
4234 regstart[r] = old_regstart[r];
4235
4236 /* xx why this test? */
4237 if (old_regend[r] >= regstart[r])
4238 regend[r] = old_regend[r];
4239 }
4240 }
4241 p1++;
4242 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4243 PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
4244
4245 goto fail;
4246 }
4247 }
4248
4249 /* Move past the register number and the inner group count. */
4250 p += 2;
4251 break;
4252
4253
4254 /* \<digit> has been turned into a `duplicate' command which is
4255 followed by the numeric value of <digit> as the register number. */
4256 case duplicate:
4257 {
4258 register const char *d2, *dend2;
4259 int regno = *p++; /* Get which register to match against. */
4260 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
4261
4262 /* Can't back reference a group which we've never matched. */
4263 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
4264 goto fail;
4265
4266 /* Where in input to try to start matching. */
4267 d2 = regstart[regno];
4268
4269 /* Where to stop matching; if both the place to start and
4270 the place to stop matching are in the same string, then
4271 set to the place to stop, otherwise, for now have to use
4272 the end of the first string. */
4273
4274 dend2 = ((FIRST_STRING_P (regstart[regno])
4275 == FIRST_STRING_P (regend[regno]))
4276 ? regend[regno] : end_match_1);
4277 for (;;)
4278 {
4279 /* If necessary, advance to next segment in register
4280 contents. */
4281 while (d2 == dend2)
4282 {
4283 if (dend2 == end_match_2) break;
4284 if (dend2 == regend[regno]) break;
4285
4286 /* End of string1 => advance to string2. */
4287 d2 = string2;
4288 dend2 = regend[regno];
4289 }
4290 /* At end of register contents => success */
4291 if (d2 == dend2) break;
4292
4293 /* If necessary, advance to next segment in data. */
4294 PREFETCH ();
4295
4296 /* How many characters left in this segment to match. */
4297 mcnt = dend - d;
4298
4299 /* Want how many consecutive characters we can match in
4300 one shot, so, if necessary, adjust the count. */
4301 if (mcnt > dend2 - d2)
4302 mcnt = dend2 - d2;
4303
4304 /* Compare that many; failure if mismatch, else move
4305 past them. */
4306 if (translate
4307 ? bcmp_translate (d, d2, mcnt, translate)
4308 : bcmp (d, d2, mcnt))
4309 goto fail;
4310 d += mcnt, d2 += mcnt;
4311
4312 /* Do this because we've match some characters. */
4313 SET_REGS_MATCHED ();
4314 }
4315 }
4316 break;
4317
4318
4319 /* begline matches the empty string at the beginning of the string
4320 (unless `not_bol' is set in `bufp'), and, if
4321 `newline_anchor' is set, after newlines. */
4322 case begline:
4323 DEBUG_PRINT1 ("EXECUTING begline.\n");
4324
4325 if (AT_STRINGS_BEG (d))
4326 {
4327 if (!bufp->not_bol) break;
4328 }
4329 else if (d[-1] == '\n' && bufp->newline_anchor)
4330 {
4331 break;
4332 }
4333 /* In all other cases, we fail. */
4334 goto fail;
4335
4336
4337 /* endline is the dual of begline. */
4338 case endline:
4339 DEBUG_PRINT1 ("EXECUTING endline.\n");
4340
4341 if (AT_STRINGS_END (d))
4342 {
4343 if (!bufp->not_eol) break;
4344 }
4345
4346 /* We have to ``prefetch'' the next character. */
4347 else if ((d == end1 ? *string2 : *d) == '\n'
4348 && bufp->newline_anchor)
4349 {
4350 break;
4351 }
4352 goto fail;
4353
4354
4355 /* Match at the very beginning of the data. */
4356 case begbuf:
4357 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
4358 if (AT_STRINGS_BEG (d))
4359 break;
4360 goto fail;
4361
4362
4363 /* Match at the very end of the data. */
4364 case endbuf:
4365 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
4366 if (AT_STRINGS_END (d))
4367 break;
4368 goto fail;
4369
4370
4371 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
4372 pushes NULL as the value for the string on the stack. Then
4373 `pop_failure_point' will keep the current value for the
4374 string, instead of restoring it. To see why, consider
4375 matching `foo\nbar' against `.*\n'. The .* matches the foo;
4376 then the . fails against the \n. But the next thing we want
4377 to do is match the \n against the \n; if we restored the
4378 string value, we would be back at the foo.
4379
4380 Because this is used only in specific cases, we don't need to
4381 check all the things that `on_failure_jump' does, to make
4382 sure the right things get saved on the stack. Hence we don't
4383 share its code. The only reason to push anything on the
4384 stack at all is that otherwise we would have to change
4385 `anychar's code to do something besides goto fail in this
4386 case; that seems worse than this. */
4387 case on_failure_keep_string_jump:
4388 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
4389
4390 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4391 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
4392
4393 PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
4394 break;
4395
4396
4397 /* Uses of on_failure_jump:
4398
4399 Each alternative starts with an on_failure_jump that points
4400 to the beginning of the next alternative. Each alternative
4401 except the last ends with a jump that in effect jumps past
4402 the rest of the alternatives. (They really jump to the
4403 ending jump of the following alternative, because tensioning
4404 these jumps is a hassle.)
4405
4406 Repeats start with an on_failure_jump that points past both
4407 the repetition text and either the following jump or
4408 pop_failure_jump back to this on_failure_jump. */
4409 case on_failure_jump:
4410 on_failure:
4411 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
4412
4413 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4414 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
4415
4416 /* If this on_failure_jump comes right before a group (i.e.,
4417 the original * applied to a group), save the information
4418 for that group and all inner ones, so that if we fail back
4419 to this point, the group's information will be correct.
4420 For example, in \(a*\)*\1, we need the preceding group,
4421 and in \(zz\(a*\)b*\)\2, we need the inner group. */
4422
4423 /* We can't use `p' to check ahead because we push
4424 a failure point to `p + mcnt' after we do this. */
4425 p1 = p;
4426
4427 /* We need to skip no_op's before we look for the
4428 start_memory in case this on_failure_jump is happening as
4429 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
4430 against aba. */
4431 while (p1 < pend && (re_opcode_t) *p1 == no_op)
4432 p1++;
4433
4434 if (p1 < pend && (re_opcode_t) *p1 == start_memory)
4435 {
4436 /* We have a new highest active register now. This will
4437 get reset at the start_memory we are about to get to,
4438 but we will have saved all the registers relevant to
4439 this repetition op, as described above. */
4440 highest_active_reg = *(p1 + 1) + *(p1 + 2);
4441 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4442 lowest_active_reg = *(p1 + 1);
4443 }
4444
4445 DEBUG_PRINT1 (":\n");
4446 PUSH_FAILURE_POINT (p + mcnt, d, -2);
4447 break;
4448
4449
4450 /* A smart repeat ends with `maybe_pop_jump'.
4451 We change it to either `pop_failure_jump' or `jump'. */
4452 case maybe_pop_jump:
4453 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4454 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
4455 {
4456 register unsigned char *p2 = p;
4457
4458 /* Compare the beginning of the repeat with what in the
4459 pattern follows its end. If we can establish that there
4460 is nothing that they would both match, i.e., that we
4461 would have to backtrack because of (as in, e.g., `a*a')
4462 then we can change to pop_failure_jump, because we'll
4463 never have to backtrack.
4464
4465 This is not true in the case of alternatives: in
4466 `(a|ab)*' we do need to backtrack to the `ab' alternative
4467 (e.g., if the string was `ab'). But instead of trying to
4468 detect that here, the alternative has put on a dummy
4469 failure point which is what we will end up popping. */
4470
4471 /* Skip over open/close-group commands.
4472 If what follows this loop is a ...+ construct,
4473 look at what begins its body, since we will have to
4474 match at least one of that. */
4475 while (1)
4476 {
4477 if (p2 + 2 < pend
4478 && ((re_opcode_t) *p2 == stop_memory
4479 || (re_opcode_t) *p2 == start_memory))
4480 p2 += 3;
4481 else if (p2 + 6 < pend
4482 && (re_opcode_t) *p2 == dummy_failure_jump)
4483 p2 += 6;
4484 else
4485 break;
4486 }
4487
4488 p1 = p + mcnt;
4489 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
4490 to the `maybe_finalize_jump' of this case. Examine what
4491 follows. */
4492
4493 /* If we're at the end of the pattern, we can change. */
4494 if (p2 == pend)
4495 {
4496 /* Consider what happens when matching ":\(.*\)"
4497 against ":/". I don't really understand this code
4498 yet. */
4499 p[-3] = (unsigned char) pop_failure_jump;
4500 DEBUG_PRINT1
4501 (" End of pattern: change to `pop_failure_jump'.\n");
4502 }
4503
4504 else if ((re_opcode_t) *p2 == exactn
4505 || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
4506 {
4507 register unsigned char c
4508 = *p2 == (unsigned char) endline ? '\n' : p2[2];
4509
4510 if ((re_opcode_t) p1[3] == exactn && p1[5] != c)
4511 {
4512 p[-3] = (unsigned char) pop_failure_jump;
4513 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
4514 c, p1[5]);
4515 }
4516
4517 else if ((re_opcode_t) p1[3] == charset
4518 || (re_opcode_t) p1[3] == charset_not)
4519 {
4520 int not = (re_opcode_t) p1[3] == charset_not;
4521
4522 if (c < (unsigned char) (p1[4] * BYTEWIDTH)
4523 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4524 not = !not;
4525
4526 /* `not' is equal to 1 if c would match, which means
4527 that we can't change to pop_failure_jump. */
4528 if (!not)
4529 {
4530 p[-3] = (unsigned char) pop_failure_jump;
4531 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4532 }
4533 }
4534 }
4535 else if ((re_opcode_t) *p2 == charset)
4536 {
4537#ifdef DEBUG
4538 register unsigned char c
4539 = *p2 == (unsigned char) endline ? '\n' : p2[2];
4540#endif
4541
4542 if ((re_opcode_t) p1[3] == exactn
4543 && ! ((int) p2[1] * BYTEWIDTH > (int) p1[5]
4544 && (p2[2 + p1[5] / BYTEWIDTH]
4545 & (1 << (p1[5] % BYTEWIDTH)))))
4546 {
4547 p[-3] = (unsigned char) pop_failure_jump;
4548 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
4549 c, p1[5]);
4550 }
4551
4552 else if ((re_opcode_t) p1[3] == charset_not)
4553 {
4554 int idx;
4555 /* We win if the charset_not inside the loop
4556 lists every character listed in the charset after. */
4557 for (idx = 0; idx < (int) p2[1]; idx++)
4558 if (! (p2[2 + idx] == 0
4559 || (idx < (int) p1[4]
4560 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
4561 break;
4562
4563 if (idx == p2[1])
4564 {
4565 p[-3] = (unsigned char) pop_failure_jump;
4566 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4567 }
4568 }
4569 else if ((re_opcode_t) p1[3] == charset)
4570 {
4571 int idx;
4572 /* We win if the charset inside the loop
4573 has no overlap with the one after the loop. */
4574 for (idx = 0;
4575 idx < (int) p2[1] && idx < (int) p1[4];
4576 idx++)
4577 if ((p2[2 + idx] & p1[5 + idx]) != 0)
4578 break;
4579
4580 if (idx == p2[1] || idx == p1[4])
4581 {
4582 p[-3] = (unsigned char) pop_failure_jump;
4583 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4584 }
4585 }
4586 }
4587 }
4588 p -= 2; /* Point at relative address again. */
4589 if ((re_opcode_t) p[-1] != pop_failure_jump)
4590 {
4591 p[-1] = (unsigned char) jump;
4592 DEBUG_PRINT1 (" Match => jump.\n");
4593 goto unconditional_jump;
4594 }
4595 /* Note fall through. */
4596
4597
4598 /* The end of a simple repeat has a pop_failure_jump back to
4599 its matching on_failure_jump, where the latter will push a
4600 failure point. The pop_failure_jump takes off failure
4601 points put on by this pop_failure_jump's matching
4602 on_failure_jump; we got through the pattern to here from the
4603 matching on_failure_jump, so didn't fail. */
4604 case pop_failure_jump:
4605 {
4606 /* We need to pass separate storage for the lowest and
4607 highest registers, even though we don't care about the
4608 actual values. Otherwise, we will restore only one
4609 register from the stack, since lowest will == highest in
4610 `pop_failure_point'. */
4611 unsigned dummy_low_reg, dummy_high_reg;
4612 unsigned char *pdummy;
4613 const char *sdummy;
4614
4615 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
4616 POP_FAILURE_POINT (sdummy, pdummy,
4617 dummy_low_reg, dummy_high_reg,
4618 reg_dummy, reg_dummy, reg_info_dummy);
4619 }
4620 /* Note fall through. */
4621
4622
4623 /* Unconditionally jump (without popping any failure points). */
4624 case jump:
4625 unconditional_jump:
4626 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
4627 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
4628 p += mcnt; /* Do the jump. */
4629 DEBUG_PRINT2 ("(to 0x%x).\n", p);
4630 break;
4631
4632
4633 /* We need this opcode so we can detect where alternatives end
4634 in `group_match_null_string_p' et al. */
4635 case jump_past_alt:
4636 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
4637 goto unconditional_jump;
4638
4639
4640 /* Normally, the on_failure_jump pushes a failure point, which
4641 then gets popped at pop_failure_jump. We will end up at
4642 pop_failure_jump, also, and with a pattern of, say, `a+', we
4643 are skipping over the on_failure_jump, so we have to push
4644 something meaningless for pop_failure_jump to pop. */
4645 case dummy_failure_jump:
4646 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
4647 /* It doesn't matter what we push for the string here. What
4648 the code at `fail' tests is the value for the pattern. */
4649 PUSH_FAILURE_POINT (0, 0, -2);
4650 goto unconditional_jump;
4651
4652
4653 /* At the end of an alternative, we need to push a dummy failure
4654 point in case we are followed by a `pop_failure_jump', because
4655 we don't want the failure point for the alternative to be
4656 popped. For example, matching `(a|ab)*' against `aab'
4657 requires that we match the `ab' alternative. */
4658 case push_dummy_failure:
4659 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
4660 /* See comments just above at `dummy_failure_jump' about the
4661 two zeroes. */
4662 PUSH_FAILURE_POINT (0, 0, -2);
4663 break;
4664
4665 /* Have to succeed matching what follows at least n times.
4666 After that, handle like `on_failure_jump'. */
4667 case succeed_n:
4668 EXTRACT_NUMBER (mcnt, p + 2);
4669 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
4670
4671 assert (mcnt >= 0);
4672 /* Originally, this is how many times we HAVE to succeed. */
4673 if (mcnt > 0)
4674 {
4675 mcnt--;
4676 p += 2;
4677 STORE_NUMBER_AND_INCR (p, mcnt);
4678 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p, mcnt);
4679 }
4680 else if (mcnt == 0)
4681 {
4682 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n", p+2);
4683 p[2] = (unsigned char) no_op;
4684 p[3] = (unsigned char) no_op;
4685 goto on_failure;
4686 }
4687 break;
4688
4689 case jump_n:
4690 EXTRACT_NUMBER (mcnt, p + 2);
4691 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
4692
4693 /* Originally, this is how many times we CAN jump. */
4694 if (mcnt)
4695 {
4696 mcnt--;
4697 STORE_NUMBER (p + 2, mcnt);
4698 goto unconditional_jump;
4699 }
4700 /* If don't have to jump any more, skip over the rest of command. */
4701 else
4702 p += 4;
4703 break;
4704
4705 case set_number_at:
4706 {
4707 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
4708
4709 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4710 p1 = p + mcnt;
4711 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4712 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
4713 STORE_NUMBER (p1, mcnt);
4714 break;
4715 }
4716
4717#if 0
4718 /* The DEC Alpha C compiler 3.x generates incorrect code for the
4719 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4720 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4721 macro and introducing temporary variables works around the bug. */
4722
4723 case wordbound:
4724 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
4725 if (AT_WORD_BOUNDARY (d))
4726 break;
4727 goto fail;
4728
4729 case notwordbound:
4730 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
4731 if (AT_WORD_BOUNDARY (d))
4732 goto fail;
4733 break;
4734#else
4735 case wordbound:
4736 {
4737 boolean prevchar, thischar;
4738
4739 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
4740 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
4741 break;
4742
4743 prevchar = WORDCHAR_P (d - 1);
4744 thischar = WORDCHAR_P (d);
4745 if (prevchar != thischar)
4746 break;
4747 goto fail;
4748 }
4749
4750 case notwordbound:
4751 {
4752 boolean prevchar, thischar;
4753
4754 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
4755 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
4756 goto fail;
4757
4758 prevchar = WORDCHAR_P (d - 1);
4759 thischar = WORDCHAR_P (d);
4760 if (prevchar != thischar)
4761 goto fail;
4762 break;
4763 }
4764#endif
4765
4766 case wordbeg:
4767 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
4768 if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
4769 break;
4770 goto fail;
4771
4772 case wordend:
4773 DEBUG_PRINT1 ("EXECUTING wordend.\n");
4774 if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
4775 && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
4776 break;
4777 goto fail;
4778
4779#ifdef emacs
4780 case before_dot:
4781 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
4782 if (PTR_CHAR_POS ((unsigned char *) d) >= PT)
4783 goto fail;
4784 break;
4785
4786 case at_dot:
4787 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
4788 if (PTR_CHAR_POS ((unsigned char *) d) != PT)
4789 goto fail;
4790 break;
4791
4792 case after_dot:
4793 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
4794 if (PTR_CHAR_POS ((unsigned char *) d) <= PT)
4795 goto fail;
4796 break;
4797
4798 case syntaxspec:
4799 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
4800 mcnt = *p++;
4801 goto matchsyntax;
4802
4803 case wordchar:
4804 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
4805 mcnt = (int) Sword;
4806 matchsyntax:
4807 PREFETCH ();
4808 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
4809 d++;
4810 if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt)
4811 goto fail;
4812 SET_REGS_MATCHED ();
4813 break;
4814
4815 case notsyntaxspec:
4816 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
4817 mcnt = *p++;
4818 goto matchnotsyntax;
4819
4820 case notwordchar:
4821 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
4822 mcnt = (int) Sword;
4823 matchnotsyntax:
4824 PREFETCH ();
4825 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
4826 d++;
4827 if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt)
4828 goto fail;
4829 SET_REGS_MATCHED ();
4830 break;
4831
4832#else /* not emacs */
4833 case wordchar:
4834 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
4835 PREFETCH ();
4836 if (!WORDCHAR_P (d))
4837 goto fail;
4838 SET_REGS_MATCHED ();
4839 d++;
4840 break;
4841
4842 case notwordchar:
4843 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
4844 PREFETCH ();
4845 if (WORDCHAR_P (d))
4846 goto fail;
4847 SET_REGS_MATCHED ();
4848 d++;
4849 break;
4850#endif /* not emacs */
4851
4852 default:
4853 abort ();
4854 }
4855 continue; /* Successfully executed one pattern command; keep going. */
4856
4857
4858 /* We goto here if a matching operation fails. */
4859 fail:
4860 if (!FAIL_STACK_EMPTY ())
4861 { /* A restart point is known. Restore to that state. */
4862 DEBUG_PRINT1 ("\nFAIL:\n");
4863 POP_FAILURE_POINT (d, p,
4864 lowest_active_reg, highest_active_reg,
4865 regstart, regend, reg_info);
4866
4867 /* If this failure point is a dummy, try the next one. */
4868 if (!p)
4869 goto fail;
4870
4871 /* If we failed to the end of the pattern, don't examine *p. */
4872 assert (p <= pend);
4873 if (p < pend)
4874 {
4875 boolean is_a_jump_n = false;
4876
4877 /* If failed to a backwards jump that's part of a repetition
4878 loop, need to pop this failure point and use the next one. */
4879 switch ((re_opcode_t) *p)
4880 {
4881 case jump_n:
4882 is_a_jump_n = true;
4883 case maybe_pop_jump:
4884 case pop_failure_jump:
4885 case jump:
4886 p1 = p + 1;
4887 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4888 p1 += mcnt;
4889
4890 if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
4891 || (!is_a_jump_n
4892 && (re_opcode_t) *p1 == on_failure_jump))
4893 goto fail;
4894 break;
4895 default:
4896 /* do nothing */ ;
4897 }
4898 }
4899
4900 if (d >= string1 && d <= end1)
4901 dend = end_match_1;
4902 }
4903 else
4904 break; /* Matching at this starting point really fails. */
4905 } /* for (;;) */
4906
4907 if (best_regs_set)
4908 goto restore_best_regs;
4909
4910 FREE_VARIABLES ();
4911
4912 return -1; /* Failure to match. */
4913} /* re_match_2 */
4914
4915/* Subroutine definitions for re_match_2. */
4916
4917
4918/* We are passed P pointing to a register number after a start_memory.
4919
4920 Return true if the pattern up to the corresponding stop_memory can
4921 match the empty string, and false otherwise.
4922
4923 If we find the matching stop_memory, sets P to point to one past its number.
4924 Otherwise, sets P to an undefined byte less than or equal to END.
4925
4926 We don't handle duplicates properly (yet). */
4927
4928static boolean
4929group_match_null_string_p (p, end, reg_info)
4930 unsigned char **p, *end;
4931 register_info_type *reg_info;
4932{
4933 int mcnt;
4934 /* Point to after the args to the start_memory. */
4935 unsigned char *p1 = *p + 2;
4936
4937 while (p1 < end)
4938 {
4939 /* Skip over opcodes that can match nothing, and return true or
4940 false, as appropriate, when we get to one that can't, or to the
4941 matching stop_memory. */
4942
4943 switch ((re_opcode_t) *p1)
4944 {
4945 /* Could be either a loop or a series of alternatives. */
4946 case on_failure_jump:
4947 p1++;
4948 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4949
4950 /* If the next operation is not a jump backwards in the
4951 pattern. */
4952
4953 if (mcnt >= 0)
4954 {
4955 /* Go through the on_failure_jumps of the alternatives,
4956 seeing if any of the alternatives cannot match nothing.
4957 The last alternative starts with only a jump,
4958 whereas the rest start with on_failure_jump and end
4959 with a jump, e.g., here is the pattern for `a|b|c':
4960
4961 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
4962 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
4963 /exactn/1/c
4964
4965 So, we have to first go through the first (n-1)
4966 alternatives and then deal with the last one separately. */
4967
4968
4969 /* Deal with the first (n-1) alternatives, which start
4970 with an on_failure_jump (see above) that jumps to right
4971 past a jump_past_alt. */
4972
4973 while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
4974 {
4975 /* `mcnt' holds how many bytes long the alternative
4976 is, including the ending `jump_past_alt' and
4977 its number. */
4978
4979 if (!alt_match_null_string_p (p1, p1 + mcnt - 3,
4980 reg_info))
4981 return false;
4982
4983 /* Move to right after this alternative, including the
4984 jump_past_alt. */
4985 p1 += mcnt;
4986
4987 /* Break if it's the beginning of an n-th alternative
4988 that doesn't begin with an on_failure_jump. */
4989 if ((re_opcode_t) *p1 != on_failure_jump)
4990 break;
4991
4992 /* Still have to check that it's not an n-th
4993 alternative that starts with an on_failure_jump. */
4994 p1++;
4995 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4996 if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
4997 {
4998 /* Get to the beginning of the n-th alternative. */
4999 p1 -= 3;
5000 break;
5001 }
5002 }
5003
5004 /* Deal with the last alternative: go back and get number
5005 of the `jump_past_alt' just before it. `mcnt' contains
5006 the length of the alternative. */
5007 EXTRACT_NUMBER (mcnt, p1 - 2);
5008
5009 if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
5010 return false;
5011
5012 p1 += mcnt; /* Get past the n-th alternative. */
5013 } /* if mcnt > 0 */
5014 break;
5015
5016
5017 case stop_memory:
5018 assert (p1[1] == **p);
5019 *p = p1 + 2;
5020 return true;
5021
5022
5023 default:
5024 if (!common_op_match_null_string_p (&p1, end, reg_info))
5025 return false;
5026 }
5027 } /* while p1 < end */
5028
5029 return false;
5030} /* group_match_null_string_p */
5031
5032
5033/* Similar to group_match_null_string_p, but doesn't deal with alternatives:
5034 It expects P to be the first byte of a single alternative and END one
5035 byte past the last. The alternative can contain groups. */
5036
5037static boolean
5038alt_match_null_string_p (p, end, reg_info)
5039 unsigned char *p, *end;
5040 register_info_type *reg_info;
5041{
5042 int mcnt;
5043 unsigned char *p1 = p;
5044
5045 while (p1 < end)
5046 {
5047 /* Skip over opcodes that can match nothing, and break when we get
5048 to one that can't. */
5049
5050 switch ((re_opcode_t) *p1)
5051 {
5052 /* It's a loop. */
5053 case on_failure_jump:
5054 p1++;
5055 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5056 p1 += mcnt;
5057 break;
5058
5059 default:
5060 if (!common_op_match_null_string_p (&p1, end, reg_info))
5061 return false;
5062 }
5063 } /* while p1 < end */
5064
5065 return true;
5066} /* alt_match_null_string_p */
5067
5068
5069/* Deals with the ops common to group_match_null_string_p and
5070 alt_match_null_string_p.
5071
5072 Sets P to one after the op and its arguments, if any. */
5073
5074static boolean
5075common_op_match_null_string_p (p, end, reg_info)
5076 unsigned char **p, *end;
5077 register_info_type *reg_info;
5078{
5079 int mcnt;
5080 boolean ret;
5081 int reg_no;
5082 unsigned char *p1 = *p;
5083
5084 switch ((re_opcode_t) *p1++)
5085 {
5086 case no_op:
5087 case begline:
5088 case endline:
5089 case begbuf:
5090 case endbuf:
5091 case wordbeg:
5092 case wordend:
5093 case wordbound:
5094 case notwordbound:
5095#ifdef emacs
5096 case before_dot:
5097 case at_dot:
5098 case after_dot:
5099#endif
5100 break;
5101
5102 case start_memory:
5103 reg_no = *p1;
5104 assert (reg_no > 0 && reg_no <= MAX_REGNUM);
5105 ret = group_match_null_string_p (&p1, end, reg_info);
5106
5107 /* Have to set this here in case we're checking a group which
5108 contains a group and a back reference to it. */
5109
5110 if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
5111 REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
5112
5113 if (!ret)
5114 return false;
5115 break;
5116
5117 /* If this is an optimized succeed_n for zero times, make the jump. */
5118 case jump:
5119 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5120 if (mcnt >= 0)
5121 p1 += mcnt;
5122 else
5123 return false;
5124 break;
5125
5126 case succeed_n:
5127 /* Get to the number of times to succeed. */
5128 p1 += 2;
5129 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5130
5131 if (mcnt == 0)
5132 {
5133 p1 -= 4;
5134 EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5135 p1 += mcnt;
5136 }
5137 else
5138 return false;
5139 break;
5140
5141 case duplicate:
5142 if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
5143 return false;
5144 break;
5145
5146 case set_number_at:
5147 p1 += 4;
5148
5149 default:
5150 /* All other opcodes mean we cannot match the empty string. */
5151 return false;
5152 }
5153
5154 *p = p1;
5155 return true;
5156} /* common_op_match_null_string_p */
5157
5158
5159/* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5160 bytes; nonzero otherwise. */
5161
5162static int
5163bcmp_translate (s1, s2, len, translate)
5164 unsigned char *s1, *s2;
5165 register int len;
5166 RE_TRANSLATE_TYPE translate;
5167{
5168 register unsigned char *p1 = s1, *p2 = s2;
5169 while (len)
5170 {
5171 if (translate[*p1++] != translate[*p2++]) return 1;
5172 len--;
5173 }
5174 return 0;
5175}
5176
5177/* Entry points for GNU code. */
5178
5179/* re_compile_pattern is the GNU regular expression compiler: it
5180 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5181 Returns 0 if the pattern was valid, otherwise an error string.
5182
5183 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5184 are set in BUFP on entry.
5185
5186 We call regex_compile to do the actual compilation. */
5187
5188const char *
maxwen27116ba2015-08-14 21:41:28 +02005189bb_re_compile_pattern (pattern, length, bufp)
Tanguy Pruvot36efc942011-11-20 14:41:41 +01005190 const char *pattern;
5191 int length;
5192 struct re_pattern_buffer *bufp;
5193{
5194 reg_errcode_t ret;
5195
5196 /* GNU code is written to assume at least RE_NREGS registers will be set
5197 (and at least one extra will be -1). */
5198 bufp->regs_allocated = REGS_UNALLOCATED;
5199
5200 /* And GNU code determines whether or not to get register information
5201 by passing null for the REGS argument to re_match, etc., not by
5202 setting no_sub. */
5203 bufp->no_sub = 0;
5204
5205 /* Match anchors at newline. */
5206 bufp->newline_anchor = 1;
5207
5208 ret = regex_compile (pattern, length, re_syntax_options, bufp);
5209
5210 if (!ret)
5211 return NULL;
5212 return gettext (re_error_msgid[(int) ret]);
5213}
5214
5215/* Entry points compatible with 4.2 BSD regex library. We don't define
5216 them unless specifically requested. */
5217
5218#if defined (_REGEX_RE_COMP) || defined (_LIBC)
5219
5220/* BSD has one and only one pattern buffer. */
5221static struct re_pattern_buffer re_comp_buf;
5222
5223char *
5224#ifdef _LIBC
5225/* Make these definitions weak in libc, so POSIX programs can redefine
5226 these names if they don't use our functions, and still use
5227 regcomp/regexec below without link errors. */
5228weak_function
5229#endif
maxwen27116ba2015-08-14 21:41:28 +02005230bb_re_comp (s)
Tanguy Pruvot36efc942011-11-20 14:41:41 +01005231 const char *s;
5232{
5233 reg_errcode_t ret;
5234
5235 if (!s)
5236 {
5237 if (!re_comp_buf.buffer)
5238 return gettext ("No previous regular expression");
5239 return 0;
5240 }
5241
5242 if (!re_comp_buf.buffer)
5243 {
5244 re_comp_buf.buffer = (unsigned char *) malloc (200);
5245 if (re_comp_buf.buffer == NULL)
5246 return gettext (re_error_msgid[(int) REG_ESPACE]);
5247 re_comp_buf.allocated = 200;
5248
5249 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
5250 if (re_comp_buf.fastmap == NULL)
5251 return gettext (re_error_msgid[(int) REG_ESPACE]);
5252 }
5253
5254 /* Since `re_exec' always passes NULL for the `regs' argument, we
5255 don't need to initialize the pattern buffer fields which affect it. */
5256
5257 /* Match anchors at newlines. */
5258 re_comp_buf.newline_anchor = 1;
5259
5260 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
5261
5262 if (!ret)
5263 return NULL;
5264
5265 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5266 return (char *) gettext (re_error_msgid[(int) ret]);
5267}
5268
5269
5270int
5271#ifdef _LIBC
5272weak_function
5273#endif
maxwen27116ba2015-08-14 21:41:28 +02005274bb_re_exec (s)
Tanguy Pruvot36efc942011-11-20 14:41:41 +01005275 const char *s;
5276{
5277 const int len = strlen (s);
5278 return
maxwen27116ba2015-08-14 21:41:28 +02005279 0 <= bb_re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
Tanguy Pruvot36efc942011-11-20 14:41:41 +01005280}
5281#endif /* _REGEX_RE_COMP */
5282
5283/* POSIX.2 functions. Don't define these for Emacs. */
5284
5285#ifndef emacs
5286
5287/* regcomp takes a regular expression as a string and compiles it.
5288
5289 PREG is a regex_t *. We do not expect any fields to be initialized,
5290 since POSIX says we shouldn't. Thus, we set
5291
5292 `buffer' to the compiled pattern;
5293 `used' to the length of the compiled pattern;
5294 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
5295 REG_EXTENDED bit in CFLAGS is set; otherwise, to
5296 RE_SYNTAX_POSIX_BASIC;
5297 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
5298 `fastmap' and `fastmap_accurate' to zero;
5299 `re_nsub' to the number of subexpressions in PATTERN.
5300
5301 PATTERN is the address of the pattern string.
5302
5303 CFLAGS is a series of bits which affect compilation.
5304
5305 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
5306 use POSIX basic syntax.
5307
5308 If REG_NEWLINE is set, then . and [^...] don't match newline.
5309 Also, regexec will try a match beginning after every newline.
5310
5311 If REG_ICASE is set, then we considers upper- and lowercase
5312 versions of letters to be equivalent when matching.
5313
5314 If REG_NOSUB is set, then when PREG is passed to regexec, that
5315 routine will report only success or failure, and nothing about the
5316 registers.
5317
5318 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
5319 the return codes and their meanings.) */
5320int
5321#ifdef _LIBC
5322weak_function
5323#endif
maxwen27116ba2015-08-14 21:41:28 +02005324bb_regcomp (preg, pattern, cflags)
Tanguy Pruvot36efc942011-11-20 14:41:41 +01005325 regex_t *preg;
5326 const char *pattern;
5327 int cflags;
5328{
5329 reg_errcode_t ret;
5330 unsigned syntax
5331 = (cflags & REG_EXTENDED) ?
5332 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
5333
5334 /* regex_compile will allocate the space for the compiled pattern. */
5335 preg->buffer = 0;
5336 preg->allocated = 0;
5337 preg->used = 0;
5338
5339 /* Don't bother to use a fastmap when searching. This simplifies the
5340 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
5341 characters after newlines into the fastmap. This way, we just try
5342 every character. */
5343 preg->fastmap = 0;
5344
5345 if (cflags & REG_ICASE)
5346 {
5347 unsigned i;
5348
5349 preg->translate
5350 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
5351 * sizeof (*(RE_TRANSLATE_TYPE)0));
5352 if (preg->translate == NULL)
5353 return (int) REG_ESPACE;
5354
5355 /* Map uppercase characters to corresponding lowercase ones. */
5356 for (i = 0; i < CHAR_SET_SIZE; i++)
5357 preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
5358 }
5359 else
5360 preg->translate = NULL;
5361
5362 /* If REG_NEWLINE is set, newlines are treated differently. */
5363 if (cflags & REG_NEWLINE)
5364 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
5365 syntax &= ~RE_DOT_NEWLINE;
5366 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
5367 /* It also changes the matching behavior. */
5368 preg->newline_anchor = 1;
5369 }
5370 else
5371 preg->newline_anchor = 0;
5372
5373 preg->no_sub = !!(cflags & REG_NOSUB);
5374
5375 /* POSIX says a null character in the pattern terminates it, so we
5376 can use strlen here in compiling the pattern. */
5377 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
5378
5379 /* POSIX doesn't distinguish between an unmatched open-group and an
5380 unmatched close-group: both are REG_EPAREN. */
5381 if (ret == REG_ERPAREN) ret = REG_EPAREN;
5382
5383 return (int) ret;
5384}
5385
5386
5387/* regexec searches for a given pattern, specified by PREG, in the
5388 string STRING.
5389
5390 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
5391 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
5392 least NMATCH elements, and we set them to the offsets of the
5393 corresponding matched substrings.
5394
5395 EFLAGS specifies `execution flags' which affect matching: if
5396 REG_NOTBOL is set, then ^ does not match at the beginning of the
5397 string; if REG_NOTEOL is set, then $ does not match at the end.
5398
5399 We return 0 if we find a match and REG_NOMATCH if not. */
5400int
5401#ifdef _LIBC
5402weak_function
5403#endif
maxwen27116ba2015-08-14 21:41:28 +02005404bb_regexec (preg, string, nmatch, pmatch, eflags)
Tanguy Pruvot36efc942011-11-20 14:41:41 +01005405 const regex_t *preg;
5406 const char *string;
5407 size_t nmatch;
5408 regmatch_t pmatch[];
5409 int eflags;
5410{
5411 int ret;
5412 struct re_registers regs;
5413 regex_t private_preg;
5414 int len = strlen (string);
5415 boolean want_reg_info = !preg->no_sub && nmatch > 0;
5416
5417 private_preg = *preg;
5418
5419 private_preg.not_bol = !!(eflags & REG_NOTBOL);
5420 private_preg.not_eol = !!(eflags & REG_NOTEOL);
5421
5422 /* The user has told us exactly how many registers to return
5423 information about, via `nmatch'. We have to pass that on to the
5424 matching routines. */
5425 private_preg.regs_allocated = REGS_FIXED;
5426
5427 if (want_reg_info)
5428 {
5429 regs.num_regs = nmatch;
5430 regs.start = TALLOC (nmatch, regoff_t);
5431 regs.end = TALLOC (nmatch, regoff_t);
5432 if (regs.start == NULL || regs.end == NULL)
5433 return (int) REG_NOMATCH;
5434 }
5435
5436 /* Perform the searching operation. */
maxwen27116ba2015-08-14 21:41:28 +02005437 ret = bb_re_search (&private_preg, string, len,
Tanguy Pruvot36efc942011-11-20 14:41:41 +01005438 /* start: */ 0, /* range: */ len,
5439 want_reg_info ? &regs : (struct re_registers *) 0);
5440
5441 /* Copy the register information to the POSIX structure. */
5442 if (want_reg_info)
5443 {
5444 if (ret >= 0)
5445 {
5446 unsigned r;
5447
5448 for (r = 0; r < nmatch; r++)
5449 {
5450 pmatch[r].rm_so = regs.start[r];
5451 pmatch[r].rm_eo = regs.end[r];
5452 }
5453 }
5454
5455 /* If we needed the temporary register info, free the space now. */
5456 free (regs.start);
5457 free (regs.end);
5458 }
5459
5460 /* We want zero return to mean success, unlike `re_search'. */
5461 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
5462}
5463
5464
5465/* Returns a message corresponding to an error code, ERRCODE, returned
5466 from either regcomp or regexec. We don't use PREG here. */
5467size_t
5468#ifdef _LIBC
5469/* Make these definitions weak in libc, so POSIX programs can redefine
5470 these names if they don't use our functions, and still use
5471 regcomp/regexec below without link errors. */
5472weak_function
5473#endif
maxwen27116ba2015-08-14 21:41:28 +02005474bb_regerror (errcode, preg, errbuf, errbuf_size)
Tanguy Pruvot36efc942011-11-20 14:41:41 +01005475 int errcode;
5476 const regex_t *preg;
5477 char *errbuf;
5478 size_t errbuf_size;
5479{
5480 const char *msg;
5481 size_t msg_size;
5482
5483 if (errcode < 0
5484 || errcode >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
5485 /* Only error codes returned by the rest of the code should be passed
5486 to this routine. If we are given anything else, or if other regex
5487 code generates an invalid error code, then the program has a bug.
5488 Dump core so we can fix it. */
5489 abort ();
5490
5491 msg = gettext (re_error_msgid[errcode]);
5492
5493 msg_size = strlen (msg) + 1; /* Includes the null. */
5494
5495 if (errbuf_size != 0)
5496 {
5497 if (msg_size > errbuf_size)
5498 {
5499 strncpy (errbuf, msg, errbuf_size - 1);
5500 errbuf[errbuf_size - 1] = 0;
5501 }
5502 else
5503 strcpy (errbuf, msg);
5504 }
5505
5506 return msg_size;
5507}
5508
5509
5510/* Free dynamically allocated space used by PREG. */
5511
5512void
5513#ifdef _LIBC
5514/* Make these definitions weak in libc, so POSIX programs can redefine
5515 these names if they don't use our functions, and still use
5516 regcomp/regexec below without link errors. */
5517weak_function
5518#endif
maxwen27116ba2015-08-14 21:41:28 +02005519bb_regfree (preg)
Tanguy Pruvot36efc942011-11-20 14:41:41 +01005520 regex_t *preg;
5521{
5522 if (preg->buffer != NULL)
5523 free (preg->buffer);
5524 preg->buffer = NULL;
5525
5526 preg->allocated = 0;
5527 preg->used = 0;
5528
5529 if (preg->fastmap != NULL)
5530 free (preg->fastmap);
5531 preg->fastmap = NULL;
5532 preg->fastmap_accurate = 0;
5533
5534 if (preg->translate != NULL)
5535 free (preg->translate);
5536 preg->translate = NULL;
5537}
5538
5539#endif /* not emacs */