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